Implicit State Machines in Seed — Audit, 2026-11-03

What this is

A survey of the implicit state machines in the desktop app, the web app, and the vault — places where behavior is governed by a set of discrete modes and transitions between them, but where those modes are encoded indirectly (boolean clusters, nullable fields, useRef latches, generation counters, setTimeout sequencing, nullable DB timestamps) instead of as one explicit state with declared transitions.

It is an audit, not a proposal to rewrite anything. Each finding ends with a verdict: model it explicitly, fix it differently, or leave it alone. A meaningful number of findings get "leave it alone" or "this is a bug, not a missing abstraction" — a hand-rolled phase is only worth replacing when the replacement removes reachable wrong states.

What counts as an implicit state machine

Signals used throughout:

    clusters of booleans mutated from several call sites, where combinations like isSubmitting && error && success are representable

    useRef(false) latches, "once" guards, in-flight/lock flags, module-level mutable maps with implicit entry lifetimes

    ad-hoc status strings written in many places with no exhaustive handling of transitions

    generation/revision counters used to discard stale async results

    effect chains where one state change exists only to trigger setting another

    phase encoded in nullable timestamps or in "which of these three fields is set"

    setTimeout as a transition, polling loops with their own timeouts, retry/backoff

    the strongest signal: a defensive re-check, a comment explaining a transition rule, or a regression test named after the scenario that broke. Nearly every top finding below has all three.

Baseline: what is already explicit

The repo already uses XState v5 (xstate@5.19.2, @xstate/react@4.1.3), so this is not a greenfield question — it's a question of where the existing pattern should be extended.

Declared in frontend/packages/shared, frontend/apps/desktop, frontend/packages/editor. Existing machines:

Machine

Lines

frontend/packages/shared/src/models/document-machine.ts

2318

frontend/packages/shared/src/models/document-card-cleanup-machine.ts

991

frontend/packages/editor/src/mention-menu-machine.ts

335

frontend/packages/shared/src/models/document-creation-machine.ts

190

Plus use-document-machine.ts, use-editor-gate.ts, document-machine-inspect.ts, the debug drawer, and the desktop/web wrappers (app-document-card-cleanup-machine.ts, web-document-actors.ts, web-document-card-cleanup.ts).

Two dependency facts that affect the recommendations:

    The web app uses XState without declaring it. frontend/apps/web/package.json has no xstate entry; it resolves transitively through @shm/shared. Three web files import it. Any new web machine should come with an explicit dependency.

    The vault has no XState at all. vault/package.json uses valtio + react-router-dom and pulls xstate only transitively via the file: dependency on @shm/shared. The vault is a separate Bun workspace with its own React version pinning. Modeling vault flows explicitly means either adding the dependency deliberately or writing a plain typed reducer — see the open questions.

Coverage and method

Twelve parallel read-only passes, partitioned so no two overlapped:

Pass

Scope

1

desktop Electron main process (main.ts, app-*.ts, daemon, auto-update, IPC)

2

desktop embedded browser, scraper, WXR import

3

