Skip to content

Add start, onDatabaseActivated and debugDump extension lifecycle hooks - #3398

Merged
mstomar125 merged 3 commits into
mainfrom
issue-3313-extension-lifecycle
Sep 30, 2026
Merged

mstomar125 merged 3 commits into
mainfrom
issue-3313-extension-lifecycle

Conversation

@mstomar125

@mstomar125 mstomar125 commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Closes #3313

Part of the Pro/core boundary epic (#3298). Adds the lifecycle hooks from ADR-082 §2.5 (proposed) and calls them from core at their final positions, so the Pro-removal issue that follows only has to delete the direct Pro calls. Every existing Pro call stays; with no extension hooks registered, behaviour is unchanged.

What changed

Contract (plugins/ui-extensions.ts). A separate block adds ExtensionLifecycle { start?, onDatabaseActivated? }, and NodespaceExtension gains lifecycle? and debugDump? (placed right after apiVersion, clear of the settings fields that landed in the previous PR).

Dispatch (plugins/extension-lifecycle.ts, new). Plain TypeScript. It imports only ./ui-extensions and the logger, never ui-extensions.svelte.ts, so the database store's import graph stays free of the reactive wrapper (pinned by a source test).

  • startExtensions() calls each start() in registration order. A throw or rejection is logged and the others still start. The returned disposer runs the cleanups in reverse registration order, each isolated (a throw or a rejected promise is logged), and a start() that resolves after disposal has its cleanup run immediately. Cleanups are held per registration slot, so async starts that settle out of order still unwind in reverse registration order.
  • notifyDatabaseActivated(id) calls each hook synchronously in registration order, each isolated. A hook that returns a rejected promise anyway is caught and logged, never unhandled.
  • collectExtensionDebugDumps() returns { [extension id]: debugDump() }, with error: <message> for a throw and error: debugDump must be synchronous for a promise. Every read of extension-owned state (lifecycle, its hooks, debugDump) sits inside a try, so even a throwing getter is isolated.
  • The module doc lists the exact firing points, which are part of the versioned API, and states what is not ordered: start() against the first onDatabaseActivated (the store loads independently of the shell's mount and an async start() is not awaited), and that start() reads the registry once at mount. The hook also does not fire when evicting the previous database's caches throws, because its guarantee is that the eviction completed.

Wiring.

  • app-shell.svelte: stopExtensions = startExtensions() right after the proSync.start() chain in the Tauri-bridge branch, and stopExtensions?.() beside cleanupProSync?.().
  • database.svelte.ts: notifyDatabaseActivated(resolved) at the end of the first-resolution block in load() (after the restore if/else), and notifyDatabaseActivated(id) in switchTo() right after evictAndReloadActiveDatabase() and before clearAllTabs(). It does not fire in browser dev mode, for a superseded switch, or for a later load() that keeps the selection.
  • debug-channel.ts: the store dump gains stores.extensions, serialized one extension at a time through toDumpable, so a dump that cannot be serialized becomes error: <message> for that extension only. The proSync block is untouched. The PII note now mentions extension dumps.

Deviations from the issue (the code differed, or a choice was needed)

  1. collectStoreDump() split out of captureStoreDump(). debugChannelWrite returns early under Vitest, so the dump's content was untestable through captureStoreDump. captureStoreDump now writes what the new exported collectStoreDump gathers; nothing else about it changed.
  2. Fixture lifecycle lives in fixtures/test-extension/lifecycle.ts, not as options on createTestExtension. The settings PR that landed just before this changed createTestExtension's signature, so a separate file avoids touching it, and it keeps createTestExtension() hook-free by default. createTestLifecycleParts({ deferStart, onDatabaseActivated, debugDump }) returns the parts to spread into the overrides, an ordered events log, and releaseStart() for the deferred start.
  3. debugDump returning undefined is recorded as null (JSON has no undefined; JSON.parse(undefined) would otherwise throw and be reported as a misleading error string).
  4. An extension id of __proto__ stays a key in both the dump collection and the store dump (Object.fromEntries rather than assignment).

Tests

  • New tests/plugins/extension-lifecycle.test.ts (27 tests): start order and reverse cleanup, out-of-order async settle, late async start cleaned up immediately, double dispose, throwing / rejecting start, throwing and rejecting cleanup, throwing property getters in all three entry points, non-function start result, hook order and this binding, throwing hook, rejected-promise hook logged, dump keying and error strings (throw, getter, async dump, __proto__ id), no-ops with nothing registered. Source assertions that app-shell.svelte calls startExtensions() inside the Tauri-bridge branch and stopExtensions?.() inside the returned unmount cleanup (brace-matched blocks, each call appearing once), and that the module imports only the registry and the logger.
  • database.test.ts, new describe "extension lifecycle hooks" (13 tests): load() non-default (once, right id, after clearAll and after the whole eviction, active id already committed), load() default (once, no clearAll), switchTo (once, after clearAll, before clearAllTabs), superseded switch, a load() superseded by a tray switch, a switch that never commits, switching to the active database, browser dev mode, a second load(), a throwing hook not aborting load() or the switch, and neither load() nor switchTo() firing the hook when evicting the previous caches throws.
  • debug-channel.test.ts (8 tests): extensions['test-extension'] holds the fixture dump, none registered gives {}, throwing dump, circular dump (and the whole dump stays JSON-serializable), BigInt dump, __proto__ id, Map/Set conversion, undefined to null.

Mutation checks. 42 targeted mutations, each applied to the source with the relevant test file re-run, then reverted; all 42 fail a test. They cover reversed start and cleanup order, cleanups by settle order, dropped late cleanup, missing double-dispose guard, un-caught start / cleanup / hook / dump throws, unhandled start, cleanup, hook and dump rejections, an undetected async dump, property reads moved outside the try in each entry point, unbound this, __proto__ assignment in both the collection and the store dump, a reactive-wrapper import, the app-shell calls removed, moved (the start call out of the bridge branch, the disposer out of the unmount cleanup) and commented out with their text left behind, switchTo notify removed / before eviction / after clearAllTabs / before the routing commit, load() notify removed / before the restore / on every load, either call site swallowing an eviction throw so the hook fires anyway, a browser-mode notify, and the debug block removed / without per-extension isolation / without undefined handling / without toDumpable. Two review rounds tightened the suite: a bare import './ui-extensions.svelte' first slipped past my import-graph regex, and the first app-shell test only pinned that the two calls existed, not where.

Pro-boundary ratchet

BASELINES are not touched. Counts on this branch are identical to origin/main across all 12 markers, so the delta is 0 and nothing here falls under the three classes that may add Pro lines. The one added line that contains a marker is the reflowed PII doc comment in debug-channel.ts, which already named proSync.userEmail.

Verification

  • bun run --cwd packages/desktop-app quality:fix: clean (eslint, design tokens, svelte-check 0 errors).
  • bun run test:changed: passed (frontend Happy-DOM and Chromium). Also test:free-users, and src/tests/plugins with database.test.ts and debug-channel.test.ts.
  • bun run scripts/check-pro-boundary.ts: exit 0.
  • Not run: the manual dev:tauri A to B to A switch and window close. No Tauri window is available in this environment; the behaviour it would show is covered by the store tests above.

🤖 Generated with Claude Code

@mstomar125

Copy link
Copy Markdown
Contributor Author

Pragmatic Code Review: PR #3398 (Closes #3313)

Review Type: Initial Review
Depth: Medium (Pragmatic Quality)
Scope: plugins/extension-lifecycle.ts (new), plugins/ui-extensions.ts, stores/database.svelte.ts (load, switchTo, evictAndReloadActiveDatabase), components/layout/app-shell.svelte, services/debug-channel.ts, and the new tests and fixture. Paths are under packages/desktop-app/src/.

Summary: This is a clean, well-isolated addition. The dispatch module is small and defensive. The two notifyDatabaseActivated call sites sit exactly where the issue asks, and I could not find a path that fires twice or fires for a superseded switch. The findings below are non-blocking improvements. The two most worth doing are (1) an async cleanup that rejects is still unhandled, and (2) the app-shell wiring test does not pin the placement it is meant to pin.


Requirements Check

Start and cleanup

  • startExtensions starts in registration order and cleans up in reverse, including a late start(). Cleanups are held per registration slot (extension-lifecycle.ts:87, :115-122). A start() that settles after disposal runs its cleanup at once (:93). A second dispose is a no-op (:116).
  • A failing start or cleanup does not affect the others (:100-112, :69-75). One caveat is in finding 5.

Database activation

  • Fires once per committed activation. In load() it is at database.svelte.ts:252, after the restore if/else, inside the first-resolution block, guarded by resolved !== null. In switchTo() it is at :466.
  • Never fires in browser dev mode (that branch returns at :178-186, before the block). Never fires for a superseded switch (the seq returns at :446/:449 come first). Never fires for a later load() (the block is entered only while activeDatabaseId === null).
  • In switchTo() it fires (:466) after evictAndReloadActiveDatabase() (:462), whose first step is clearAll(), and before clearAllTabs() (:472).
  • In load() restoring a non-default database it fires after clearAll() (:243 to :252).
  • A throwing hook never aborts the switch or load(). Each hook has its own try/catch. Rejected promises are caught via .then(undefined, …).

Debug dump

  • The store dump gains stores.extensions[<id>] (debug-channel.ts:186-198).
  • A throwing dump, a circular dump and a BigInt dump each become an error: <message> string for that extension only. Verified by reading toExtensionDumpEntry (:120-127). Circular values and Map/Set cycles end in a caught TypeError or RangeError.

No behaviour change

  • With no hooks registered, the only added work is a uiExtensionRegistry.all() copy, plus an empty extensions: {} in the dump.
  • [~] BASELINES are not touched. The issue's literal wording, "BASELINES equal the printed counts", is not met, because five counters sit below their baselines on this branch. I ran scripts/check-pro-boundary.ts read-only: exit 0, and no count is above its baseline. The only added line containing a marker is the reflowed PII comment, which already named proSync.userEmail. Leaving the ceilings alone is consistent with the "tighten when convenient, parallel PRs never rebase just to edit it" rule in CLAUDE.md, so I agree with the choice.
  • The manual dev:tauri A to B to A check was not run. The PR discloses this. The store tests cover the behaviour, but it stays an open acceptance item.
  • I did not re-run the test suites. This was a review-only pass with no writes. Test quality below is judged by reading.

Deviations from the issue (PR body, 1 to 4). All four are sound.

  1. Splitting collectStoreDump out is justified, since debugChannelWrite is a no-op under Vitest. It has one tiny side effect, see finding 6.
  2. Putting the lifecycle fixture in fixtures/test-extension/lifecycle.ts avoids touching createTestExtension's signature after the settings PR changed it. It also keeps the default fixture hook-free.
  3. Recording undefined as null is right, because JSON.parse(undefined) would otherwise report a misleading error.
  4. Keeping __proto__ as a key via Object.fromEntries is right. It has a small test gap, see finding 7.

Code Review Findings

1. [Improvement] An async cleanup that rejects is unhandled, and an async debugDump silently dumps {}

plugins/extension-lifecycle.ts:68-75 and :151-160

Principle: isolation of untrusted callbacks must cover the failure channels the type system allows. start() may return () => void, and TypeScript accepts async () => {…} as that type. runCleanup only catches synchronous throws, so return async () => { await flush(); } that rejects becomes an unhandled promise rejection at app shutdown. notifyDatabaseActivated already handles this case for hooks (:135-139), so the module is inconsistent with itself. The same gap exists for debugDump. An async dump becomes a Promise value, JSON.stringify turns it into {}, and a rejection is unhandled.

Suggestion: reuse the existing guard. In runCleanup:

const result: unknown = cleanup();
if (isThenable(result)) result.then(undefined, (error: unknown) => log.error('Extension cleanup rejected', { extensionId, error }));

In collectExtensionDebugDumps, if the result is thenable, record 'error: debugDump must be synchronous' and attach a no-op catch. Add one test each. Both are small.

2. [Improvement] The app-shell source test does not pin placement, and the PR's "misplaced calls killed" claim does not hold as written

tests/plugins/extension-lifecycle.test.ts:355-360

Principle: a test must fail when the behaviour it names is removed. The test asserts only that the text stopExtensions = startExtensions() and stopExtensions?.() exist somewhere in app-shell.svelte. The acceptance criterion is "runs only when the Tauri bridge is present", and "the disposer runs on unmount". Moving startExtensions() out of the __TAURI_INTERNALS__ branch, or moving stopExtensions?.() out of the returned cleanup, keeps this test green. In dev:browser that would run extensions' start(). I found no other test covering app-shell placement. Removing either call does fail the test.

Suggestion: keep the source-assertion approach, but assert position with index ordering:

const bridge = shell.indexOf('__TAURI_INTERNALS__');
const cleanup = shell.indexOf('return async () =>', bridge);
expect(shell.indexOf('startExtensions()', bridge)).toBeGreaterThan(bridge);
expect(shell.indexOf('startExtensions()', bridge)).toBeLessThan(cleanup);
expect(shell.indexOf('stopExtensions?.()')).toBeGreaterThan(cleanup);

Please also double-check the "misplaced app-shell calls" mutation in the 28-mutation list. By reading, that mutation would survive.

3. [Improvement] The documented contract is silent on the ordering between start() and the first onDatabaseActivated

plugins/extension-lifecycle.ts:14-49 (module doc), database.svelte.ts:252, navigation-sidebar.svelte:136-138

Principle: timing is the API, so state the ordering guarantees you rely on. The doc pins every firing point except how the two hooks relate. Today databaseStore.load() is kicked off from the sidebar's onMount. Svelte runs child mounts before the parent's, so that is before app-shell's startExtensions(). It works because load() awaits IPC (list_databases) first, while startExtensions() runs in the same synchronous flush. Nothing states or tests that. Two consequences an extension author will hit:

  • onDatabaseActivated can run before an async start() has settled. This is the current Pro behaviour, so it is fine, but it should be written down.
  • startExtensions snapshots the registry once (:84, documented), while notifyDatabaseActivated reads it live (:130). An extension registered after the app shell mounted gets activations but never start(), and it misses the activation that already happened.

Suggestion: add two sentences to the module doc: "start() is called before the first activation, but is not awaited; a hook may run while an async start() is pending", and "extensions must be registered before the app shell mounts". If you want a guarantee rather than a timing coincidence, a load()-vs-startExtensions() ordering test is cheap.

4. [Improvement, low likelihood] The hook is skipped if evictAndReloadActiveDatabase() throws after the selection is committed

database.svelte.ts:462-466 (and :243-252 in load())

Principle: a committed state change needs a matching notification, or an explicit statement that it can be lost. The hook fires only if eviction completes. activeDatabaseId and the routing are already committed at that point, so a synchronous throw from any collaborator in eviction skips the hook. Today activateProSync runs before eviction and survives such a throw. Once the follow-up moves that call onto this hook, a throwing eviction would leave cloud sync pointed at the previous database while the UI shows the new one. The failure mode already exists for clearAllTabs() and is very unlikely, since each eviction call is fire-and-forget.

Suggestion: either document it in the "does not fire" list ("or when the eviction throws"), or wrap the eviction so the hook still fires. The current wording, "once per committed activation", is slightly stronger than the code.

5. [Nit] The "never throws" claim has small holes: property reads sit outside the try blocks

plugins/extension-lifecycle.ts:98-99, :131-132, :154

extension.lifecycle, lifecycle.start, lifecycle.onDatabaseActivated and extension.debugDump are read before the try. A getter that throws would escape startExtensions() and break app-shell's onMount, or, from notifyDatabaseActivated, abort switchTo. Extensions are bundled first-party objects, so this is exotic. Still, moving the reads inside the existing try makes the "never throws" wording true for free. While there, new Array<() => void>(n) is typed as a dense (() => void)[] though it is sparse. (() => void) | undefined would make the !== undefined check at :120 honest.

6. [Nit] captureStoreDump now takes its timestamp before the collection instead of after

services/debug-channel.ts:142-143

In the object literal, timestamp: new Date().toISOString() is evaluated before await collectStoreDump(). Previously it was evaluated after all the dynamic imports. It is a few milliseconds and not worth arguing over. If "no behaviour change" is the goal, hoist const stores = await collectStoreDump(); above the write.

7. [Nit] Small test gaps and one brittle test

  • debug-channel.ts:190-195 re-keys with Object.fromEntries, but only collectExtensionDebugDumps has a __proto__ test. A mutation in the debug-channel re-key would survive. One line in debug-channel.test.ts closes it. There is also no BigInt case. The behaviour (an error string for that extension) is correct and cheap to pin.
  • extension-lifecycle.test.ts:362-366 counts notifyDatabaseActivated( occurrences in the store source. The 11 behavioural tests in database.test.ts already pin both call sites and their order, so this grep test adds brittleness (a third legitimate call or a comment fails it) and no coverage. I would drop it.

Verified, no action needed

  • Exactly once, no double fire. From the commit (activeDatabaseId = …) to notifyDatabaseActivated there is no await in either load() or switchTo(), so nothing can interleave. A load() racing a switchTo(), or two concurrent load() calls, ends with only the winner notifying: the loser's superseded() check runs first and returns. Both are covered by tests (does not fire for a load() a tray switch superseded, fires only for the winning switch).
  • Disposer. Each cleanup slot is written at most once for a standard promise (a fulfil or a reject, never both). After disposal the cleanup runs immediately and is never stored, so it cannot run twice. A start that never settles is never cleaned, which is the right default. Reverse order holds for the sync and out-of-order-settle cases. Late-settling cleanups run in settle order, which the doc states.
  • Registry snapshot. Reading all() once for start is the right call, because the disposer must pair with the set that was started. all() returns a copy, so registry mutation during dispatch is safe.
  • Import graph. extension-lifecycle.ts imports only ./ui-extensions and the logger. ui-extensions.ts imports only the svelte type and the logger. No new or circular edge enters database.svelte.ts.
  • Repo rules. No any, no lint suppressions, no raw console.*, no #NNNN in code comments, no Pro wording in added lines beyond the reflowed proSync.userEmail comment.
  • Test quality. The 23, 11 and 6 new tests kill the mutations I could construct by reading: order, out-of-order settle, late cleanup, double dispose, isolation, unbound this, hook placement (before or after clearAll, before clearAllTabs), and default-vs-restore branch. The store tests use the real registry and the real lifecycle module and mock only the store collaborators, so they are not over-mocked.

Recommendation: APPROVE

There are no blockers. Findings 1 and 2 are cheap and worth doing in this PR. Finding 3 is a doc paragraph. Findings 4 to 7 can be taken or left. The manual dev:tauri A to B to A pass is still an open acceptance item for the author or a maintainer to tick off before merge.

@mstomar125 mstomar125 left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated pragmatic-code-review: APPROVE (posted as a comment, GitHub blocks self-approval). Full findings in the review comment above.

@mstomar125

Copy link
Copy Markdown
Contributor Author

Address-review summary (round 1)

Reviewer verdict was APPROVE with seven non-blocking findings. Fixes are in f46db23f.

Addressed (6 of 7, plus half of the 7th)

  • 1. Async cleanup / async debugDump. runCleanup now logs a cleanup that returns a rejected promise. A promise-returning debugDump is recorded as error: debugDump must be synchronous (instead of dumping {}) and its rejection is logged. One test each.
  • 2. App-shell placement test. The test now brace-matches the Tauri-bridge branch and the returned unmount cleanup and asserts stopExtensions = startExtensions() is inside the former and stopExtensions?.() inside the latter, each appearing once. The reviewer was right that my earlier "misplaced calls" claim was not backed by a mutation: the list only had removed calls. Two real placement mutations (start moved out of the branch, disposer moved out of the cleanup) now fail this test, and the PR body is corrected.
  • 3. Ordering docs. The module doc now says nothing orders start() against the first onDatabaseActivated (the store loads independently of the shell's mount; an async start() is not awaited), and that start() reads the registry once at mount.
  • 4. Hook skipped if eviction throws. Documented, not wrapped. The hook's stated guarantee is "after the previous database's caches were evicted", so not firing when eviction throws is consistent with it, and the store already records the error on that path. Wrapping would fire the hook on a state where that guarantee is false. Revisit if a future extension needs to be told about a half-failed switch.
  • 5. "Never throws" holes. Every read of extension-owned state (lifecycle, its hooks, debugDump) is now inside the existing try in all three entry points; cleanup slots are typed (() => void) | undefined. Getter tests for each entry point.
  • 6. Timestamp order. captureStoreDump collects the stores first and takes its timestamp after, as before.
  • 7. Test gaps. Added the __proto__-id and BigInt cases to debug-channel.test.ts. Dropped the notifyDatabaseActivated( occurrence-count test: the 11 store tests already pin both call sites and their order, so it only added brittleness.

Not addressed: the manual dev:tauri A to B to A pass. No Tauri window is available in this environment; the store tests cover the behaviour. It remains an open acceptance item for a maintainer with a desktop session.

Verification after the fixes: quality:fix clean, test:changed and the targeted suites pass (387 tests in plugins, database and debug-channel), ratchet exit 0 with counts unchanged from origin/main. Mutation suite is now 38 mutations, all killed.

Re-Review Decision

Decision: RE-REVIEW NEEDED

Rationale: The fixes change logic in the dispatch module (rejection handling for cleanups and dumps, property reads moved inside the try blocks) and rewrite the placement test, rather than being style or doc-only. A focused re-review of 8b65a763..f46db23f should confirm the async-dump and getter handling and that the new placement test cannot be satisfied by a misplaced call.

@mstomar125

Copy link
Copy Markdown
Contributor Author

Pragmatic Code Review: PR #3398 (Closes #3313), re-review of 8b65a763..f46db23f

Review Type: Re-Review
Depth: Medium (Pragmatic Quality)
Scope: only commit f46db23f ("Address review: isolate async cleanups and dumps, pin app-shell placement"). Paths are under packages/desktop-app/src/.

Previous Review Summary: 7 recommendations (all non-blocking). 7 addressed, 0 not addressed, 4 new findings (all [Nit], none blocking).

I did not re-run the suites: this was a read-only pass. For the placement test I replayed its exact logic (same regex, same blockAt) in a throwaway node script against in-memory mutated copies of app-shell.svelte, with no repo writes. Results are in finding 2.


Status of the round-1 findings

1. Async cleanup / async debugDump: Addressed, holds.

  • extension-lifecycle.ts:82-93: runCleanup now attaches result.then(undefined, …) and logs Extension cleanup rejected. A sync throw is still logged as Extension cleanup threw. The two paths are exclusive, so nothing is reported twice.
  • :172-189: a thenable debugDump result is recorded as error: debugDump must be synchronous and its rejection is logged through an attached handler, so it cannot go unhandled. The entries.push sits after the .then(...) call. If an exotic thenable's then throws, the catch records one error entry and there is no double push.
  • The function is still invoked on every capture, so its side effects run. That is unavoidable, and the type doc (ui-extensions.ts:144-149) and the module doc both already say "synchronous".
  • Both new tests are non-vacuous. Without the guard, the rejection goes unhandled and the log.error assertion fails. flush()'s 5 microtask ticks are enough, since a .then on an already-rejected promise settles in one tick.

2. App-shell placement test: Addressed for the mutations that matter, with residual gaps (finding N1).

  • The regex /\.__TAURI_INTERNALS__\s*\)\s*\{/ matches exactly one place in the real file, app-shell.svelte:255-256, which is the if (typeof window …) branch. The other occurrence, at :87, is … .__TAURI_INTERNALS__) return; and has no {, so it cannot match.
  • The naive brace matcher is correct on the real source. It resolves the branch to 256 -> 429, where line 429 is the } of } else {. The cleanup resolves to 576 -> 631, the }; that closes return async () => {. There are no unbalanced braces in strings, comments or regexes in either block today. The first return async () => { after the branch is the unmount cleanup, because the other one (:200) sits before the branch.
  • If a stray brace in a string or comment appears later, the realistic result is a loud failure, not a false pass.
  • Replayed mutations:
Mutation Result
start moved before the Tauri if fails
start moved into the browser else fails
disposer moved after the returned cleanup fails
disposer moved to mount time, before the return fails
a commented-out call with its text left (// stopExtensions = startExtensions();, and the same for the disposer) passes
start moved into a listen(...) callback inside the branch passes
disposer moved into a dead if (false) { … } inside the cleanup passes
  • The two placements round 1 asked about (start outside the Tauri branch, disposer outside the unmount cleanup) are now pinned, and so are their obvious variants. The residual classes are in N1.

3. Ordering docs: Addressed, and true.

  • navigation-sidebar.svelte:136-137 calls databaseStore.load() from its own onMount. database.svelte.ts:675 also retries load() on daemon reconnect, and database-settings.svelte:31 calls it too. So the store does load independently of the shell's mount.
  • load() awaits IPC before it commits, and an async start() is never awaited. "Nothing orders start() against the first onDatabaseActivated" is therefore accurate, and deliberately weaker than the coincidental sync ordering.
  • startExtensions() reads uiExtensionRegistry.all() once (:102). notifyDatabaseActivated reads it live (:150). "Registered later receives activations but never start()" is correct.

4. Hook not fired when eviction throws: Addressed as documentation, and the doc is true.

  • In load() (database.svelte.ts:243-252) and switchTo() (:462-466), evictAndReloadActiveDatabase() is a run of sync calls, and notifyDatabaseActivated is the next statement. A throw skips it, and both catch blocks (:254-256, :484-486) set this.error. In switchTo, clearAllTabs() is skipped too.
  • I accept the author's rationale for documenting rather than wrapping: the hook's guarantee is "eviction completed", and wrapping would fire it in a state where that is false.
  • The behaviour is now stated as part of a versioned contract but is not pinned by a test (N3).

5. Reads of extension-owned state inside the try: Addressed, with one over-claim (N2).

  • extension.lifecycle, lifecycle.start, lifecycle.onDatabaseActivated and extension.debugDump are all read inside the try in all three entry points. The cleanup slot type is (() => void) | undefined, which makes the !== undefined check at :139-140 honest.
  • No behaviour regression from moving the reads in. return inside the forEach callback's try returns from that callback only, and continue inside try in a for…of is fine. There is no finally.
  • A throwing debugDump getter is now recorded as error: getter failed for that extension only. Before, it aborted the whole extensions section.
  • The three getter tests are non-vacuous: register() reads only id, apiVersion and the contribution arrays, so the hostile extension really is registered. Each test also asserts the healthy neighbour still ran.

6. Timestamp order: Addressed. debug-channel.ts:139-141 collects the stores first and then stamps, as before.

7. Test gaps: Addressed.

  • debug-channel.test.ts gains __proto__ and BigInt cases. The __proto__ test uses an object value, so an assignment-style re-key would rewrite the prototype and fail it. Its afterEach unregisters __proto__. The BigInt case matches /^error: .*BigInt/i, and the message contains "BigInt" on V8 and JSC.
  • The 11 store tests in database.test.ts:861-1043 do pin both call sites. Removing the load() notify fails the first two tests. Removing the switchTo notify fails the third. Ordering against clearAll, pinNodes and clearAllTabs is pinned. The dropped grep-count test lost nothing.

New findings (most severe first)

N1. [Nit] The placement test is text-based, so three misplacements still pass

tests/plugins/extension-lifecycle.test.ts:454-472

Principle: a test should fail when the behaviour it names is removed.

  • A call that is commented out but leaves its text behind still satisfies the toMatch, toContain and toHaveLength(1) checks. "Comment the line out while debugging" is the realistic way to break this.
  • A startExtensions() moved into a nested event callback inside the branch, or a stopExtensions?.() moved into a nested dead block inside the cleanup, also passes.
  • The last two are far less likely, and the brace-matching approach has real value, so I would only fix the first.

Suggestion: strip comments from shell before matching, for example shell.replace(/\/\*[\s\S]*?\*\/|(?<![:'"])\/\/[^\n]*/g, ''). If you want it fully robust, parse the <script> with the typescript package that is already in node_modules. The naive brace matcher is fine as it stands.

N2. [Nit] "Every read of extension-owned state sits inside the try" over-claims: extension.id is still read outside it

plugins/extension-lifecycle.ts:125, :131, :140, :157, :161, :180, :187, and the comment at :116-117

The catch blocks, the .then callbacks and the disposer loop (extensions[index].id, :140, outside any try) read id directly. The registry already reads ext.id as a plain string at registration (ui-extensions.ts:252-256), so the realistic risk is nil. The only consequence would be one throwing id getter aborting the rest of the unmount loop.

Suggestion: soften the comment to "every read of lifecycle, its hooks and debugDump", or drop the concern. Nothing else is needed.

N3. [Nit] The now-documented "no fire when eviction throws" behaviour is not pinned by a test

database.svelte.ts:243-252 and :462-466, module doc extension-lifecycle.ts:41-45

Principle: a documented part of a versioned contract should have a test. Make the mocked clearAll throw once, then assert in one load() restore case and one switchTo case that the hook did not fire and databaseStore.error is set. That is about 20 lines and stops a later "helpful" wrap of the eviction from silently changing the contract.

N4. [Nit] The module doc does not say an async cleanup is not awaited

plugins/extension-lifecycle.ts:24-28

The doc now says a rejected cleanup promise is logged. It could add that the promise is not awaited, so the next (earlier-registered) cleanup starts immediately and reverse-order teardown holds only for each cleanup's synchronous part. Extension authors could otherwise assume strict sequential teardown.


Repo rules and other checks

  • No any, no lint suppressions, no raw console.*, no #NNNN in added code lines, and no Pro wording in the added lines. I scanned the diff mechanically. The one #3298 mention is in the PR body, not in code.
  • Tests: the new lifecycle tests are non-vacuous, as detailed above. There is no over-mocking, since the store tests use the real registry and the real lifecycle module.
  • The PR body's corrected mutation claim and the 38-mutation figure are consistent with the diff. The two placement mutations it names (start out of the branch, disposer out of the cleanup) do fail the new test, as replayed above.
  • The manual dev:tauri A to B to A pass is still an open acceptance item, as the author discloses. It is unchanged and not a blocker for this commit.

Recommendation: APPROVE

All seven round-1 findings are genuinely addressed, and the new async and getter handling is correct: no double-reporting, no unhandled rejections, and no loop-semantics regressions. The placement test now catches the misplacements that matter. N1 to N4 are optional nits, and N1's comment-stripping is the only one I would consider doing before merge.

@mstomar125 mstomar125 left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated pragmatic-code-review (re-review): APPROVE (posted as a comment, GitHub blocks self-approval). Full findings in the review comment above.

@mstomar125

Copy link
Copy Markdown
Contributor Author

Address-review summary (round 2, re-review of f46db23f)

The re-review verdict was APPROVE: all seven round-1 findings confirmed fixed, plus four optional nits. All four are taken in a3e657df; they touch tests and comments only, no production logic.

  • N1 (placement test passes on a commented-out call). The test strips comments before matching, so // stopExtensions = startExtensions(); no longer satisfies it. Both commented-out mutations now fail it. The other two residual classes the reviewer replayed (a call moved into a nested callback inside the branch, or into a dead block inside the cleanup) are left as they are: a text-level check cannot pin them without parsing the file, and both are unlikely edits.
  • N2 (comment over-claims). The comment now names only the reads it guards (lifecycle and its hooks). extension.id is a validated string from registration, so it stays outside the try.
  • N3 (eviction-throw not pinned). Two store tests, one for load() and one for switchTo(), make clearAll throw and assert the hook did not fire and the store recorded the error (and that clearAllTabs did not run in the switch). Wrapping the eviction at either call site fails them.
  • N4 (async cleanup not awaited). The module doc says so, and that reverse order holds for each cleanup's synchronous part only.

Verification: quality:fix clean, test:changed passed (frontend and Chromium), ratchet exit 0 with counts unchanged from origin/main. Mutation suite is 42 mutations, all killed. PR body updated to match.

Not done: the manual dev:tauri A to B to A pass (no Tauri window in this environment); it remains an open acceptance item for a maintainer with a desktop session.

Re-Review Decision

Decision: NO RE-REVIEW NEEDED

Rationale: The commit changes only test assertions, two new store tests and comments, no production logic, and each change is mutation-verified. The reviewer had already approved the logic changes in f46db23f.

mstomar125 and others added 3 commits September 30, 2026 14:40
An extension can now carry `lifecycle: { start, onDatabaseActivated }` and a
top-level `debugDump`. `plugins/extension-lifecycle.ts` dispatches them in
registration order, each isolated so a throw or rejection is logged and never
stops the host or the other extensions.

- The app shell calls `startExtensions()` in its Tauri-bridge branch and runs
  the disposer on unmount. Cleanups run in reverse registration order, and a
  `start()` that settles after disposal has its cleanup run immediately.
- The database store calls `notifyDatabaseActivated(id)` on the first
  resolution in `load()` (after the restore branch) and in `switchTo()` right
  after the previous database's caches are evicted and before the workspace
  reset. It does not fire in browser dev mode, for a superseded switch, or for
  a later `load()` that keeps the selection.
- The debug channel's store dump records each extension's dump under
  `extensions[<id>]`, serialized one extension at a time so an unserializable
  dump costs only its own entry. `captureStoreDump` now writes what the new
  exported `collectStoreDump` gathers.

With no hooks registered, behaviour is unchanged. The test extension gains a
recording lifecycle and dump in `fixtures/test-extension/lifecycle.ts`.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…ment

- runCleanup logs a cleanup that returns a rejected promise, matching how
  start and onDatabaseActivated are already handled.
- collectExtensionDebugDumps records a promise-returning debugDump as
  `error: debugDump must be synchronous` and logs its rejection instead of
  dumping `{}`.
- Every read of extension-owned state (lifecycle, its hooks, debugDump) now
  sits inside the try block, so a throwing getter is isolated too. The
  cleanup slots are typed as possibly-empty.
- The module doc states that nothing orders start() against the first
  onDatabaseActivated, that start() reads the registry once at mount, and
  that the hook does not fire when eviction throws.
- captureStoreDump collects the stores before taking its timestamp, as before.
- The app-shell test now asserts the start call is inside the Tauri-bridge
  branch and the disposer inside the returned unmount cleanup, by brace-matched
  blocks. The grep-count test on the database store is dropped: the store
  tests already pin both call sites and their order.
- New tests: async cleanup rejection, throwing getters for all three entry
  points, async dump, BigInt dump, and a __proto__ id through the store dump.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…-throw

- The app-shell placement test strips comments first, so a call that is
  commented out with its text left behind no longer satisfies it.
- Two store tests pin that neither load() nor switchTo() fires the hook when
  evicting the previous caches throws, and that the store records the error.
- The lifecycle module doc says an async cleanup is not awaited, and the
  comment on guarded reads names only what it guards.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add start, onDatabaseActivated and debugDump extension lifecycle hooks

1 participant