Repository navigation
Add start, onDatabaseActivated and debugDump extension lifecycle hooks - #3398
Conversation
Pragmatic Code Review: PR #3398 (Closes #3313)Review Type: Initial Review Summary: This is a clean, well-isolated addition. The dispatch module is small and defensive. The two Requirements CheckStart and cleanup
Database activation
Debug dump
No behaviour change
Deviations from the issue (PR body, 1 to 4). All four are sound.
Code Review Findings1. [Improvement] An async cleanup that rejects is unhandled, and an async
|
mstomar125
left a comment
There was a problem hiding this comment.
Automated pragmatic-code-review: APPROVE (posted as a comment, GitHub blocks self-approval). Full findings in the review comment above.
Address-review summary (round 1)Reviewer verdict was APPROVE with seven non-blocking findings. Fixes are in Addressed (6 of 7, plus half of the 7th)
Not addressed: the manual Verification after the fixes: Re-Review DecisionDecision: 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 |
Pragmatic Code Review: PR #3398 (Closes #3313), re-review of
|
| 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-137callsdatabaseStore.load()from its ownonMount.database.svelte.ts:675also retriesload()on daemon reconnect, anddatabase-settings.svelte:31calls it too. So the store does load independently of the shell's mount.load()awaits IPC before it commits, and an asyncstart()is never awaited. "Nothing ordersstart()against the firstonDatabaseActivated" is therefore accurate, and deliberately weaker than the coincidental sync ordering.startExtensions()readsuiExtensionRegistry.all()once (:102).notifyDatabaseActivatedreads it live (:150). "Registered later receives activations but neverstart()" is correct.
4. Hook not fired when eviction throws: Addressed as documentation, and the doc is true.
- In
load()(database.svelte.ts:243-252) andswitchTo()(:462-466),evictAndReloadActiveDatabase()is a run of sync calls, andnotifyDatabaseActivatedis the next statement. A throw skips it, and bothcatchblocks (:254-256,:484-486) setthis.error. InswitchTo,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.onDatabaseActivatedandextension.debugDumpare all read inside thetryin all three entry points. The cleanup slot type is(() => void) | undefined, which makes the!== undefinedcheck at:139-140honest.- No behaviour regression from moving the reads in.
returninside theforEachcallback'stryreturns from that callback only, andcontinueinsidetryin afor…ofis fine. There is nofinally. - A throwing
debugDumpgetter is now recorded aserror: getter failedfor that extension only. Before, it aborted the whole extensions section. - The three getter tests are non-vacuous:
register()reads onlyid,apiVersionand 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.tsgains__proto__and BigInt cases. The__proto__test uses an object value, so an assignment-style re-key would rewrite the prototype and fail it. ItsafterEachunregisters__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-1043do pin both call sites. Removing theload()notify fails the first two tests. Removing theswitchTonotify fails the third. Ordering againstclearAll,pinNodesandclearAllTabsis 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,toContainandtoHaveLength(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 astopExtensions?.()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 rawconsole.*, no#NNNNin added code lines, and no Pro wording in the added lines. I scanned the diff mechanically. The one#3298mention 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:tauriA 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
left a comment
There was a problem hiding this comment.
Automated pragmatic-code-review (re-review): APPROVE (posted as a comment, GitHub blocks self-approval). Full findings in the review comment above.
Address-review summary (round 2, re-review of
|
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]>
a3e657d to
b352d44
Compare
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 addsExtensionLifecycle { start?, onDatabaseActivated? }, andNodespaceExtensiongainslifecycle?anddebugDump?(placed right afterapiVersion, clear of the settings fields that landed in the previous PR).Dispatch (
plugins/extension-lifecycle.ts, new). Plain TypeScript. It imports only./ui-extensionsand the logger, neverui-extensions.svelte.ts, so the database store's import graph stays free of the reactive wrapper (pinned by a source test).startExtensions()calls eachstart()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 astart()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() }, witherror: <message>for a throw anderror: debugDump must be synchronousfor a promise. Every read of extension-owned state (lifecycle, its hooks,debugDump) sits inside a try, so even a throwing getter is isolated.start()against the firstonDatabaseActivated(the store loads independently of the shell's mount and an asyncstart()is not awaited), and thatstart()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 theproSync.start()chain in the Tauri-bridge branch, andstopExtensions?.()besidecleanupProSync?.().database.svelte.ts:notifyDatabaseActivated(resolved)at the end of the first-resolution block inload()(after the restore if/else), andnotifyDatabaseActivated(id)inswitchTo()right afterevictAndReloadActiveDatabase()and beforeclearAllTabs(). It does not fire in browser dev mode, for a superseded switch, or for a laterload()that keeps the selection.debug-channel.ts: the store dump gainsstores.extensions, serialized one extension at a time throughtoDumpable, so a dump that cannot be serialized becomeserror: <message>for that extension only. TheproSyncblock is untouched. The PII note now mentions extension dumps.Deviations from the issue (the code differed, or a choice was needed)
collectStoreDump()split out ofcaptureStoreDump().debugChannelWritereturns early under Vitest, so the dump's content was untestable throughcaptureStoreDump.captureStoreDumpnow writes what the new exportedcollectStoreDumpgathers; nothing else about it changed.fixtures/test-extension/lifecycle.ts, not as options oncreateTestExtension. The settings PR that landed just before this changedcreateTestExtension's signature, so a separate file avoids touching it, and it keepscreateTestExtension()hook-free by default.createTestLifecycleParts({ deferStart, onDatabaseActivated, debugDump })returns the parts to spread into the overrides, an orderedeventslog, andreleaseStart()for the deferred start.debugDumpreturningundefinedis recorded asnull(JSON has noundefined;JSON.parse(undefined)would otherwise throw and be reported as a misleading error string).__proto__stays a key in both the dump collection and the store dump (Object.fromEntriesrather than assignment).Tests
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 andthisbinding, throwing hook, rejected-promise hook logged, dump keying and error strings (throw, getter, async dump,__proto__id), no-ops with nothing registered. Source assertions thatapp-shell.sveltecallsstartExtensions()inside the Tauri-bridge branch andstopExtensions?.()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, afterclearAlland after the whole eviction, active id already committed),load()default (once, noclearAll),switchTo(once, afterclearAll, beforeclearAllTabs), superseded switch, aload()superseded by a tray switch, a switch that never commits, switching to the active database, browser dev mode, a secondload(), a throwing hook not abortingload()or the switch, and neitherload()norswitchTo()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,undefinedtonull.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,switchTonotify removed / before eviction / afterclearAllTabs/ 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 / withoutundefinedhandling / withouttoDumpable. Two review rounds tightened the suite: a bareimport './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
BASELINESare not touched. Counts on this branch are identical toorigin/mainacross 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 indebug-channel.ts, which already namedproSync.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). Alsotest:free-users, andsrc/tests/pluginswithdatabase.test.tsanddebug-channel.test.ts.bun run scripts/check-pro-boundary.ts: exit 0.dev:tauriA 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