desktop src/components/** + draft-status.tsx, sidebar-context.tsx

4

desktop src/models/**, src/utils/**, client/subscription top-level files

5

desktop src/pages/**, root.tsx, app context/IPC

6

web app/document-edit/**, local DBs, commenting, drafts

7

web auth/session/registration/invites + app/routes/hm.*

8

web site/hosting/domain admin, assistant/agents, resource pages, loaders

9

vault frontend (router, store, views, components)

10

vault backend (schema, api-service, session, challenges, email)

11

frontend/packages/shared/src/models/** (shared by desktop + web)

12

frontend/packages/ui + frontend/packages/editor (shared by desktop + web)

Passes 11 and 12 are outside the literal "desktop/web/vault apps" boundary, but most app-level flow logic lives there and is rendered by both apps, so excluding them would have produced a misleading picture. Findings from those passes are marked (shared).

Backend Go code was not in scope. It has its own explicit state handling (backend/blob/reindex.go, backend/hmnet/syncing/**) worth a separate pass.

The headline: several of these machines exist two or three times

The single most actionable result of this audit isn't any individual finding. It's that the largest implicit machines are implemented independently in desktop and web — same domain concept, divergent encodings, divergent bug histories, divergent test coverage.

Domain concept

Desktop implementation

Web implementation

Publish saga (probe → publish → post-commit)

src/models/documents.ts (usePublishResource, ~320 lines)

app/document-edit/web-document-actors.ts (publishWebDocument, ~300 lines)

Hosting session + pending domains + site-move intent

src/models/host.ts, host-session.ts

app/models/host.ts (polls and transitions inside a queryFn)

Comment draft/submit lifecycle

src/components/commenting.tsx

app/commenting.tsx + comment-draft-utils.ts

Deferred intent after auth

— (desktop auths in-process)

app/pending-intent.ts + invite-join.ts (two parallel mechanisms)

Draft placeholder/kind resolution

src/pages/desktop-resource.tsx, models/drafts.ts

app/document-edit/web-draft-path.ts, web-draft-shell.ts

Maintenance enqueue → release saga

src/models/documents.ts

4 separate call sites in app/**

The third column of effort — a third implementation of the comment composer lifecycle — lives in frontend/packages/editor/src/comment-editor.tsx.

Implication: the highest-leverage move is not "add machines to desktop" and "add machines to web" in parallel. It's to model each of these once in @shm/shared and have both apps drive it, the way document-machine.ts already is. Doing it per-app would double the surface we are trying to shrink.

Tier 1 — model these explicitly

1. Vault auth/sign-up flow orchestration

App: vault frontend. Verdict: model explicitly. This is the clearest case in the repo.

The entire sign-in/sign-up/delegation/invite flow is one machine encoded as a tuple of ~8 nullable Valtio store fields plus three sessionStorage keys plus module-closure flags plus useRef latches in individual views. Which screens are reachable is never declared — it emerges from guards in router.tsx and ~15 imperative navigator.go() calls scattered through store actions.

States (reachable screen graph, abbreviated): root → {enterprise-site-signin, invite-via-site-signin, invited, locked, pending-flow, pre-login}; pre-login → login | verify-pending; login → password | passkey | recover; verify-pending → auth-choose → password-set | passkey → recovery → identity-secured → pending flow; plus delegate, connect, connect-success, settings, no-recovery, identity-recovered.

Encoding: sessionChecked, session?.authenticated, decryptedDEK, inviteCode/inviteStatus, delegationRequest, vaultConnectionRequest, returnToPath, inviteOnly, returnedFromSiteSignIn.

Files:

    vault/src/frontend/router.tsx — guards at 42–434, route table 437–546

    vault/src/frontend/store.ts — getPendingFlowPath 60–73, navigation calls at 830, 882, 904, 924, 968, 1119, 1206, 1303, 1580, 2225, 2239, 2417

    vault/src/frontend/views/DelegateView.tsx, PreLoginView.tsx, EnterprisePreLoginView.tsx

Why this one first:

    Three independent useRef latches exist only to paper over transition races, each with a comment saying so: targetRef ("store updates notify asynchronously", router.tsx:47–66), hadRequestRef in two places ("redirecting to '/' then would win the race", router.tsx:405–419 and DelegateView.tsx:38–63).

    A TODO at router.tsx:441-442 admits the guards are insufficient: users can reach routes "without having a session, and see a half-baked page". Impossible states are reachable today.

    Six regression tests are each defending one transition: login-reload, settings-deeplink (with 100 ms settle sleeps), connect-success (named "routing repro"), invite-only, choose-auth ("leaving sign-up early"), delegation-registration-loop.

    returnToPath is written and cleared from four different effects plus a ?next= query-param side channel.

    consumeSiteSignInReturn() is read once, inside createRouter() — a one-shot flag baked into router construction.

2. Web sign-in round trip through the vault

App: web. Verdict: model explicitly, jointly with #1 — they are two halves of one protocol.

States: anonymous → delegation-armed (session key + authState + return URL persisted to IndexedDB, browser leaves for the vault) → callback-received → identity-stored → site-session-pending → signed-in | error | signed-out, with pending-intent and hostingReturn forking the terminal transition.

Files:

    frontend/apps/web/app/routes/hm.auth.callback.tsx (42–224)

    frontend/apps/web/app/auth-session.ts (startAuth 100–148, handleCallback 156–287)

    frontend/apps/web/app/auth.tsx (174–206, 347–374)

Evidence:

    Dedup is a module-level Map keyed by URL (inFlightAuthCallbacks, completedAuthCallbacks, lines 28–29) that survives StrictMode remounts and leaks entries forever.

    The membership probe is fired and deliberately not awaited; the toast variant (welcome-back vs login) depends on which lookup settles first, with a comment admitting it ("read whichever toast lookups have settled", 176–180).

    Two navigation primitives chosen by convention: navigate(replace) vs window.location.replace, because a client transition "can retain the signed-out header/account queries".

    __tests__/auth-callback-navigation.test.tsx is 204 lines of pinned transitions.

Closely coupled, same cluster:

    Local identity/session composite — the phase is re-derived independently in four places: server cookie presence, client keyPair, the keyPairLoaded gate, and HTTP error-text sniffing (message.includes(' 403 ') decides "not a member", routes/hm.sign-in.tsx:71-76). auth.tsx:71-74 documents that logged-out and still-loading are indistinguishable.

    Daemon auth refresh loop — five module-level variables (daemonAuthRefresh, lastAuthenticatedKeyPairId, daemonAuthExpiresAt, authGeneration, authAbortController) in app/universal-client.tsx:28-156, with a generation compare-and-set inside .then and a compensating DELETE if the identity changed mid-flight. No timeout and no failed state: a hung refresh holds the latch forever.

3. The publish saga (both apps, two implementations)

Apps: both, separately. Verdict: model once in @shm/shared; this is the highest-value consolidation.

Desktop phases: probe destination (exists | missing | redirect-takeover) → resolve path → enqueue parent-maintenance job (awaitingPrimary) → publish → release job → refetch published doc (indexed | synthesize-fallback) → invite-after-publication gate → invalidation fan-out.

Web phases: prepare → maybe-bootstrap-genesis → prepare-change → sign → enqueue-followups → publish → post-commit (resolve-with-retry / cleanup drafts / invalidate).

Files:

    frontend/apps/desktop/src/models/documents.ts:264-589 — phase locals existingDocVersion, destinationIsMissing, takesOverRedirect (299–335); parentMaintenanceJobId spanning an await (472–495); a 7-condition inviteAfterPublication conjunction (458–470)

    frontend/apps/web/app/document-edit/web-document-actors.ts:298-604

Evidence, quoting the web implementation directly:

    L505–508: "CRITICAL: never throw here. Throwing after a successful publish would send the machine back to editing… the Publish button stays green/visible even though the publish succeeded." A phase boundary with different error semantics, enforced by a comment.

    RETRY_DELAYS_MS = [150, 300, 500, 800, 1200] for "the daemon has not indexed the new version yet" — retry-with-sleep, which the repo's own coding guidelines warn about.

    deleteAllDocumentDrafts exists because "an autosave racing ahead of the assigned draftId mints a fresh nanoid" — an unmodeled race that produced duplicate draft identities.

    Desktop equivalent synthesizes an HMDocument by hand when the publish succeeded but isn't indexed, with the comment "never a synthetic version" (507–521), and overwrites destinationIsMissing in a catch because "a successful resource probe takes precedence over a stale gRPC miss".

    Both sides carry leftover console.log('[publish]…') instrumentation.

Tests on both sides are named after the bugs: "resolves (does not throw) when the daemon has not yet indexed the new version after publish", "publish removes stray orphan drafts for the same doc", "does not invite when the content publication fails after creating the home genesis".

4. Hosting session, pending custom domains, and durable site-move intent

Apps: both, two implementations. Verdict: model once in @shm/shared.

The web version is the starker one: the state machine executes inside a react-query queryFn. domainStatus (frontend/apps/web/app/models/host.ts:639-740) polls every 20 s, and inside the query function it iterates pending domains, calls the host API, and writes state transitions — 'Active' → publishing → updateMovedSitePublication → delete record, or → error.

States per domain: waiting-dns → initializing → publishing | error → terminal; orthogonal to a cancelingDomains set, a domainPublications in-flight map, and the hosting-session generation.

Files:

    frontend/apps/web/app/models/host.ts:142-268, 531-740

    frontend/apps/web/app/components/web-hosting.tsx:845-1064 (a ~10-branch if/else ladder mapping state to view)

    frontend/apps/desktop/src/models/host.ts:116-413, host-session.ts

Evidence:

    assertSession(generation) is called three times around every API call, plus after every async hop. The encoding evolved from a numeric authVersion to a UUID authGeneration because the numeric version already failed — there is a regression test named "never restores an old login when clearing storage reuses the same numeric auth version".

    signal?.aborted, cancelingDomains.has(), readState().pendingDomains.some(...) are sprinkled after every await: defensive re-validation standing in for enforced transitions.

    web-hosting.tsx:991-999 reconciles local status against serverDomain.status with a nested ternary, with a fallback branch for "this domain is active, but it is not the current published address".

    host.test.tsx (779 lines, 24 cases) reads as a bug history: "cancels a pending domain without publishing an Active response that arrives afterwards", "does not adopt a late DNS response after hosting logout", "keeps failed domain publication recoverable, then clears it only after a successful retry".

Site-move intent is the same pattern at a smaller scale, also duplicated: a PendingSiteMove record is written to persistent storage before the API call so a crash leaves a recoverable breadcrumb, then recoverSiteMove re-derives the phase by comparing the server's name against oldName/newName. On the UI side, movedUrl is a nullable string encoding "the hosting move succeeded but the publication update didn't — Retry should only update metadata" (desktop/src/components/hosted-site-settings.tsx:55, web/app/components/web-hosting.tsx:79). This is a hand-rolled two-phase commit.

5. Daemon process lifecycle + app startup phases

App: desktop main process. Verdict: model explicitly; it has already shipped a bug.

GoDaemonState is a tagged union ({t: 'startup' | 'ready' | 'error' | 'migrating'}) — so this is a partial machine. What's implicit is the process side and the startup choreography around it: stopped → spawning → grpc-waiting → migrating(completed/total) → http-health-checking → ready → error → killing → restarting, crossed with an "expected vs unexpected close" dimension.

Encoding: currentDaemonProcess, expectingDaemonClose (daemon.ts:90-91), the isGrpcReady latch (app-grpc.ts:12), and three local flags in main.ts:197-269 (loadingWindowShown, daemonIsPolling, unsubscribe) that interpret two successive 'ready' events as "first ready = gRPC up, second ready = ACTIVE" — sequencing purely by event-ordering convention.

Files: frontend/apps/desktop/src/daemon.ts, daemon-readiness.ts, main.ts:86-89, 197-269, 355-409, app-grpc.ts.

Evidence:

    Two different producers set t:'ready' with different meanings: a stderr log line match on "DaemonStarted" (daemon.ts:152-154) and waitForDaemonActive.

    killCurrentDaemon has a 5 s timeout that resolves without confirming the process died, then nulls currentDaemonProcess anyway.

    main.ts:364-372 carries a long comment describing a real shipped race: isStartingUp was cleared before a window existed and window-all-closed quit the app.

    The forceActiveState debug handler (main.ts:442-485) re-implements the startup sequence inline — two copies that can drift.

    Verified: markGRPCReady() only ever sets isGrpcReady = true (app-grpc.ts:87-88), called from daemon.ts:265 and :294. Nothing resets it, so after restartDaemon the error interceptor behaves as if the daemon were up while it is dead. See "Bugs found on the way".

6. Desktop onboarding wizard

App: desktop. Verdict: model explicitly. Only path a new user has to a working account, zero tests.

States: welcome → profile → vault → recovery → ready, with side branches existing (restore phrase) and import (key file), plus terminal flags hasCompletedOnboarding / hasSkippedOnboarding. Conditional edge: profile → vault only when initialAccountIdCount === 0.

The problem: currentStep exists in three places simultaneously — the persisted store (setOnboardingStep), localState, and a separate currentStep useState. Every transition writes two or three of them.

Files: frontend/apps/desktop/src/components/onboarding.tsx — step machine 118–436, VaultStep 629–842, CreateAccountStep 1081–1242; store at src/app-onboarding-store.ts.

Evidence: the file is littered with console.log('Before - Local step:', …) / console.log('After - Store state:', …) debug scaffolding, which is what desync-chasing looks like. handlePrev from existing/import unconditionally returns to vault even when shouldConfigureVault is false — i.e. to a step that was never shown. Sub-steps have their own latches (hasResolvedRemoteAccounts, hasStarted, generatedMnemonicRef, createdAccountRef). The store accepts transitions from six separate ipcMain.on channels with no validation, so hasCompletedOnboarding && hasSkippedOnboarding is representable.

7. WXR (WordPress) import lifecycle

App: desktop. Verdict: model explicitly and fix the bugs first — this one has durable side effects (publishes documents, registers keys) and the orchestrator has no tests.

States: pending → authors → posts → complete | error, plus cancelled (implicit: the state row is deleted) and resumed.

Encoding: two divergent phase unions — WXRImportState.phase in wxr-import-store.ts:30 (has 'pending', lacks 'parsing') and ImportProgress.phase in wxr-import.ts:79 (has 'parsing', lacks 'pending').

Files: frontend/apps/desktop/src/wxr-import.ts:90-152, 157-384, 806-823, wxr-import-store.ts, app-web-importing.ts:460-495, components/wxr-import-dialog.tsx.

Evidence (see "Bugs found on the way" for the two verified defects): no abort mechanism at all; no single-run guard, so startWXRImport and resumeWXRImport can both drive the loop concurrently against the same persisted state; importedPosts is incremented for skipped and failed posts too; an encrypted import file can't resume mid-posts because progress isn't written back; the dialog reads a global ['WXR_IMPORT_STATUS'] query, so a previous run's residual phase === 'complete' jumps a fresh dialog straight to the completion screen.

8. Vault email challenge lifecycle

App: vault backend. Verdict: model explicitly; the highest security weight in this audit.

States: issued → verified (row deleted, user created / email updated) | expired (lazily deleted) | locked (attempt_count reaches 3) | superseded (a new start past cooldown deletes and reinserts) | send-failed.

Two different flows are multiplexed onto one table by key: registration (new_email IS NULL, keyed by the registration email) and email change (new_email set, keyed by the current email). A third copy of the same state rides in the evb cookie; a fourth in the daemon request body.

Files: vault/src/api-service.ts — registerStart 909–986, registerVerify 988–1071, changeEmailStart 1522–1618, changeEmailVerify 1620–1689, changeEmailVerifyDaemon 1697–1755; schema vault/src/sqlite-schema.sql:36-53; cookie state vault/src/cookies.ts:97-148.

Evidence:

    The validity predicate is implemented three times (registerVerify ~1001–1027, changeEmailVerify ~1645–1668, changeEmailVerifyDaemon ~1714–1737) over the same fields with subtly different checks; they already diverge in error messages. A comment at 1691–1695 admits the daemon path "mirrors" the browser checks.

    email as primary key means a registration challenge and an email-change challenge cannot coexist for the same address — the encoding conflates two machines by key choice.

    The resend cooldown is not a state; it is create_time reinterpreted. Nothing distinguishes "issued, cooldown running" from "issued, resendable".

    Racy check-then-insert in both *Start handlers: two concurrent starts both pass the cooldown SELECT, then one INSERT hits a PK violation that isn't an APIError and therefore isn't mapped — a 500.

    Existing regression tests mark past TOCTOU races: "registerVerify rejects when the email was claimed after start", "changeEmailVerify rejects when the target email was claimed after start".

9. Desktop sync service: subscriptions, discovery, activity watermark, invalidation

App: desktop main process. Verdict: model explicitly or move it to the backend — see open questions. ~1200 lines of hand-rolled coordination.

States: per resource subscribed → discovering → ok | tombstone | redirect | not-found → settled-polling(slow) with a covered-by-recursive overlay; global polling idle | in-flight; invalidation accumulating → debouncing → flushing; cadence focused (1×) | backgrounded (10×).

Encoding: a module-level SyncState bag (app-sync.ts:139-176) with a watermark, a polling flag, a pending-invalidation set, two timers and five maps/sets; per-subscription {unsubscribe, discoveryTimer, isCovered} plus a closure-local cancelled flag as a cancellation token; free-form DiscoveryState | null writes ({isDiscovering}, {isNotFound}, {isTombstone}, null).

Evidence: transitions are enforced by defensive re-reads of current state ("Don't overwrite settled state", 833); isNotFound && isDiscovering is reachable; the error path leaves isDiscovering set forever with only a warning; ensureActivityPolling uses setTimeout(() => {}, 0) as a placeholder timer sentinel standing in for a "starting" state (702); debounce jitter is Math.random() * 100.

(shared) The read side of the same domain is a copy-pasted derived boolean. frontend/packages/shared/src/models/entity.ts computes isDiscovering from five independent signals, and the identical 5-line formula with identical caveat comments appears verbatim at L165–170 and again at L455–460. The timeout (isTimedOut) is computed at render time from Date.now() - startedAt — it doesn't fire, it just decays whenever something re-renders.

10. Desktop embedded browser: guest navigation, covers, agent grant

App: desktop. Verdict: model explicitly; it's self-contained and security-relevant.

States per guest: normal → https-attempt(generation) → committed | insecure-warning | blocked-warning → open (user consent), plus an agentNavigating mode that suppresses normal redirect handling.

Encoding, all in one closure (app-web-browser.ts:344-588): two parallel cover latches blocked and insecure where each setter clears the other by hand; generation incremented by supersede(); attempt: {generation, https}; agentNavigating boolean; and a requests map correlating IPC navigate requests to did-navigate commits.

Evidence: blocked && insecure is representable and exclusivity is held only by each setter clearing the other plus [blocked, insecure].find(...) ordering at two call sites. did-fail-load has a three-condition defensive filter. A 10-second setTimeout races loadURL's resolution, reconciled by a live() generation check with a comment explaining why. committed() reconstructs which cover is showing by comparing guest.getURL() to cover.page rather than reading stored state.

The renderer half (pages/web-browser.tsx:90-243) runs three parallel generation counters — pending, resolution, faviconRevision — doing the same job in one component, with two asymmetric guards in the browser-location handler that no type encodes.

The browser agent grant (browser-agent-tools.tsx:86-210 + app-web-browser.ts:267-342) is a second machine in the same subsystem: unavailable → granted → connecting → connected ⇄ paused → error, with a nested navigation-approval sub-state whose answer callback is stored in React state, a 40 s timeout answering null, an originsRef mirror of origins because the polling closure can't see fresh state, and a grant object mutated in place so in-flight checks observe the new origin list.

11. Comment composer and draft lifecycle (three implementations) (shared + both apps)

Verdict: model once in @shm/shared or the editor package; three divergent copies is the real finding.

frontend/packages/editor/src/comment-editor.tsx carries the largest ref-latch cluster found anywhere in the repo — fourteen flags/refs for one lifecycle: isExpanded, isDraftReady, isInitializedRef, hasLocalEditsRef, isApplyingInitialBlocksRef, shouldFocusOnActivateRef, shouldMoveCursorToEndOnFocusRef, dragDepthRef, pendingDropRef, insertedReferences WeakSet, contentChangeTimeoutRef, isDraggingOver, isSlashDialogOpen, and a submitTrigger numeric counter used as an event.

States: composer collapsed → expanded → focus-pending → focused (never returns); draft init uninitialized → rehydrating-media → ready racing a local-edits latch; drop idle → drag-over(depth) → pending-drop(while collapsed) → inserting; content clean → dirty-debounced(300ms) → flushed.

Evidence: hasLocalEditsRef is checked twice inside async init purely to stop media rehydration clobbering user typing; a queued drop is sequenced with requestAnimationFrame after expansion; isExpanded && !isDraftReady and isDraggingOver && isExpanded are representable and vetoed by re-checking on every drag event.

Desktop's copy (desktop/src/components/commenting.tsx:127-333) encodes the same lifecycle in five refs plus a boolean, including an isDeletingDraft ref that must suppress a pending debounced save, set redundantly in two places. Web's copy (app/comment-draft-utils.ts:59-172) has saveTimeoutRef, pendingSaveRef, activeDraftKeyRef and a comment admitting the hazard: "The editor can emit its final content during child cleanup after this hook has unmounted" — where an empty emission means "delete the draft".

12. Media upload lifecycle (shared)

App: both. Verdict: model explicitly; the encoding is the most fragile found in the UI layer.

States: empty-form → drag-hover → uploading → error → uploaded/replaced, plus a parallel "web-import in flight" state and a post-upload success flash.

Encoding: the block's phase lives in which prop is set (url vs fileBinary vs mediaRef vs displaySrc vs src), fileName.color === 'red' doubles as the invalid-file error flag, and a module-level Set<string> of block ids (uploadedBlockIds + markBlockUploaded/consumeUploaded, media-render.tsx:50-62) carries the "just uploaded" signal across components, consumed one-shot in useState(() => consumeUploaded(block.id)).

Files: frontend/packages/editor/src/media-render.tsx, media-container.tsx:104-244, video.tsx:297-307, image.tsx:76-140.

Evidence: stale uploadedBlockIds entries survive block deletion and consumption depends on mount order. A comment at media-render L146–147 — "we used to spread the current block.props into the new props… it was causing bugs" — makes prop-overwrite a convention. Three different drag-hover conventions coexist for the same gesture: no depth counting (MediaContainer), relatedTarget containment (MediaForm), and dragDepthRef (CommentEditor).

Tier 2 — worth modeling, lower urgency

    Auto-update pipeline (desktop, auto-update.ts, 1116 lines). UpdateStatus is already a discriminated union, so this is a partial machine — but it's mutated at ~15 sites, the renderer can write main-process status via ipcMain.on('auto-update:set-status'), install phases are labeled "PHASE 1 / PHASE 2" in comments, sequencing uses sleeps (including sleep 1/sleep 2 in generated relaunch shell scripts), and rollback is re-implemented per platform with RPM rollback explicitly "not implemented". High blast radius (bricked installs); the reason it isn't Tier 1 is that the union already exists and the risk is concentrated in the platform branches rather than the phase encoding.

    useAutoRebase (shared, use-document-machine.ts:942-1404). The collaborative-merge orchestrator sits outside the document machine: a 6-condition effect gate, a setTimeout debounce, four snapshot predicates re-checked inside the timer, a suppressChangeRef latch with a fallback that peeks (editor as any)._suppressChangeRef, and a cursor save/restore sub-lifecycle with three fallbacks. ~15 diagnostic console.log sites. Prime candidate for folding into the existing machine rather than a new one.

    desktop-resource.tsx coordination around the document machine (desktop, partial machine). Nine "latest value" refs written every render, a ternary ladder resolving which entity the route points to, two parallel draft_externally_modified handlers with different matching rules, a hand-rolled deps-vs-version optimistic concurrency guard, and window.location.reload() as the escape hatch when state diverges.

    resource-page-common.tsx sticky resource-load gate (shared, 5227 lines). lastGoodRouteIdRef, hasEverLoadedRef, lastLoadedDocumentRef are mutated during render — deliberately, per the comment at L1192–1197: "keep DocumentMachineProvider mounted across transient resource failures… Without this sticky gate, the early returns below would unmount DocumentBody and destroy the XState actor on each blip." The right fix is probably a transient-error state in the machine, not a new machine.

    Draft kind/placeholder resolution (web, web-draft-path.ts, web-draft-shell.ts, web-create-draft.ts). Draft kind is never stored; it is re-derived on every save from URL path prefixes (- vs -private-), editPath: null vs [], editUid nullability, and a separate localStorage set of space-home draft ids that exists because, per the comment, "the editor's autosave, which rewrites the draft's editPath, can't erase the marker". A field that cannot represent the state is the definition of this category.

    Maintenance enqueue → release saga (web + desktop). The job machine is explicit (document-card-cleanup-machine.ts); the call-site handshake is not. It's hand-rolled at 5 sites with three divergent awaitingPrimary proof shapes and .catch(console.error) on release. The rule "enqueue before the primary, release after" is pure convention; an enqueue failure degrades to a toast asking the user to review parent links manually — an undeclared abandoned terminal state.

    Pending-intent deferred actions (web, pending-intent.ts). Four intent types × ~7 outcomes, a single-slot IndexedDB store (so a second intent silently overwrites the first), a module promise latch that returns the same promise to callers with different arguments, inconsistent failure semantics per branch (comment failure silently returns none; publish-draft failure repoints the draft for retry), and consumption spread across an IDB record, a dialog onClose, location.state, and a useRef once-latch. invite-join.ts is a second, parallel mechanism for the same idea.

    Desktop entity-subscription refcounting (models/entities.ts:139-334). unsubscribed → subscribed(n) → pending-teardown → unsubscribed, where teardown is a queueMicrotask that re-checks the count, with a comment recording the previous implementation: "Unlike the previous 300ms setTimeout, this completes before window destruction." A sleep hack replaced by a re-check hack. useHackyAuthorsSubscriptions.ts is the consumer-side workaround whose name is the finding.

    Notification sync loop (desktop, app-notifications.ts:242-624). hasStartedSyncLoop once-latch, per-account debounce timers, an in-flight dedupe map, optimistic pendingActions reconciled by clientActionId, adaptive cadence (30 s / 3 s / ×10 backgrounded), and host hints learned as a side effect of a read handler — a query that performs writes and triggers a zero-delay re-sync.

    Notification read watermark (shared, notification-read-logic.ts). A scalar watermark plus a per-event map, where marking a below-watermark event unread lowers the watermark to targetAtMs - 1 and reconstructs reads from otherLoadedEvents. Clients pass their loaded window, the notify service passes its whole inbox and its answer wins — so an optimistic unread can silently lose read marks for events outside the loaded page. A WeakMap cache is valid only because "read states are never mutated in place", enforced by convention.

    Assistant panel visibility (web + desktop, separately). Web: isOpen, openDecided, openedByReader, hydrated

      a newChatRequest counter, plus four refs in the host component. hydrated is state rather than a ref because of a documented StrictMode bug. Desktop (pages/main.tsx:124-176) has three writers of assistantOpen that must each remember to re-send IPC, and a corrective effect for a deliberately-wrong intermediate state.

    Desktop auth dialog handshake (components/desktop-auth-dialog.tsx:40-241). No state variable at all: five phases derived from browserUrl, connectError, isReady, input.initialSubmit, plus three latch refs and a 500 ms setInterval. Render output is chosen by four order-dependent if guards.

    Seed hosting publish dialog (components/publish-site.tsx:609-710). A six-mode union driven by an effect with a deliberately under-declared dep list, a derived pseudo-state sessionExpired that hijacks rendering, and a re-auth path that leaves mode stale when it happens from register-custom-domain.

    MobilePanelSheet gesture machine (shared, ui/src/mobile-panel-sheet.tsx). closed → opening → open@partial | open@full → close-dragging | resize-dragging → closing, with two parallel drag systems sharing one handle, a suppressHandleClick latch distinguishing drag-end from tap, and a keyboardOpen viewport heuristic. resolveSheetSnap is already extracted and tested, which makes this a cheap migration.

    Comments scroll-follow (shared, use-comments-scroll.ts, comments.tsx:142-165). following-bottom ⇄ anchored-reading, where the unsolved transition is stated in a comment: "a queued programmatic scroll must not turn off following as if the reader had scrolled up." Position lives in a module-level Map keyed per document with an eviction heuristic. The deleted-comment phase ladder cites issue #435.

    Vault Connect pairing (vault frontend + backend). idle → token-in-fragment → request-held → credential-registered → completing → success, where pendingCredential is a retry memo mutated into the request object (a transaction-phase marker disguised as data), hasVaultConnectionFragment() reads window.location at render time as a second source of truth, and vaultConnectionInProgress is a reentrancy flag.

    Vault registration verification (vault frontend). registrationVerificationPending and registrationVerified are module-closure flags inside createActions — not in the Valtio state, invisible to snapshots, and not reset by resetState() or handleLogout. A stale true makes a new handleRegisterVerify a silent no-op unless handleStartRegistration reset it first.

    Vault invitation + writer-grant delivery (vault backend). Redemption is a correctly transactional single-use UPDATE, but the grant machine has no state of its own: "pending" is computed as account NOT IN invitation_grants, retried only when a client happens to sync, and the daemon createCapability call precedes the DB insert.

Tier 3 — implicit, but leave it alone (or fix it differently)

Pushing back on things that look like findings but shouldn't become machines:

    require-sign-in gate (web). Two independent implementations of one policy that "must never disagree" per the file header — the Remix-side gate and the proxy forward-auth probe, with open-path knowledge also duplicated in ops config. This is a single-source-of-truth problem, not a runtime machine. Fix: one shared/generated allowlist.

    query-documents.tsx debounce + generation runner (desktop). Three coordinated staleness checks per async boundary. Correct, but this is what react-query already does. Fix: use the query layer, don't model it.

    SaveIndicatorStatus / draftStatus (desktop). Real bug (below), but the fix is clearTimeout and a status re-check, not a machine.

    Vault sessions table. active → expired → deleted via expire_time + row existence, with lazy cleanup on read. Idiomatic and safe. Leave it.

    Vault failed-sign-in counter. A counter with four reset sites. Trivial; a machine adds nothing.

    Browser network provenance tracker (browser-network-policy.ts). Ordering-dependent merge logic, but it's minimal given Electron's event guarantees and it's tested. Modeling would mostly add ceremony.

    BlockHoverActions positioner (shared). Four states, imperative DOM class mutation that can desync from React. Small enough that the existing cleanup effect is a reasonable answer.

    DraftRouteRedirect (desktop). Legacy-route transitional code. Not worth modeling; worth deleting when the legacy routes go.

    routes/$.tsx loadRoute (web) and the various Condition/DocumentFilter/SettingsTab unions. These are functions of input or already-explicit unions, not lifecycles.

    getVaultConnect "double claim" — flagged during the audit as a non-atomic read-then-delete; I checked and it is not a live defect. vault/src/api-service.ts:1306-1324 runs the SELECT and the DELETE as adjacent synchronous bun:sqlite calls with no await between them, so a single-process vault cannot interleave two claims. It would become a real race only if the vault ever runs as multiple processes against one DB file. Worth a comment, not a rewrite. (The unauthenticated INSERT OR REPLACE overwrite path is a separate, real design question.)

Recurring idioms — the actual smell inventory

Independent of individual findings, the same five workarounds appear across all three apps. These are the signatures of the missing abstraction, and they are a better guide to "where should we look next" than any single file.

    Generation / revision counters to discard stale async. supersede()+generation and resolution, pending, faviconRevision (desktop browser); authGeneration (web hosting and web daemon auth); queryGeneration (desktop query page); routeRevision (private guest teardown); revision (browser agent retry); maintenanceRevision (web draft DB); authVersion → authGeneration (web hosting, after the numeric version demonstrably failed).

    useRef(false) once-latches. Twenty-plus sites. The telling subset is the ones that permanently suppress a retry after a transient failure — attemptedForRef in models/local-assistant.ts, sentRef in useDraftResolutionSync.

    Ref mirrors of state, because a closure can't see fresh state. originsRef/origins, latestBlocksRef, activeDraftKeyRef, the nine xRef.current = x writes in desktop-resource.tsx, liveSuppressRef's two lookup paths in useAutoRebase.

    Durable intent written before the API call, with a recovery replay. pendingSiteMove + recoverSiteMove, maintenance enqueue/release, pendingIntent, invite-join marker, movedUrl, WXR import state. This is a saga/outbox pattern hand-rolled six times with six different failure semantics — the single most duplicated idea in the audit.

    Phase encoded in nullable timestamps or "which field is set". The vault schema (used_time, verified_at, create_time-as-cooldown), NotificationConfigState's four fields for five phases, media block props, name: string | null as "not edited" in site settings.

A sixth, less common but worth naming: copy-pasted derived booleans. entity.ts's isDiscovering formula appears verbatim twice, caveat comments included. A duplicated derivation is a state that wanted to be stored once.

Bugs found on the way

These are defects, independent of whether anything gets modeled. Marked [verified] where I read the code and confirmed it myself; [reported] where it comes from an audit pass and I have not independently checked it.

    [verified] cancelWXRImport() does not cancel anything. frontend/apps/desktop/src/wxr-import.ts:806-808 calls only clearImportState(). There is no abort signal or cancelled flag anywhere in the module, so executeImport keeps running — publishing documents and writing state back onto a cleared store after the user cancelled.

    [verified] WXR import has no single-run guard. startWXRImport and resumeWXRImport both call executeImport directly; two invocations can drive the same persisted state concurrently. Combined with (1): a cancel followed by a restart gives two live loops publishing to the user's account.

    [verified] SaveIndicatorStatus can hide the saving spinner. components/publish-draft-button.tsx:484-493 sets a 1 s setTimeout(() => setStatus('idle')) on saved and never clears it. If saving arrives inside that window, the stale timer fires and blanks the indicator mid-save. Fix: clear the previous timer and re-check the status inside the callback.

    [verified] Dead guard in the publish button. isLocationAvailable is useRef(true) at components/publish-draft-button.tsx:90 and read at :339; there is no writer anywhere in the repo, so if (!isLocationAvailable.current) can never be true. Either an unfinished interlock or dead code — needs the author to say which.

    [verified] isGrpcReady is a one-way latch. app-grpc.ts:87-88 only ever sets it true, from daemon.ts:265 and :294. Nothing resets it on restartDaemon, so after a restart the error interceptors treat a dead daemon as ready. User-visible impact needs tracing (see open questions).

    [verified] The vault's WebAuthn challenge has no server-side expiry. vault/src/cookies.ts:18-38 commits purpose, challenge and (for register) sessionId into the HMAC — but no timestamp. The 5-minute lifetime is maxAge: 300 on the cookie, which only the browser enforces. There is no server-side time check at verification. Worth a focused security look; I have not assessed exploitability and am not describing an attack here.

    [reported] changeEmailVerify updates the user's email without a transaction. vault/src/api-service.ts:1681-1683 does SELECT challenge → UPDATE users.email → DELETE challenge unwrapped; a crash between the update and the delete leaves a consumed-but-live challenge row, and the daemon path can't clear the cookie.

    [reported] grantInvitedRoles can double-grant. vault/src/api-service.ts:833-881 calls the daemon's createCapability before the INSERT ... ON CONFLICT DO NOTHING. If the insert fails, the next sync sees no row and creates the capability again.

    [reported] web-cleanup-worker can drop a wake request. requested is cleared before run(); a wake() that arrives during a failing run sets it again, but the .catch exits the loop and nulls running, so the pending request needs another external wake(). There is also no way to restart after stop().

    [reported] A transient failure permanently suppresses local-assistant provisioning. models/local-assistant.ts:97-111 latches attemptedForRef per key, and resolveLocalAssistantProvisioning returns null for "still loading", "missing prerequisites" and "already exists" alike — so one provider-API blip looks like success and is never retried for that mount.

    [reported] scrapeMode: 'processing' is a dead state. Declared in web-scraper.ts:546, never emitted; only 'downloading' is sent, so the import UI can never display the processing phase.

    [reported] Vault registrationVerified survives logout. A module-closure flag in createActions, not reset by resetState() or handleLogout; a stale true silently no-ops a subsequent handleRegisterVerify.

    [reported] app.addListener('will-quit') is registered per daemon start. Inside startMainDaemon (daemon.ts:281), so every restart adds another listener.

Open questions that need a decision, not more reading

    Does the vault get XState, or a typed reducer? Finding #1 is the strongest case in the repo, but the vault is a separate Bun workspace with no xstate dependency, its own React pinning, and valtio as the incumbent. Adding xstate there is a deliberate dependency decision with a CI/bundle cost; a hand-written discriminated-union reducer over the existing store would capture most of the value. I don't think this should be decided by whoever happens to pick up the ticket.

    Should app-sync.ts be modeled, or moved? ~1200 lines re-implementing subscription, discovery, backoff and invalidation in the Electron main process, over a backend that already has its own syncing and reindexing state machines in Go. Modeling it in XState would make it correct; moving the coordination to the daemon would make it smaller. That's an architecture call, not a refactor.

    Should the document machine grow a transient-error state? Both the resource-page-common.tsx sticky gate and the desktop-resource.tsx ref cluster exist because the page must keep the actor alive across blips the machine can't express. Extending the existing machine is probably cheaper than either workaround — but it touches a 2318-line machine that both apps depend on.

    What is the user-visible consequence of the isGrpcReady latch? I confirmed the latch never resets; I have not traced what the interceptors actually do to a request issued against a restarting daemon. Needs one focused trace before it's worth filing.

    The vault's WebAuthn challenge replay window. The missing server-side expiry is a fact; whether it is exploitable in practice depends on the assertion-verification path. The repo has a security-audit skill that is explicitly user-invoked only — this seems like the case for it.

    Do we consolidate publish/hosting into @shm/shared first, or model in place? Consolidating is the right end state and roughly doubles the work per machine up front. Modeling in place is faster and bakes the duplication in deeper. My recommendation is to consolidate publish (#3) because the two copies have already diverged in behavior, and to model hosting (#4) in place on the web side first, since the web copy is the one with the polling-inside-a- queryFn problem and the richer test suite to migrate against.

Suggested sequencing

Ordered by (evidence of real bugs) × (blast radius) ÷ (cost), not by size:

    Fix the verified bugs (1–6 above). None of them require a machine, and two of them (WXR cancel, double-run) have durable side effects on user data today.

    Vault auth flow (#1) — after deciding question 1.

    Publish saga (#3), consolidated into @shm/shared.

    Daemon lifecycle + startup (#5) — smallest Tier 1 item with a shipped-bug history.

    Desktop onboarding (#6) — low risk, zero existing tests, triple-stored state.

    Web sign-in round trip (#2), jointly with the vault side.

    Vault email challenge (#8) — pair with the security question.

    Hosting/pending-domain (#4), embedded browser (#10), comment composer (#11), media upload (#12), sync (#9) — after question 2.

Appendix: notes on confidence

    Every finding above is grounded in code that was read, with file and line references. Where a pass could not confirm something, it is marked [reported] rather than stated as fact.

    One audit claim was checked and rejected — the getVaultConnect double-claim race (see Tier 3). Treat the [reported] items as leads, not conclusions.

    Line numbers are as of 2026-11-03 on the custom-images working tree and will drift.

    The Go backend, frontend/apps/mobile, frontend/apps/canvas, frontend/apps/cli, agents/, and ops/ were out of scope.

Do you like what you are reading? Subscribe to receive updates.

Unsubscribe anytime