Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
build(ui): restore `npm run lint` as an enforcing gate (#1143)
Call White571da1941581
diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.ymlindex e9550c327..dd5cf379e 100644--- a/.github/workflows/lint.yml+++ b/.github/workflows/lint.yml@@ -46,6 +46,7 @@ jobs:run: |npm cinpm run validate:theme+ npm run lintnpm testnpm run builddiff --git a/docs/plans/ui-lint-debt-cleanup.md b/docs/plans/ui-lint-debt-cleanup.mdnew file mode 100644index 000000000..87bda591d--- /dev/null+++ b/docs/plans/ui-lint-debt-cleanup.md@@ -0,0 +1,602 @@+# UI Lint Debt Cleanup++Restore `cd ui && npm run lint` to a green, meaningful gate.++- Measured at: `78c26be8296f5ba006780b94f7724fd3815ffa1b`+- Rebased onto: `2d47aa469d0ef9c6c9a0f7382fc014706145f18a` — its only `ui/` change+ (`agentActivity.ts`) adds no lint debt, so every count below still holds.+- Branch: `fix/ui-lint-debt`+- Scope: `ui/**` and this document only.++## 1. Verified baseline++Reproduced from a clean `npm ci` at the base commit. `npm run lint` is+`eslint .` with no `--max-warnings`, so **only errors decide the exit code**;+the 41 warnings are already tolerated by the declared command.++```+403 problems (362 errors, 41 warnings) across 90 files+```++| Rule | Errors | Warnings | Files |+| --- | ---: | ---: | ---: |+| `@typescript-eslint/no-explicit-any` | 280 | 0 | 49 |+| `react-refresh/only-export-components` | 42 | 0 | 23 |+| `react-hooks/exhaustive-deps` | 0 | 37 | 14 |+| `react-hooks/refs` | 14 | 0 | 10 |+| `react-hooks/set-state-in-effect` | 14 | 0 | 12 |+| `@typescript-eslint/no-unused-vars` | 7 | 0 | 5 |+| unused `eslint-disable` directives | 0 | 4 | 4 |+| `react-hooks/globals` | 2 | 0 | 1 |+| `@typescript-eslint/no-unused-expressions` | 2 | 0 | 1 |+| `no-useless-escape` | 1 | 0 | 1 |+| **Total** | **362** | **41** | **90** |++### Why the debt accumulated++`ui/eslint.config.js` is the stock Vite scaffold and arrived in the squashed+`3faf4712 v2 init` commit, together with `eslint-plugin-react-hooks@^7` — a+major version that added the `refs`, `set-state-in-effect`, and `globals`+rules. Nothing has run the linter since: `.github/workflows/lint.yml` executes+`validate:theme`, `test`, and `build` in `ui/`, but **never `npm run lint`**.+An ungated command drifts by default.++Wiring the gate into CI is outside this lane's scope (`.github/**`) and is+reported separately. Everything below assumes the gate will eventually be+enforced, which is why the end state must be a command that *stays* green+rather than one that merely exits zero once.++### The count is not an inventory++`eslint-plugin-react-hooks@7` is compiler-backed: it bails out of a component+as soon as it hits something it cannot analyse. An unfixed `react-hooks/refs`+error is therefore a *frontier*, not a leaf — everything behind it in the same+component is invisible until it is fixed, and fixing it can make the error+count go **up**.++Measured, not assumed: deleting the 43 `react-hooks/exhaustive-deps` disable+comments — without changing a line of logic — moves the totals from 287 errors+/ 37 warnings to **296 errors / 80 warnings**, revealing 2 more `refs`, 3 more+`set-state-in-effect`, 2 `immutability` (both in `EditorApp.tsx`), and 2 more+`preserve-manual-memoization`.++Two consequences run through every decision below. Progress in this family+cannot be read off the total. And every inline suppression is a piece of the UI+the analysis cannot see, which is why the ratchet freezes the suppressions too+(§3) rather than only the reported errors.++## 2. Root-cause grouping and decisions++### G1 — `no-unused-vars` disagrees with the codebase's `_` convention (7 errors)++Six of seven are deliberate `_`-prefixed placeholders (`_value`,+`_legacyDefaultBackend`, `_loading`, `_itemValue`, `_label`, `_drop`). The+convention exists in the source; the config never opted into it.++**Decision: fix at the config.** Set `argsIgnorePattern`,+`varsIgnorePattern`, `caughtErrorsIgnorePattern`, and+`destructuredArrayIgnorePattern` to `^_`. This aligns the rule with the+convention already in use — it does not weaken it: any unused binding that is+*not* explicitly marked still errors, which a fixture probe pins.++The seventh (`BackendOAuthPanel.tsx`, an unused `catch` binding) is a real+finding and is fixed as code (`catch { }`).++### G2 — `catch (err: any)` is the codebase's only error-message idiom (67 errors)++67 of the 280 `no-explicit-any` errors are one shape:++```ts+catch (err: any) { setError(err?.message || FALLBACK); }+```++`any` is used here purely to reach `.message` on an `unknown` catch binding.+The codebase already contains the correct idiom, written inline ~20 times+(`err instanceof Error ? err.message : String(err)`), but no shared helper+exists, so the wrong shape kept being copied.++**Decision: fix with a shared contract.** One helper module in `ui/src/lib`+that turns `unknown` into a message. Three call-site shapes exist and are+*not* interchangeable, so the helper exposes them explicitly rather than+collapsing them:++| Observed shape | Empty-string `message` behaviour |+| --- | --- |+| `err?.message \|\| fallback` | falls through to `fallback` |+| `err?.message ?? String(err)` | keeps the empty string |+| `err instanceof Error ? err.message : String(err)` | keeps the empty string |++Only the `any`-bearing sites are converted. The already-correct inline sites+are left alone: touching them would enlarge the diff without changing a single+lint result.++### G3 — react-hooks correctness (30 errors)++`react-hooks/refs` (14), `set-state-in-effect` (14), `globals` (2). These are+genuine React correctness rules from the v7 plugin bump, never previously run.++**Decision: fix as code, per site.** Each is judged individually; there is no+shared cause to correct.++`refs` and `globals` are fixed here. 13 of the 16 are behaviour-preserving+restructures. Three are deliberate, already-commented patterns that the rule+cannot express — `App.tsx` bridges one frame on purpose, `useLatestRef.ts`+*is* the read-a-ref-in-render helper, `WindowManagerProvider.tsx` bootstraps at+mount. Those keep their behaviour and receive a narrow+`eslint-disable-next-line <rule> -- <reason>` pointing at the existing+rationale; the ratchet freezes those three suppressions like any other (§3), so+they are counted, not hidden.++`set-state-in-effect` is not fixed here — see its own section below.++Any site whose behaviour genuinely changes gets a dedicated regression test and+is called out in the PR body.++### G4 — trivia (3 errors, 4 stale directives)++`no-unused-expressions` ×2 (`ChannelList.tsx`), `no-useless-escape` ×1+(`mentions.ts`, an unnecessary `\[` inside a character class), and 4+`eslint-disable` comments that no longer suppress anything.++**Decision: fix as code.** Stale directives are deleted — a suppression that+suppresses nothing is misleading documentation.++### G5 — react-refresh module boundaries (42 errors, 23 files)++One rule, but its two messages ask for **opposite** fixes, so they are+different classes of work:++- *"Use a new file to share constants or functions between components"* — the+ module has a recognised component export **and** a non-component one. Move+ the non-component out.+- *"Move your component(s) to a separate file"* — the module has exports but no+ recognised component export, so its local components can never be+ hot-replaced. Move the component out. (A **class** component does not count+ as a component export; React Refresh does not support classes.)++**G5a — pure helpers stranded in component modules (26 errors, 12 files).**+Constants, lookup tables, and pure functions exported from a `.tsx` component+module, mostly so tests can import them: all 8 of `vendorMeta.tsx`, 4 of+`DockContext.tsx`, `badgeVariants`, `buttonVariants`,+`sessionAgentDisplayName`, `harnessTabFromParam`, `selectApiErrorFields`, and+so on.++One is a false positive rather than a stranded helper:+`export const DEFAULT_VENDOR = VENDOR_OPTIONS[0]` — an uppercase name with an+initializer the plugin cannot analyse reads as a component, which flags every+sibling export in a `.tsx` file that contains no JSX at all. Renaming the file+to `.ts` is the correct fix, not a suppression.++*Decision: fix.* Each moves to a sibling module that owns it, following the+convention already in the tree (`settings/models/` keeps `eligibility.ts`,+`format.ts`, `reorder.ts` beside its components). Two of the 12 files are+context modules contributing *helper* exports (`DockContext.tsx` ×4,+`ApiContext.tsx` ×2); their hook exports belong to G5c.++**G5b — a component stranded in a data module (2 errors, 2 files).** The mirror+image: `apps/registry.tsx` defines its Suspense fallback next to the registry+object, and `ui/error-boundary.tsx` pairs a class boundary with its fallback.++*Decision: fix.* The component moves out, which is also what the rule means+here — a fallback that can never hot-reload forces a full page reload for a+one-line copy change.++**G5c — a context hook next to its provider (14 errors, 11 files).** The+standard `XContext.tsx = context + Provider + useX` layout. Two fix directions+exist and they differ enormously in cost:++| Direction | Files whose imports change |+| --- | --- |+| move the hook out | up to 78 (`useApi`), 55 (`useToast`), 22 (`useWindowManager`) |+| move the Provider out | 1–4 (providers are mounted once) |++*Decision: fix by moving the Provider out*, for every context except+`ApiContext.tsx`. Renaming `XContext.tsx` to `XContext.ts` keeps every+consumer's extensionless import specifier valid, so only the mount points+change. The tree already demonstrates the pattern twice+(`showPageDrag.ts` + `ShowPageDragProvider.tsx`, `unsavedChangesContext.ts` ++`UnsavedChangesProvider.tsx`).++**Baselined exception — `ApiContext.tsx` (1 error, `useApi`).** Both directions+are disproportionate here, and the risk is measured rather than assumed:++- 3194 lines, of which `ApiProvider` is ~1200; the rest is the API surface type+ and ~120 exported payload types that most of `ui/` imports.+- 143 commits in the last 90 days — the second-busiest file in `ui/src` after+ `ChatPage.tsx`.+- **36 unmerged local branches currently modify it, 21 of them committed to+ within the last 30 days.** For comparison, the three contexts split in this+ PR are touched by 1, 2 and 2 unmerged branches.++Splitting it means relocating ~1200 lines in the file with by far the widest+live-branch overlap in the repository — a conflict for 36 branches, in exchange+for hot-reload on one file. Moving `useApi` instead would rewrite 78 import+sites. Neither belongs in a lint PR, and the brief forbids work that comes+closest to overwriting other branches.++The two pure helpers in the same file *are* extracted (G5a), leaving exactly+one baselined error with a written rationale and a named follow-up: extract+`ApiProvider` in a dedicated PR when the branch queue for that file is short.++### G6 — residual `@typescript-eslint/no-explicit-any` (~213 errors)++After G2 the remainder is per-site typing work, not a shared cause. The shapes+are `param: any` (70), `Promise<any>` (46), `<any>` type arguments (19),+`field: any` (16), `Record<_, any>` (15), `as any` (14), `any[]` (12), other+(21). The `Promise<any>` cluster is the return type of ~50 API-client methods+whose responses come from the Python backend, which publishes no schema the UI+can generate from. Inventing those contracts from call-site usage would encode+guesses as types and risk runtime mismatch — that is a worse outcome than an+honest `any`.++**Decision: narrowest explicit baseline plus a ratchet.** See §3.++**Explicitly rejected:** a named alias such as `type ApiJson = any` to collapse+the 46 `Promise<any>` sites. It would silence the rule while leaving the values+just as untyped, and it would destroy the ratchet's ability to notice a *new*+untyped endpoint. Keeping them counted is the honest option.++### `react-hooks/set-state-in-effect` (17 errors after G3)++What survives G3 is the "reset derived state when the subject changes" and+prop-mirroring shapes, in components with no test coverage. Each rewrite moves+when a render happens, so each needs its own regression test first — and by the+frontier property above, fixing one reveals more.++**Decision: baseline.** Batching render-order rewrites behind a lint deadline is+how a subtle bug ships.++### `react-hooks/preserve-manual-memoization` (9 errors)++**Decision: baseline.** These are React Compiler *adoption* advice.+`babel-plugin-react-compiler` is not in this project's Vite plugin list+(`plugins: [react()]`), so no shipped behaviour depends on them. They become+actionable in the change that turns the compiler on.++### `react-hooks/exhaustive-deps` (37 warnings)++Warnings do not affect the exit code and are not part of restoring the gate.+They are not fixed here — but their **suppressions** are frozen by the ratchet+(§3) so the unanalysed area cannot grow.++## 3. Baseline and ratchet++`ui/eslint-baseline.json` is an explicit per-file, per-rule ledger of the+residue, and `npm run lint` is now `node scripts/lint-baseline.mjs`: the same+ESLint pass, measured against that ledger. `npm run lint:report` still runs+plain `eslint .`; `npm run lint:baseline` regenerates the ledger.++The ledger has two tallies, because a rule can be silenced two ways:++| Tally | What it records | Final count |+| --- | ---: | ---: |+| `violations` | errors ESLint reported | 240 across 48 files |+| `suppressions` | messages an inline `eslint-disable` comment hid | 48 across 34 files |++Freezing the suppressions is what makes the gate sound. Without it, adding one+comment is a free way past the ratchet — and each comment also removes its+component from the compiler-backed analysis, so the dark area measured in §1+would grow unobserved.++### Invariant++Once the run is known to be complete, the build fails on recorded-debt drift+when any of these is true. The first three apply to each tally independently;+the last is ledger-wide:++1. **Unclassified** — a `(file, rule)` pair with no ledger entry. The lookup is+ per pair, so a file already listed for one rule buys no tolerance for+ another.+2. **Expanded** — a pair's count exceeds its recorded number.+3. **Stale** — a pair's count is *below* its recorded number, or the pair is+ gone. An improvement has to be recorded in the same commit, otherwise the+ freed headroom silently becomes budget for new violations.+4. **Unexplained** — a rule appears in the ledger with no entry in its+ `rationale` map. A rule nobody had to explain is exactly how an unrelated+ error class slips in and stops being visible.++Whether the run *is* complete is a separate, unconditional question, answered+first — see "The gate measures its own completeness" below.++The ledger therefore never grows on its own — raising a number is an edit to a+reviewed file, not a side effect of a push — and nothing it tolerates is+anonymous: every tolerated violation is one greppable line naming its rule, its+file, and its exact count, under a rule-level rationale in the same file.++### What the invariant does not cover++The ratchet is keyed on `(file, rule)` counts, which is less than a violation's+identity. Two consequences follow, and both are stated here rather than left for+a reader to discover:++- **A one-for-one site replacement inside an already-recorded pair passes.**+ Delete one baselined `no-explicit-any` in `src/lib/platforms.ts`, add another+ anywhere in the same file, and the count is unchanged, so the gate exits 0.+ Measured, not theorised. This is the accepted residual of a count ratchet, and+ it is the same trade-off ESLint 9's own `suppressions-service` makes with the+ identical `Record<file, Record<rule, {count}>>` shape. It is bounded on three+ sides: the pair must already carry recorded debt, the count cannot grow, and+ once that debt is genuinely paid down the *stale* check forces the allowance+ down with it, permanently. Raising it again needs a reviewer.+- **The ledger records what was found, never what was looked at.** Narrowing the+ lint scope would exempt arbitrary source with no signal in the ledger at all —+ the exempted pairs would simply read as *stale* and the next+ `npm run lint:baseline` would book the exemption as if the debt had been paid.+ That hole is closed outside the ledger, by the integrity checks below, which+ run before both the verdict and `--update`.++Closing the first one properly means keying the ledger on a site fingerprint,+which pushes ledger churn into every unrelated PR that touches a line carrying+baselined debt — 52 of the 240 sit in `ApiContext.tsx` alone. That cost lands+outside this cleanup, so the count model stays and the claim is written to+match it.++### Non-goals of the baseline++- It is not an ignore list. Ignored paths and disabled rules would hide+ unclassified errors; per-pair counts cannot.+- It does not downgrade errors to warnings.+- It does not cover rules that are fully fixed — those pairs are absent, so any+ regression fails as *unclassified*.++### Evidence++`compareToBaseline`, `missingRationales`, `fatalProblems`, `reportLines` and+`integrityLines` are pure functions with red-first unit tests+(`ui/scripts/lintBaseline.test.mjs`, 33 cases): exact match, new rule in a new+file, new rule in an already-listed file, expanded count, reduced count,+vanished pair, deleted file, empty-run vacuity, each rationale branch, each+`fatalProblems` discrimination, each integrity failure in isolation and all of+them together, and — the load-bearing one — a subprocess regression proving+`lint:baseline --update` cannot write a baseline while an integrity check is+failing. That last case runs the real command rather than an injected fake,+because a fake would only pin the ordering its author already imagined.++The measurement itself is pinned in `ui/scripts/lintPolicy.test.mjs` (40 cases):+the walk against a synthetic tree and against the real one, its symlink+semantics asserted equal to ESLint's own enumerator, the positive invariant that+every intended file resolves the pinned policy, and one case per drift —+`basePath`, scoped `ignores`, a dropped rule, a demoted rule, loosened options+at unchanged severity, an unpinned rule appearing, each language and plugin+boundary, each globals direction, grouping, both coverage directions, the+vacuous-empty case, every inline directive family, `eslint-disable-next-line`+still reaching `suppressedMessages`, and the independence of the expected+globals catalog from the package the resolved config derives from.++Two of those cases pin the residual above as an *intended* property rather than+an oversight: that a one-for-one swap inside a recorded pair passes, and that+the same swap is caught the moment it changes the count, the rule or the file.++The gate script is also pinned as reviewable text. Its `(file, rule)` key joins+on NUL, which cannot occur in either half; written as a literal byte it made+the whole script binary to git (`Bin 0 -> 8114 bytes`), so the gate everyone is+asked to trust stopped appearing in diffs. `pairKey` writes it as an escape,+with identical runtime meaning, and a test asserts the source contains no raw+NUL.++The wired command was then driven end to end against all four evasion routes,+each of which failed the gate and was reverted:++| Probe | Gate output |+| --- | --- |+| `any` in a brand-new file | `NEW … no-explicit-any 1 errors (not in the baseline)` |+| one extra `any` in a listed file | `EXPANDED … 3 errors, baseline allows 2` |+| the same `any` behind a disable comment | `NEW … 1 suppressed messages (not in the baseline)` |+| one recorded `any` fixed, ledger untouched | `STALE … 1 errors, baseline still records 2` |++The *config* decisions are pinned the same way, as executable probes against the+real `eslint.config.js` rather than as prose+(`ui/scripts/eslintConventions.test.mjs`): an unmarked unused binding still+errors while an `_`-marked one does not (G1), and `react-hooks/refs` still+errors on an ordinary ref read *and* write during render, so the one blanket+exemption in `useLatestRef.ts` cannot quietly become a config-wide relaxation.++Those probes assert **severity 2**, not merely that the rule fired. The gate+tallies severity-2 messages, so a rule demoted to a warning would still appear+in `messages`, still pass a presence check, and still change no count in the+ledger — while no longer gating anything. Measured: with `react-hooks/refs` and+`no-unused-vars` demoted to `warn`, the presence-only form of these probes+passed 10/10.++### The gate measures its own completeness++A behavioural probe only defends the rule someone thought to write it for, so the+class needs closing at a chokepoint. Three successive attempts at that chokepoint+described the policy with *hand-written* statements about it, and each one had a+blind complement that review then found, one at a time:++| Description | What it could not see |+| --- | --- |+| the rule ids at severity 1 and at severity 0 | a severity-2 rule that leaves the config outright |+| global `ignores` only | an `ignores` on a rule-bearing entry, which exempts a subtree while its `files` is unchanged |+| the union of every entry's `files` | the same scoped ignore, from the other side |+| "some rules resolve" counts as *linted* | a path resolving 1 rule out of 106 |+| every rule's *severity* | a rule kept at error with its options loosened |+| every entry's `{name, files, ignores}` | `basePath`, which narrows an entry's reach without touching any of the three |+| a fixed list of representative paths | any file not on the list |++Enumerating the domain is the generator: whatever the list says, the complement+is invisible, and a fourth list would only move the blind spot. So the domain is+no longer written down. `npm run lint` **measures** it, and refuses to report+anything at all until four questions come out clean — before the drift verdict,+and before `--update` may write a baseline:++1. **Domain** — walk `ui/` with `fs.readdir`/Dirent and collect every `.ts` and+ `.tsx` file, at any depth, excluding only `node_modules` and `dist` (the two+ roots the declared policy already places outside it). An empty walk is itself+ a failure, so the check cannot pass vacuously. Symlink handling mirrors+ ESLint's own enumerator exactly, so the two lists are comparable.+2. **Coverage** — every walked file must appear in the ESLint run, and every+ TypeScript file the run opened must appear in the walk. Both directions, so+ neither a narrowed scope nor a blind walk can hide behind the other.+3. **Policy** — every walked file must resolve `EXPECTED_POLICY` in full: all+ 106 rules *with their options*, plus the boundaries that can stop a rule+ running even when the rule map is intact — parser identity, `ecmaVersion`,+ `sourceType`, parser options, processor, plugin ids, linter options, and+ browser globals. Identical failures are grouped, so a config-wide drift+ prints once rather than 514 times.+4. **Inline overrides** — no source may reconfigure a rule in a comment. Each+ file is parsed a second time with the shared config's rules stripped and+ `allowInlineConfig: false`, and every node from `getInlineConfigNodes()` that+ is not in `getDisableDirectives()` is a failure. Structural, by node+ identity: no regex, no new dependency.++Point 4 exists because `/* eslint some-rule: "off" */` is invisible to *both*+tallies — it produces no error to count and no suppressed message either. The+48 existing `eslint-disable` suppressions are unaffected: they stay in the+normal ESLint pass, keep populating `suppressedMessages`, and remain frozen by+the ledger. Turning them all off with `linterOptions.noInlineConfig` was+considered and rejected for exactly that reason.++`vite.config.ts` is the concrete file this recovers: a root-level source that+every path-list and every `{name, files, ignores}` contract missed, and that a+one-word `basePath: 'src'` silently dropped from the lint run.++`EXPECTED_POLICY` lives in `ui/scripts/lintPolicy.mjs`, imported by the gate and+by its tests, so there is one copy. A dependency upgrade is *meant* to fail+against it; the diff is the review prompt, and it is the only place a change in+enforcement policy surfaces before it silently changes what+`eslint-baseline.json` is allowed to record. There is deliberately no+auto-generator and no snapshot-update path — a contract that rewrites itself+records drift instead of gating it.++#### The reference has to be independent of the subject++That claim held on every axis but one, and the exception had a different shape+from the seven blind complements above. `EXPECTED_POLICY.globals` *read* the+installed `globals` package's `browser` export — the same export+`eslint.config.js` builds `languageOptions.globals` from. The subject was fully+measured: all 1169 names and their writability values were compared, in both+directions. The *reference* just was not independent of it, so on that one axis+the comparison was `X === X`.++It is a real hole because `no-global-assign` runs at error with no exceptions, so+each of the 1044 readonly names in that catalog is an identifier product code may+not reassign. Upstream flipping one to writable, or dropping one altogether,+narrows what the gate enforces — and both sides of the check would have moved+together and passed. The only trace would have been a version bump in+`package-lock.json`.++So the catalog is a committed value now, in `ui/scripts/browserGlobals.mjs`:+1169 names with their boolean writability (`false` readonly, `true` writable,+which is what the resolved config actually contains), and neither that file nor+`lintPolicy.mjs` imports `globals` at all. It is 1196 lines because being long is+what makes an upstream change readable — the file *is* the review prompt.+Nothing regenerates it; a generator would restore the self-reference it exists to+remove. Exactly one test compares the snapshot against the installed package, so+an upgrade fails by name in one legible place instead of passing silently+everywhere.++Red-first here means three assertions that fail against the previous head and+pass now, each for its own reason: mutating `globals.browser` at runtime no+longer moves `EXPECTED_POLICY.globals`; the expected catalog is not that object+by identity; and neither policy module imports `globals`, asserted structurally+by walking the modules' own `ImportDeclaration` nodes rather than by matching+source text. The first two catch a live pointer, the third catches the copy that+would be taken at load time and would still move on every upgrade.++The failures a `globals` upgrade now produces, each surfacing on its own with the+rest of the policy reading as unchanged:++| Upstream change | Under the live read | Under the committed catalog |+| --- | --- | --- |+| a browser global is added | both sides gain it, no drift | `1 unexpected global(s): …`, exit 1 |+| a browser global is removed | both sides lose it, no drift | `1 expected global(s) absent: …`, exit 1 |+| one is loosened to writable | both sides flip, `no-global-assign` quietly stops covering it, no drift | `1 global(s) changed writability: …`, exit 1 |++What remains hand-written is the *boundary* of the TypeScript policy, kept small+and behavioural: `scripts/*.mjs` and `eslint.config.js` are opened by the run but+resolve the empty rule map, so only a fatal parse or config error can be reported+for them. Broadening the lint scope to JS/MJS is a separate decision; that+assertion is where it would become visible.++Red-first, each defect driven through the real command and then reverted, with+the config and the baseline confirmed byte-identical afterwards:++| Defect | Under the earlier contracts | Under the measurement |+| --- | --- | --- |+| `basePath: 'src'` on the rule-bearing entry | all green, `vite.config.ts` silently unlinted | `UNLINTED vite.config.ts`, plus a `POLICY` group, exit 1 |+| `ignores: ['src/lib/**']` on the same entry | caught only if a listed path happened to live there | every file in the subtree fails coverage |+| an upstream preset drops `react-hooks/globals` | *no drift*, if severity alone was pinned | `POLICY` on all 514 files, grouped into one entry |+| a rule kept at error with its options loosened | severity map unchanged, all green | `rule config changed`, exit 1 |+| `/* eslint …: "off" */` in a source file | invisible to both tallies | `INLINE`, exit 1 |+| `/* eslint …: "warn" */` in a source file | invisible to both tallies | `INLINE`, exit 1 |+| the same file, under `lint:baseline --update` | a fresh green baseline written | exit 1, `eslint-baseline.json` unchanged |+| `// eslint-disable-next-line` alone | — | not an `INLINE` failure; still lands in the suppression tally |++The third row is the whole argument in one line: an enforcement rule left the+gate, every test passed, and the ledger reported no drift.++The cost is one extra parse of the 514 sources: `npm run lint` goes from 9.1 s+to 11.3 s. The `calculateConfigForFile` sweep across all of them is 12.6 ms.++## 4. Result++| Rule | Before | Fixed | Suppressed | Baselined |+| --- | ---: | ---: | ---: | ---: |+| `@typescript-eslint/no-explicit-any` | 280 | 67 | 0 | 213 |+| `react-refresh/only-export-components` | 42 | 41 | 0 | 1 |+| `react-hooks/refs` | 14 | 11 | 3 ² | 0 |+| `react-hooks/set-state-in-effect` | 14 | 0 | 0 | 17 ¹ |+| `@typescript-eslint/no-unused-vars` | 7 | 7 | 0 | 0 |+| `react-hooks/globals` | 2 | 2 | 0 | 0 |+| `@typescript-eslint/no-unused-expressions` | 2 | 2 | 0 | 0 |+| `no-useless-escape` | 1 | 1 | 0 | 0 |+| `react-hooks/preserve-manual-memoization` | 0 ¹ | 0 | 0 | 9 |+| **Total errors** | **362** | **131** | **3** | **240** |++¹ Both counts *rose* while the code got better — the frontier property (§1).+Fixing the 14 `refs` errors let the analyser reach code it had been bailing out+of, which exposed 3 more `set-state-in-effect` and all 9+`preserve-manual-memoization` findings. Neither is a regression; they were+always there, behind an error that stopped the analysis.++² Three deliberate read-a-ref-in-render sites (G3). They keep their behaviour+behind a rationaled `eslint-disable-next-line`, and the ratchet freezes them in+the suppression ledger, so they are counted rather than hidden. The suppression+tally goes 45 → 48 for exactly these three.++Warnings go 41 → 54, all `react-hooks/exhaustive-deps`, for the same reason.+`npm run lint` has never had `--max-warnings`, so they do not gate.++No product behaviour changes. Every module split in G5 is a verbatim move.++## 5. Acceptance++From a clean install in `ui/`:++```bash+npm ci+npm run lint # eslint + ratchet, exit 0+npm test # full Vitest suite+npm run validate:theme+npm run build # validate:imports + tsc -b + vite build+```++Plus `git diff --check` and a full review of the diff against `origin/master`.++Exact before/after totals for every command are recorded in the PR body.++## 6. CI enforcement++`.github/workflows/lint.yml` never ran `npm run lint` — which is how the debt+reached 362 errors in the first place (§1). A gate nobody runs is not a gate,+so this cleanup would have rotted again on the same schedule.++The `build-linux-artifacts` job now runs it, after `validate:theme` and before+`npm test`:++```yaml+ - name: Build UI assets+ working-directory: ui+ run: |+ npm ci+ npm run validate:theme+ npm run lint+ npm test+ npm run build+```++One added line, in a file this lane does not otherwise own; the extension was+approved for exactly this hunk. It costs one ESLint pass in a job that has+already installed `node_modules`.diff --git a/ui/eslint-baseline.json b/ui/eslint-baseline.jsonnew file mode 100644index 000000000..c9d861644--- /dev/null+++ b/ui/eslint-baseline.json@@ -0,0 +1,267 @@+{+ "$comment": "Explicit ledger of the lint violations that predate the UI lint cleanup and are not fixed by it. `npm run lint` fails on anything not recorded here, on a recorded entry that grows, and on a recorded entry that shrinks without being re-recorded. See scripts/lint-baseline.mjs. Regenerate with `npm run lint:baseline`; raising a count needs a reviewer to agree in the PR.",+ "rationale": {+ "@typescript-eslint/no-explicit-any": "The untyped edge of the Python API. Each one is a response body, an SSE event payload or a third-party callback that reaches the UI as `any`. Typing them is a per-endpoint contract change against the backend, not a lint fix, and doing it as one sweep would produce a diff nobody can review. The ratchet's job here is to stop a NEW endpoint from landing untyped; the recorded ones come down endpoint by endpoint.",+ "react-hooks/set-state-in-effect": "Legitimate-looking `reset derived state when the subject changes` and prop-mirroring effects in components with no test coverage. Each rewrite changes when a render happens, so each needs its own regression test first; batching them behind a lint deadline is how a subtle render-order bug ships.",+ "react-hooks/preserve-manual-memoization": "Advice for adopting the React Compiler, not a defect. `babel-plugin-react-compiler` is not in this project's Vite plugin list, so no shipped behaviour depends on these; they become actionable in the change that turns the compiler on.",+ "react-refresh/only-export-components": "`src/context/ApiContext.tsx` only. Every other context module in the UI now splits its handle from its provider, but this one is 3142 lines with ~78 consumers, and the split means relocating the ~1200-line provider in the single most contended file in the repository (36 unmerged branches currently modify it). The cost is a merge conflict for everyone else, and the benefit is hot-reload for one file \u2014 so it belongs in a change that owns ApiContext, not in a lint cleanup.",+ "react-hooks/exhaustive-deps": "Inline `eslint-disable` comments predating this cleanup. Each one also opts its component out of the compiler-backed hook analysis, so the suppressed count is a direct measure of the UI the other react-hooks rules cannot see: removing all 43 raises the error count rather than lowering it. Frozen here so that area cannot grow while it is retired component by component.",+ "react-hooks/refs": "Inline suppressions of the render-phase ref rule, in the same unanalysable area as the exhaustive-deps ones above. Frozen so no new render-phase ref access can be hidden behind a comment."+ },+ "violations": {+ "src/components/AppShell.tsx": {+ "@typescript-eslint/no-explicit-any": 2,+ "react-hooks/set-state-in-effect": 2+ },+ "src/components/Dashboard.tsx": {+ "@typescript-eslint/no-explicit-any": 9+ },+ "src/components/InstallHint.tsx": {+ "react-hooks/set-state-in-effect": 1+ },+ "src/components/Wizard.tsx": {+ "@typescript-eslint/no-explicit-any": 9+ },+ "src/components/settings/SettingsBackendsPage.tsx": {+ "@typescript-eslint/no-explicit-any": 1+ },+ "src/components/settings/SettingsMessagingPage.tsx": {+ "@typescript-eslint/no-explicit-any": 3,+ "react-hooks/set-state-in-effect": 1+ },+ "src/components/settings/SettingsPlatformsPage.tsx": {+ "@typescript-eslint/no-explicit-any": 10+ },+ "src/components/settings/SettingsServicePage.tsx": {+ "@typescript-eslint/no-explicit-any": 4+ },+ "src/components/settings/models/modelsApi.ts": {+ "@typescript-eslint/no-explicit-any": 1+ },+ "src/components/settings/providers/ClaudeProviderConfig.tsx": {+ "@typescript-eslint/no-explicit-any": 1+ },+ "src/components/settings/providers/CodexProviderConfig.tsx": {+ "@typescript-eslint/no-explicit-any": 1+ },+ "src/components/settings/shared/useBackendRuntime.ts": {+ "@typescript-eslint/no-explicit-any": 2+ },+ "src/components/settings/shared/useOAuthFlowLock.ts": {+ "react-hooks/preserve-manual-memoization": 1+ },+ "src/components/shared/RoutingConfigPanel.tsx": {+ "@typescript-eslint/no-explicit-any": 3,+ "react-hooks/set-state-in-effect": 1+ },+ "src/components/steps/AgentDetection.tsx": {+ "@typescript-eslint/no-explicit-any": 3+ },+ "src/components/steps/ChannelList.tsx": {+ "@typescript-eslint/no-explicit-any": 29+ },+ "src/components/steps/DiscordConfig.tsx": {+ "@typescript-eslint/no-explicit-any": 6+ },+ "src/components/steps/DoctorPanel.tsx": {+ "@typescript-eslint/no-explicit-any": 4+ },+ "src/components/steps/LarkConfig.tsx": {+ "@typescript-eslint/no-explicit-any": 6+ },+ "src/components/steps/ModeSelection.tsx": {+ "@typescript-eslint/no-explicit-any": 2+ },+ "src/components/steps/PlatformSelection.tsx": {+ "@typescript-eslint/no-explicit-any": 7+ },+ "src/components/steps/SlackConfig.tsx": {+ "@typescript-eslint/no-explicit-any": 4+ },+ "src/components/steps/Summary.tsx": {+ "@typescript-eslint/no-explicit-any": 9+ },+ "src/components/steps/TelegramConfig.tsx": {+ "@typescript-eslint/no-explicit-any": 4+ },+ "src/components/steps/UserList.tsx": {+ "@typescript-eslint/no-explicit-any": 6+ },+ "src/components/steps/WeChatConfig.tsx": {+ "@typescript-eslint/no-explicit-any": 4+ },+ "src/components/steps/Welcome.tsx": {+ "@typescript-eslint/no-explicit-any": 1+ },+ "src/components/ui/secret-request-card.tsx": {+ "react-hooks/set-state-in-effect": 1+ },+ "src/components/ui/vault-chat-requests.tsx": {+ "react-hooks/set-state-in-effect": 1+ },+ "src/components/workbench/AgentsPage.tsx": {+ "@typescript-eslint/no-explicit-any": 1+ },+ "src/components/workbench/AppsEditorPage.tsx": {+ "react-hooks/set-state-in-effect": 1+ },+ "src/components/workbench/ChatPage.tsx": {+ "@typescript-eslint/no-explicit-any": 1,+ "react-hooks/preserve-manual-memoization": 2,+ "react-hooks/set-state-in-effect": 3+ },+ "src/components/workbench/FileTree.tsx": {+ "react-hooks/set-state-in-effect": 2+ },+ "src/components/workbench/HarnessPage.tsx": {+ "@typescript-eslint/no-explicit-any": 1+ },+ "src/components/workbench/TerminalView.tsx": {+ "react-hooks/set-state-in-effect": 1+ },+ "src/components/workbench/VaultsPage.tsx": {+ "react-hooks/set-state-in-effect": 1+ },+ "src/components/workbench/harnessLifecycle.test.ts": {+ "@typescript-eslint/no-explicit-any": 1+ },+ "src/components/workbench/harnessLifecycle.ts": {+ "@typescript-eslint/no-explicit-any": 5+ },+ "src/context/ApiContext.tsx": {+ "@typescript-eslint/no-explicit-any": 52,+ "react-refresh/only-export-components": 1+ },+ "src/context/DockProvider.tsx": {+ "react-hooks/preserve-manual-memoization": 5+ },+ "src/context/StatusContext.ts": {+ "@typescript-eslint/no-explicit-any": 3+ },+ "src/context/StatusProvider.tsx": {+ "@typescript-eslint/no-explicit-any": 1+ },+ "src/context/apiErrorParse.ts": {+ "@typescript-eslint/no-explicit-any": 1+ },+ "src/lib/platforms.ts": {+ "@typescript-eslint/no-explicit-any": 12+ },+ "src/lib/secretFields.ts": {+ "@typescript-eslint/no-explicit-any": 4+ },+ "src/lib/useMessageSearch.ts": {+ "react-hooks/set-state-in-effect": 1+ },+ "src/lib/useNewSession.ts": {+ "react-hooks/set-state-in-effect": 1+ },+ "src/lib/usePendingVaultRequests.ts": {+ "react-hooks/preserve-manual-memoization": 1+ }+ },+ "suppressions": {+ "src/App.tsx": {+ "react-hooks/refs": 1+ },+ "src/components/apps/AppWindow.tsx": {+ "react-hooks/exhaustive-deps": 2+ },+ "src/components/settings/SettingsBackendsPage.tsx": {+ "react-hooks/exhaustive-deps": 1+ },+ "src/components/settings/models/SourceOrderDrawer.tsx": {+ "react-hooks/exhaustive-deps": 1+ },+ "src/components/settings/models/menus/AddCustomModelDialog.tsx": {+ "react-hooks/exhaustive-deps": 1+ },+ "src/components/settings/models/menus/OpenCodeMenuDrawer.tsx": {+ "react-hooks/exhaustive-deps": 1+ },+ "src/components/settings/providers/OpencodeProviderConfig.tsx": {+ "react-hooks/exhaustive-deps": 1+ },+ "src/components/settings/shared/useBackendRuntime.ts": {+ "react-hooks/exhaustive-deps": 1+ },+ "src/components/settings/shared/useOpencodePermission.ts": {+ "react-hooks/set-state-in-effect": 1+ },+ "src/components/steps/AgentDetection.tsx": {+ "react-hooks/exhaustive-deps": 1+ },+ "src/components/steps/ChannelList.tsx": {+ "react-hooks/exhaustive-deps": 3+ },+ "src/components/steps/DoctorPanel.tsx": {+ "react-hooks/exhaustive-deps": 1+ },+ "src/components/steps/LarkConfig.tsx": {+ "react-hooks/exhaustive-deps": 3+ },+ "src/components/steps/LogsPanel.tsx": {+ "react-hooks/exhaustive-deps": 2+ },+ "src/components/steps/SlackConfig.tsx": {+ "react-hooks/exhaustive-deps": 3+ },+ "src/components/ui/directory-browser.tsx": {+ "react-hooks/exhaustive-deps": 1+ },+ "src/components/ui/editor-dialog.tsx": {+ "react-hooks/exhaustive-deps": 1+ },+ "src/components/ui/vault-approval-card.tsx": {+ "react-hooks/exhaustive-deps": 1+ },+ "src/components/ui/vault-secret-form.tsx": {+ "react-hooks/exhaustive-deps": 1+ },+ "src/components/workbench/AgentsPage.tsx": {+ "react-hooks/exhaustive-deps": 2+ },+ "src/components/workbench/AppsFileBrowserPage.tsx": {+ "react-hooks/exhaustive-deps": 2+ },+ "src/components/workbench/EditorApp.tsx": {+ "react-hooks/exhaustive-deps": 2+ },+ "src/components/workbench/FilePicker.tsx": {+ "react-hooks/exhaustive-deps": 3+ },+ "src/components/workbench/FileTree.tsx": {+ "react-hooks/exhaustive-deps": 1+ },+ "src/components/workbench/GlobalPromptsDialog.tsx": {+ "react-hooks/exhaustive-deps": 1+ },+ "src/components/workbench/InboxPage.tsx": {+ "react-hooks/exhaustive-deps": 2+ },+ "src/components/workbench/MentionEditor.tsx": {+ "react-hooks/exhaustive-deps": 1+ },+ "src/components/workbench/MonacoEditor.tsx": {+ "react-hooks/exhaustive-deps": 1+ },+ "src/components/workbench/ProjectAgentsMdDialog.tsx": {+ "react-hooks/exhaustive-deps": 1+ },+ "src/components/workbench/WebPushControl.tsx": {+ "react-hooks/exhaustive-deps": 1+ },+ "src/context/ApiContext.tsx": {+ "react-hooks/exhaustive-deps": 1+ },+ "src/context/WindowManagerProvider.tsx": {+ "react-hooks/refs": 1+ },+ "src/lib/useLatestRef.ts": {+ "react-hooks/refs": 1+ },+ "src/lib/vaultTags.test.ts": {+ "@typescript-eslint/no-explicit-any": 1+ }+ }+}diff --git a/ui/eslint.config.js b/ui/eslint.config.jsindex 5e6b472f5..d045ed3c9 100644--- a/ui/eslint.config.js+++ b/ui/eslint.config.js@@ -19,5 +19,22 @@ export default defineConfig([ecmaVersion: 2020,globals: globals.browser,},+ rules: {+ // The codebase already marks a binding as deliberately unused by naming it+ // `_something` — an argument kept for signature shape, a destructured slot+ // being skipped, a caught error that is intentionally swallowed. Opt the+ // rule into that convention instead of asking every such site for a+ // suppression comment. Anything not explicitly marked still errors, which+ // `scripts/eslintConventions.test.mjs` pins.+ '@typescript-eslint/no-unused-vars': [+ 'error',+ {+ argsIgnorePattern: '^_',+ varsIgnorePattern: '^_',+ caughtErrorsIgnorePattern: '^_',+ destructuredArrayIgnorePattern: '^_',+ },+ ],+ },},])diff --git a/ui/package.json b/ui/package.jsonindex bf9d065e0..bae725a67 100644--- a/ui/package.json+++ b/ui/package.json@@ -10,7 +10,9 @@"dev": "vite","validate:imports": "node scripts/validate-out-of-tree-imports.mjs","build": "npm run validate:imports && tsc -b && vite build",- "lint": "eslint .",+ "lint": "node scripts/lint-baseline.mjs",+ "lint:report": "eslint .",+ "lint:baseline": "node scripts/lint-baseline.mjs --update","preview": "vite preview","test": "vitest run","test:crypto": "vitest run src/lib/vaultCrypto.test.ts",diff --git a/ui/scripts/browserGlobals.mjs b/ui/scripts/browserGlobals.mjsnew file mode 100644index 000000000..36f22430f--- /dev/null+++ b/ui/scripts/browserGlobals.mjs@@ -0,0 +1,1196 @@+// The browser global catalog the lint policy expects, committed as a value.+//+// `eslint.config.js` builds `languageOptions.globals` from the `globals` package's+// `browser` export, so the resolved policy moves whenever that dependency moves.+// The expected side must not. An earlier revision of `EXPECTED_POLICY` read the+// same live export, which made the comparison `X === X` on this one axis: a+// catalog that gained a name, lost one, or flipped one from readonly to writable+// would have moved *both* sides together and passed, and the only trace would+// have been a version bump in the lockfile.+//+// So the catalog is written down here instead. `no-global-assign` is enabled with+// no exceptions, so every `false` below is an identifier the gate refuses to let+// product code reassign; a name that quietly becomes `true` upstream stops being+// protected, and a name that disappears stops being declared at all. Either way+// enforcement narrows, and this file is where that has to become visible.+//+// The encoding is ESLint's boolean form, which is what the resolved config+// actually contains: `false` is readonly, `true` is writable.+//+// Snapshot of the `browser` export of `globals` 16.5.0: 1169 names,+// 125 of them writable. It is deliberately long — being long is what makes+// an upstream change readable. Update it by reading the upstream diff and editing+// these lines by hand; nothing regenerates it, because a generator would restore+// the self-reference this file exists to remove.++export const EXPECTED_BROWSER_GLOBALS = {+ AI: false,+ AICreateMonitor: false,+ AITextSession: false,+ AbortController: false,+ AbortSignal: false,+ AbsoluteOrientationSensor: false,+ AbstractRange: false,+ Accelerometer: false,+ AnalyserNode: false,+ Animation: false,+ AnimationEffect: false,+ AnimationEvent: false,+ AnimationPlaybackEvent: false,+ AnimationTimeline: false,+ AsyncDisposableStack: false,+ Attr: false,+ Audio: false,+ AudioBuffer: false,+ AudioBufferSourceNode: false,+ AudioContext: false,+ AudioData: false,+ AudioDecoder: false,+ AudioDestinationNode: false,+ AudioEncoder: false,+ AudioListener: false,+ AudioNode: false,+ AudioParam: false,+ AudioParamMap: false,+ AudioProcessingEvent: false,+ AudioScheduledSourceNode: false,+ AudioSinkInfo: false,+ AudioWorklet: false,+ AudioWorkletGlobalScope: false,+ AudioWorkletNode: false,+ AudioWorkletProcessor: false,+ AuthenticatorAssertionResponse: false,+ AuthenticatorAttestationResponse: false,+ AuthenticatorResponse: false,+ BackgroundFetchManager: false,+ BackgroundFetchRecord: false,+ BackgroundFetchRegistration: false,+ BarProp: false,+ BarcodeDetector: false,+ BaseAudioContext: false,+ BatteryManager: false,+ BeforeUnloadEvent: false,+ BiquadFilterNode: false,+ Blob: false,+ BlobEvent: false,+ Bluetooth: false,+ BluetoothCharacteristicProperties: false,+ BluetoothDevice: false,+ BluetoothRemoteGATTCharacteristic: false,+ BluetoothRemoteGATTDescriptor: false,+ BluetoothRemoteGATTServer: false,+ BluetoothRemoteGATTService: false,+ BluetoothUUID: false,+ BroadcastChannel: false,+ BrowserCaptureMediaStreamTrack: false,+ ByteLengthQueuingStrategy: false,+ CDATASection: false,+ CSPViolationReportBody: false,+ CSS: false,+ CSSAnimation: false,+ CSSConditionRule: false,+ CSSContainerRule: false,+ CSSCounterStyleRule: false,+ CSSFontFaceRule: false,+ CSSFontFeatureValuesRule: false,+ CSSFontPaletteValuesRule: false,+ CSSFunctionDeclarations: false,+ CSSFunctionDescriptors: false,+ CSSFunctionRule: false,+ CSSGroupingRule: false,+ CSSImageValue: false,+ CSSImportRule: false,+ CSSKeyframeRule: false,+ CSSKeyframesRule: false,+ CSSKeywordValue: false,+ CSSLayerBlockRule: false,+ CSSLayerStatementRule: false,+ CSSMarginRule: false,+ CSSMathClamp: false,+ CSSMathInvert: false,+ CSSMathMax: false,+ CSSMathMin: false,+ CSSMathNegate: false,+ CSSMathProduct: false,+ CSSMathSum: false,+ CSSMathValue: false,+ CSSMatrixComponent: false,+ CSSMediaRule: false,+ CSSNamespaceRule: false,+ CSSNestedDeclarations: false,+ CSSNumericArray: false,+ CSSNumericValue: false,+ CSSPageDescriptors: false,+ CSSPageRule: false,+ CSSPerspective: false,+ CSSPositionTryDescriptors: false,+ CSSPositionTryRule: false,+ CSSPositionValue: false,+ CSSPropertyRule: false,+ CSSRotate: false,+ CSSRule: false,+ CSSRuleList: false,+ CSSScale: false,+ CSSScopeRule: false,+ CSSSkew: false,+ CSSSkewX: false,+ CSSSkewY: false,+ CSSStartingStyleRule: false,+ CSSStyleDeclaration: false,+ CSSStyleRule: false,+ CSSStyleSheet: false,+ CSSStyleValue: false,+ CSSSupportsRule: false,+ CSSTransformComponent: false,+ CSSTransformValue: false,+ CSSTransition: false,+ CSSTranslate: false,+ CSSUnitValue: false,+ CSSUnparsedValue: false,+ CSSVariableReferenceValue: false,+ CSSViewTransitionRule: false,+ Cache: false,+ CacheStorage: false,+ CanvasCaptureMediaStream: false,+ CanvasCaptureMediaStreamTrack: false,+ CanvasGradient: false,+ CanvasPattern: false,+ CanvasRenderingContext2D: false,+ CaptureController: false,+ CaretPosition: false,+ ChannelMergerNode: false,+ ChannelSplitterNode: false,+ ChapterInformation: false,+ CharacterBoundsUpdateEvent: false,+ CharacterData: false,+ Clipboard: false,+ ClipboardChangeEvent: false,+ ClipboardEvent: false,+ ClipboardItem: false,+ CloseEvent: false,+ CloseWatcher: false,+ CommandEvent: false,+ Comment: false,+ CompositionEvent: false,+ CompressionStream: false,+ ConstantSourceNode: false,+ ContentVisibilityAutoStateChangeEvent: false,+ ConvolverNode: false,+ CookieChangeEvent: false,+ CookieDeprecationLabel: false,+ CookieStore: false,+ CookieStoreManager: false,+ CountQueuingStrategy: false,+ CreateMonitor: false,+ Credential: false,+ CredentialsContainer: false,+ CropTarget: false,+ Crypto: false,+ CryptoKey: false,+ CustomElementRegistry: false,+ CustomEvent: false,+ CustomStateSet: false,+ DOMError: false,+ DOMException: false,+ DOMImplementation: false,+ DOMMatrix: false,+ DOMMatrixReadOnly: false,+ DOMParser: false,+ DOMPoint: false,+ DOMPointReadOnly: false,+ DOMQuad: false,+ DOMRect: false,+ DOMRectList: false,+ DOMRectReadOnly: false,+ DOMStringList: false,+ DOMStringMap: false,+ DOMTokenList: false,+ DataTransfer: false,+ DataTransferItem: false,+ DataTransferItemList: false,+ DecompressionStream: false,+ DelayNode: false,+ DelegatedInkTrailPresenter: false,+ DeviceMotionEvent: false,+ DeviceMotionEventAcceleration: false,+ DeviceMotionEventRotationRate: false,+ DeviceOrientationEvent: false,+ DevicePosture: false,+ DigitalCredential: false,+ DisposableStack: false,+ Document: false,+ DocumentFragment: false,+ DocumentPictureInPicture: false,+ DocumentPictureInPictureEvent: false,+ DocumentTimeline: false,+ DocumentType: false,+ DragEvent: false,+ DynamicsCompressorNode: false,+ EditContext: false,+ Element: false,+ ElementInternals: false,+ EncodedAudioChunk: false,+ EncodedVideoChunk: false,+ ErrorEvent: false,+ Event: false,+ EventCounts: false,+ EventSource: false,+ EventTarget: false,+ External: false,+ EyeDropper: false,+ FeaturePolicy: false,+ FederatedCredential: false,+ Fence: false,+ FencedFrameConfig: false,+ FetchLaterResult: false,+ File: false,+ FileList: false,+ FileReader: false,+ FileSystem: false,+ FileSystemDirectoryEntry: false,+ FileSystemDirectoryHandle: false,+ FileSystemDirectoryReader: false,+ FileSystemEntry: false,+ FileSystemFileEntry: false,+ FileSystemFileHandle: false,+ FileSystemHandle: false,+ FileSystemObserver: false,+ FileSystemWritableFileStream: false,+ FocusEvent: false,+ FontData: false,+ FontFace: false,+ FontFaceSet: false,+ FontFaceSetLoadEvent: false,+ FormData: false,+ FormDataEvent: false,+ FragmentDirective: false,+ GPU: false,+ GPUAdapter: false,+ GPUAdapterInfo: false,+ GPUBindGroup: false,+ GPUBindGroupLayout: false,+ GPUBuffer: false,+ GPUBufferUsage: false,+ GPUCanvasContext: false,+ GPUColorWrite: false,+ GPUCommandBuffer: false,+ GPUCommandEncoder: false,+ GPUCompilationInfo: false,+ GPUCompilationMessage: false,+ GPUComputePassEncoder: false,+ GPUComputePipeline: false,+ GPUDevice: false,+ GPUDeviceLostInfo: false,+ GPUError: false,+ GPUExternalTexture: false,+ GPUInternalError: false,+ GPUMapMode: false,+ GPUOutOfMemoryError: false,+ GPUPipelineError: false,+ GPUPipelineLayout: false,+ GPUQuerySet: false,+ GPUQueue: false,+ GPURenderBundle: false,+ GPURenderBundleEncoder: false,+ GPURenderPassEncoder: false,+ GPURenderPipeline: false,+ GPUSampler: false,+ GPUShaderModule: false,+ GPUShaderStage: false,+ GPUSupportedFeatures: false,+ GPUSupportedLimits: false,+ GPUTexture: false,+ GPUTextureUsage: false,+ GPUTextureView: false,+ GPUUncapturedErrorEvent: false,+ GPUValidationError: false,+ GainNode: false,+ Gamepad: false,+ GamepadAxisMoveEvent: false,+ GamepadButton: false,+ GamepadButtonEvent: false,+ GamepadEvent: false,+ GamepadHapticActuator: false,+ GamepadPose: false,+ Geolocation: false,+ GeolocationCoordinates: false,+ GeolocationPosition: false,+ GeolocationPositionError: false,+ GravitySensor: false,+ Gyroscope: false,+ HID: false,+ HIDConnectionEvent: false,+ HIDDevice: false,+ HIDInputReportEvent: false,+ HTMLAllCollection: false,+ HTMLAnchorElement: false,+ HTMLAreaElement: false,+ HTMLAudioElement: false,+ HTMLBRElement: false,+ HTMLBaseElement: false,+ HTMLBodyElement: false,+ HTMLButtonElement: false,+ HTMLCanvasElement: false,+ HTMLCollection: false,+ HTMLDListElement: false,+ HTMLDataElement: false,+ HTMLDataListElement: false,+ HTMLDetailsElement: false,+ HTMLDialogElement: false,+ HTMLDirectoryElement: false,+ HTMLDivElement: false,+ HTMLDocument: false,+ HTMLElement: false,+ HTMLEmbedElement: false,+ HTMLFencedFrameElement: false,+ HTMLFieldSetElement: false,+ HTMLFontElement: false,+ HTMLFormControlsCollection: false,+ HTMLFormElement: false,+ HTMLFrameElement: false,+ HTMLFrameSetElement: false,+ HTMLHRElement: false,+ HTMLHeadElement: false,+ HTMLHeadingElement: false,+ HTMLHtmlElement: false,+ HTMLIFrameElement: false,+ HTMLImageElement: false,+ HTMLInputElement: false,+ HTMLLIElement: false,+ HTMLLabelElement: false,+ HTMLLegendElement: false,+ HTMLLinkElement: false,+ HTMLMapElement: false,+ HTMLMarqueeElement: false,+ HTMLMediaElement: false,+ HTMLMenuElement: false,+ HTMLMetaElement: false,+ HTMLMeterElement: false,+ HTMLModElement: false,+ HTMLOListElement: false,+ HTMLObjectElement: false,+ HTMLOptGroupElement: false,+ HTMLOptionElement: false,+ HTMLOptionsCollection: false,+ HTMLOutputElement: false,+ HTMLParagraphElement: false,+ HTMLParamElement: false,+ HTMLPictureElement: false,+ HTMLPreElement: false,+ HTMLProgressElement: false,+ HTMLQuoteElement: false,+ HTMLScriptElement: false,+ HTMLSelectElement: false,+ HTMLSelectedContentElement: false,+ HTMLSlotElement: false,+ HTMLSourceElement: false,+ HTMLSpanElement: false,+ HTMLStyleElement: false,+ HTMLTableCaptionElement: false,+ HTMLTableCellElement: false,+ HTMLTableColElement: false,+ HTMLTableElement: false,+ HTMLTableRowElement: false,+ HTMLTableSectionElement: false,+ HTMLTemplateElement: false,+ HTMLTextAreaElement: false,+ HTMLTimeElement: false,+ HTMLTitleElement: false,+ HTMLTrackElement: false,+ HTMLUListElement: false,+ HTMLUnknownElement: false,+ HTMLVideoElement: false,+ HashChangeEvent: false,+ Headers: false,+ Highlight: false,+ HighlightRegistry: false,+ History: false,+ IDBCursor: false,+ IDBCursorWithValue: false,+ IDBDatabase: false,+ IDBFactory: false,+ IDBIndex: false,+ IDBKeyRange: false,+ IDBObjectStore: false,+ IDBOpenDBRequest: false,+ IDBRecord: false,+ IDBRequest: false,+ IDBTransaction: false,+ IDBVersionChangeEvent: false,+ IIRFilterNode: false,+ IdentityCredential: false,+ IdentityCredentialError: false,+ IdentityProvider: false,+ IdleDeadline: false,+ IdleDetector: false,+ Image: false,+ ImageBitmap: false,+ ImageBitmapRenderingContext: false,+ ImageCapture: false,+ ImageData: false,+ ImageDecoder: false,+ ImageTrack: false,+ ImageTrackList: false,+ Ink: false,+ InputDeviceCapabilities: false,+ InputDeviceInfo: false,+ InputEvent: false,+ IntegrityViolationReportBody: false,+ InterestEvent: false,+ IntersectionObserver: false,+ IntersectionObserverEntry: false,+ Keyboard: false,+ KeyboardEvent: false,+ KeyboardLayoutMap: false,+ KeyframeEffect: false,+ LanguageDetector: false,+ LargestContentfulPaint: false,+ LaunchParams: false,+ LaunchQueue: false,+ LayoutShift: false,+ LayoutShiftAttribution: false,+ LinearAccelerationSensor: false,+ Location: false,+ Lock: false,+ LockManager: false,+ MIDIAccess: false,+ MIDIConnectionEvent: false,+ MIDIInput: false,+ MIDIInputMap: false,+ MIDIMessageEvent: false,+ MIDIOutput: false,+ MIDIOutputMap: false,+ MIDIPort: false,+ MathMLElement: false,+ MediaCapabilities: false,+ MediaCapabilitiesInfo: false,+ MediaDeviceInfo: false,+ MediaDevices: false,+ MediaElementAudioSourceNode: false,+ MediaEncryptedEvent: false,+ MediaError: false,+ MediaKeyError: false,+ MediaKeyMessageEvent: false,+ MediaKeySession: false,+ MediaKeyStatusMap: false,+ MediaKeySystemAccess: false,+ MediaKeys: false,+ MediaList: false,+ MediaMetadata: false,+ MediaQueryList: false,+ MediaQueryListEvent: false,+ MediaRecorder: false,+ MediaRecorderErrorEvent: false,+ MediaSession: false,+ MediaSource: false,+ MediaSourceHandle: false,+ MediaStream: false,+ MediaStreamAudioDestinationNode: false,+ MediaStreamAudioSourceNode: false,+ MediaStreamEvent: false,+ MediaStreamTrack: false,+ MediaStreamTrackAudioSourceNode: false,+ MediaStreamTrackAudioStats: false,+ MediaStreamTrackEvent: false,+ MediaStreamTrackGenerator: false,+ MediaStreamTrackProcessor: false,+ MediaStreamTrackVideoStats: false,+ MessageChannel: false,+ MessageEvent: false,+ MessagePort: false,+ MimeType: false,+ MimeTypeArray: false,+ ModelGenericSession: false,+ ModelManager: false,+ MouseEvent: false,+ MutationEvent: false,+ MutationObserver: false,+ MutationRecord: false,+ NamedNodeMap: false,+ NavigateEvent: false,+ Navigation: false,+ NavigationActivation: false,+ NavigationCurrentEntryChangeEvent: false,+ NavigationDestination: false,+ NavigationHistoryEntry: false,+ NavigationPrecommitController: false,+ NavigationPreloadManager: false,+ NavigationTransition: false,+ Navigator: false,+ NavigatorLogin: false,+ NavigatorManagedData: false,+ NavigatorUAData: false,+ NetworkInformation: false,+ Node: false,+ NodeFilter: false,+ NodeIterator: false,+ NodeList: false,+ NotRestoredReasonDetails: false,+ NotRestoredReasons: false,+ Notification: false,+ NotifyPaintEvent: false,+ OTPCredential: false,+ Observable: false,+ OfflineAudioCompletionEvent: false,+ OfflineAudioContext: false,+ OffscreenCanvas: false,+ OffscreenCanvasRenderingContext2D: false,+ Option: false,+ OrientationSensor: false,+ OscillatorNode: false,+ OverconstrainedError: false,+ PERSISTENT: false,+ PageRevealEvent: false,+ PageSwapEvent: false,+ PageTransitionEvent: false,+ PannerNode: false,+ PasswordCredential: false,+ Path2D: false,+ PaymentAddress: false,+ PaymentManager: false,+ PaymentMethodChangeEvent: false,+ PaymentRequest: false,+ PaymentRequestUpdateEvent: false,+ PaymentResponse: false,+ Performance: false,+ PerformanceElementTiming: false,+ PerformanceEntry: false,+ PerformanceEventTiming: false,+ PerformanceLongAnimationFrameTiming: false,+ PerformanceLongTaskTiming: false,+ PerformanceMark: false,+ PerformanceMeasure: false,+ PerformanceNavigation: false,+ PerformanceNavigationTiming: false,+ PerformanceObserver: false,+ PerformanceObserverEntryList: false,+ PerformancePaintTiming: false,+ PerformanceResourceTiming: false,+ PerformanceScriptTiming: false,+ PerformanceServerTiming: false,+ PerformanceTiming: false,+ PeriodicSyncManager: false,+ PeriodicWave: false,+ PermissionStatus: false,+ Permissions: false,+ PictureInPictureEvent: false,+ PictureInPictureWindow: false,+ Plugin: false,+ PluginArray: false,+ PointerEvent: false,+ PopStateEvent: false,+ Presentation: false,+ PresentationAvailability: false,+ PresentationConnection: false,+ PresentationConnectionAvailableEvent: false,+ PresentationConnectionCloseEvent: false,+ PresentationConnectionList: false,+ PresentationReceiver: false,+ PresentationRequest: false,+ PressureObserver: false,+ PressureRecord: false,+ ProcessingInstruction: false,+ Profiler: false,+ ProgressEvent: false,+ PromiseRejectionEvent: false,+ ProtectedAudience: false,+ PublicKeyCredential: false,+ PushManager: false,+ PushSubscription: false,+ PushSubscriptionOptions: false,+ QuotaExceededError: false,+ RTCCertificate: false,+ RTCDTMFSender: false,+ RTCDTMFToneChangeEvent: false,+ RTCDataChannel: false,+ RTCDataChannelEvent: false,+ RTCDtlsTransport: false,+ RTCEncodedAudioFrame: false,+ RTCEncodedVideoFrame: false,+ RTCError: false,+ RTCErrorEvent: false,+ RTCIceCandidate: false,+ RTCIceTransport: false,+ RTCPeerConnection: false,+ RTCPeerConnectionIceErrorEvent: false,+ RTCPeerConnectionIceEvent: false,+ RTCRtpReceiver: false,+ RTCRtpScriptTransform: false,+ RTCRtpSender: false,+ RTCRtpTransceiver: false,+ RTCSctpTransport: false,+ RTCSessionDescription: false,+ RTCStatsReport: false,+ RTCTrackEvent: false,+ RadioNodeList: false,+ Range: false,+ ReadableByteStreamController: false,+ ReadableStream: false,+ ReadableStreamBYOBReader: false,+ ReadableStreamBYOBRequest: false,+ ReadableStreamDefaultController: false,+ ReadableStreamDefaultReader: false,+ RelativeOrientationSensor: false,+ RemotePlayback: false,+ ReportBody: false,+ ReportingObserver: false,+ Request: false,+ ResizeObserver: false,+ ResizeObserverEntry: false,+ ResizeObserverSize: false,+ Response: false,+ RestrictionTarget: false,+ SVGAElement: false,+ SVGAngle: false,+ SVGAnimateElement: false,+ SVGAnimateMotionElement: false,+ SVGAnimateTransformElement: false,+ SVGAnimatedAngle: false,+ SVGAnimatedBoolean: false,+ SVGAnimatedEnumeration: false,+ SVGAnimatedInteger: false,+ SVGAnimatedLength: false,+ SVGAnimatedLengthList: false,+ SVGAnimatedNumber: false,+ SVGAnimatedNumberList: false,+ SVGAnimatedPreserveAspectRatio: false,+ SVGAnimatedRect: false,+ SVGAnimatedString: false,+ SVGAnimatedTransformList: false,+ SVGAnimationElement: false,+ SVGCircleElement: false,+ SVGClipPathElement: false,+ SVGComponentTransferFunctionElement: false,+ SVGDefsElement: false,+ SVGDescElement: false,+ SVGElement: false,+ SVGEllipseElement: false,+ SVGFEBlendElement: false,+ SVGFEColorMatrixElement: false,+ SVGFEComponentTransferElement: false,+ SVGFECompositeElement: false,+ SVGFEConvolveMatrixElement: false,+ SVGFEDiffuseLightingElement: false,+ SVGFEDisplacementMapElement: false,+ SVGFEDistantLightElement: false,+ SVGFEDropShadowElement: false,+ SVGFEFloodElement: false,+ SVGFEFuncAElement: false,+ SVGFEFuncBElement: false,+ SVGFEFuncGElement: false,+ SVGFEFuncRElement: false,+ SVGFEGaussianBlurElement: false,+ SVGFEImageElement: false,+ SVGFEMergeElement: false,+ SVGFEMergeNodeElement: false,+ SVGFEMorphologyElement: false,+ SVGFEOffsetElement: false,+ SVGFEPointLightElement: false,+ SVGFESpecularLightingElement: false,+ SVGFESpotLightElement: false,+ SVGFETileElement: false,+ SVGFETurbulenceElement: false,+ SVGFilterElement: false,+ SVGForeignObjectElement: false,+ SVGGElement: false,+ SVGGeometryElement: false,+ SVGGradientElement: false,+ SVGGraphicsElement: false,+ SVGImageElement: false,+ SVGLength: false,+ SVGLengthList: false,+ SVGLineElement: false,+ SVGLinearGradientElement: false,+ SVGMPathElement: false,+ SVGMarkerElement: false,+ SVGMaskElement: false,+ SVGMatrix: false,+ SVGMetadataElement: false,+ SVGNumber: false,+ SVGNumberList: false,+ SVGPathElement: false,+ SVGPatternElement: false,+ SVGPoint: false,+ SVGPointList: false,+ SVGPolygonElement: false,+ SVGPolylineElement: false,+ SVGPreserveAspectRatio: false,+ SVGRadialGradientElement: false,+ SVGRect: false,+ SVGRectElement: false,+ SVGSVGElement: false,+ SVGScriptElement: false,+ SVGSetElement: false,+ SVGStopElement: false,+ SVGStringList: false,+ SVGStyleElement: false,+ SVGSwitchElement: false,+ SVGSymbolElement: false,+ SVGTSpanElement: false,+ SVGTextContentElement: false,+ SVGTextElement: false,+ SVGTextPathElement: false,+ SVGTextPositioningElement: false,+ SVGTitleElement: false,+ SVGTransform: false,+ SVGTransformList: false,+ SVGUnitTypes: false,+ SVGUseElement: false,+ SVGViewElement: false,+ Scheduler: false,+ Scheduling: false,+ Screen: false,+ ScreenDetailed: false,+ ScreenDetails: false,+ ScreenOrientation: false,+ ScriptProcessorNode: false,+ ScrollTimeline: false,+ SecurityPolicyViolationEvent: false,+ Selection: false,+ Sensor: false,+ SensorErrorEvent: false,+ Serial: false,+ SerialPort: false,+ ServiceWorker: false,+ ServiceWorkerContainer: false,+ ServiceWorkerRegistration: false,+ ShadowRoot: false,+ SharedStorage: false,+ SharedStorageAppendMethod: false,+ SharedStorageClearMethod: false,+ SharedStorageDeleteMethod: false,+ SharedStorageModifierMethod: false,+ SharedStorageSetMethod: false,+ SharedStorageWorklet: false,+ SharedWorker: false,+ SnapEvent: false,+ SourceBuffer: false,+ SourceBufferList: false,+ SpeechGrammar: false,+ SpeechGrammarList: false,+ SpeechRecognition: false,+ SpeechRecognitionErrorEvent: false,+ SpeechRecognitionEvent: false,+ SpeechRecognitionPhrase: false,+ SpeechSynthesis: false,+ SpeechSynthesisErrorEvent: false,+ SpeechSynthesisEvent: false,+ SpeechSynthesisUtterance: false,+ SpeechSynthesisVoice: false,+ StaticRange: false,+ StereoPannerNode: false,+ Storage: false,+ StorageBucket: false,+ StorageBucketManager: false,+ StorageEvent: false,+ StorageManager: false,+ StylePropertyMap: false,+ StylePropertyMapReadOnly: false,+ StyleSheet: false,+ StyleSheetList: false,+ SubmitEvent: false,+ Subscriber: false,+ SubtleCrypto: false,+ Summarizer: false,+ SuppressedError: false,+ SyncManager: false,+ TEMPORARY: false,+ TaskAttributionTiming: false,+ TaskController: false,+ TaskPriorityChangeEvent: false,+ TaskSignal: false,+ Text: false,+ TextDecoder: false,+ TextDecoderStream: false,+ TextEncoder: false,+ TextEncoderStream: false,+ TextEvent: false,+ TextFormat: false,+ TextFormatUpdateEvent: false,+ TextMetrics: false,+ TextTrack: false,+ TextTrackCue: false,+ TextTrackCueList: false,+ TextTrackList: false,+ TextUpdateEvent: false,+ TimeEvent: false,+ TimeRanges: false,+ ToggleEvent: false,+ Touch: false,+ TouchEvent: false,+ TouchList: false,+ TrackEvent: false,+ TransformStream: false,+ TransformStreamDefaultController: false,+ TransitionEvent: false,+ Translator: false,+ TreeWalker: false,+ TrustedHTML: false,+ TrustedScript: false,+ TrustedScriptURL: false,+ TrustedTypePolicy: false,+ TrustedTypePolicyFactory: false,+ UIEvent: false,+ URL: false,+ URLPattern: false,+ URLSearchParams: false,+ USB: false,+ USBAlternateInterface: false,+ USBConfiguration: false,+ USBConnectionEvent: false,+ USBDevice: false,+ USBEndpoint: false,+ USBInTransferResult: false,+ USBInterface: false,+ USBIsochronousInTransferPacket: false,+ USBIsochronousInTransferResult: false,+ USBIsochronousOutTransferPacket: false,+ USBIsochronousOutTransferResult: false,+ USBOutTransferResult: false,+ UserActivation: false,+ VTTCue: false,+ VTTRegion: false,+ ValidityState: false,+ VideoColorSpace: false,+ VideoDecoder: false,+ VideoEncoder: false,+ VideoFrame: false,+ VideoPlaybackQuality: false,+ ViewTimeline: false,+ ViewTransition: false,+ ViewTransitionTypeSet: false,+ Viewport: false,+ VirtualKeyboard: false,+ VirtualKeyboardGeometryChangeEvent: false,+ VisibilityStateEntry: false,+ VisualViewport: false,+ WGSLLanguageFeatures: false,+ WakeLock: false,+ WakeLockSentinel: false,+ WaveShaperNode: false,+ WebAssembly: false,+ WebGL2RenderingContext: false,+ WebGLActiveInfo: false,+ WebGLBuffer: false,+ WebGLContextEvent: false,+ WebGLFramebuffer: false,+ WebGLObject: false,+ WebGLProgram: false,+ WebGLQuery: false,+ WebGLRenderbuffer: false,+ WebGLRenderingContext: false,+ WebGLSampler: false,+ WebGLShader: false,+ WebGLShaderPrecisionFormat: false,+ WebGLSync: false,+ WebGLTexture: false,+ WebGLTransformFeedback: false,+ WebGLUniformLocation: false,+ WebGLVertexArrayObject: false,+ WebSocket: false,+ WebSocketError: false,+ WebSocketStream: false,+ WebTransport: false,+ WebTransportBidirectionalStream: false,+ WebTransportDatagramDuplexStream: false,+ WebTransportError: false,+ WebTransportReceiveStream: false,+ WebTransportSendStream: false,+ WheelEvent: false,+ Window: false,+ WindowControlsOverlay: false,+ WindowControlsOverlayGeometryChangeEvent: false,+ Worker: false,+ Worklet: false,+ WorkletGlobalScope: false,+ WritableStream: false,+ WritableStreamDefaultController: false,+ WritableStreamDefaultWriter: false,+ XMLDocument: false,+ XMLHttpRequest: false,+ XMLHttpRequestEventTarget: false,+ XMLHttpRequestUpload: false,+ XMLSerializer: false,+ XPathEvaluator: false,+ XPathExpression: false,+ XPathResult: false,+ XRAnchor: false,+ XRAnchorSet: false,+ XRBoundedReferenceSpace: false,+ XRCPUDepthInformation: false,+ XRCamera: false,+ XRDOMOverlayState: false,+ XRDepthInformation: false,+ XRFrame: false,+ XRHand: false,+ XRHitTestResult: false,+ XRHitTestSource: false,+ XRInputSource: false,+ XRInputSourceArray: false,+ XRInputSourceEvent: false,+ XRInputSourcesChangeEvent: false,+ XRJointPose: false,+ XRJointSpace: false,+ XRLayer: false,+ XRLightEstimate: false,+ XRLightProbe: false,+ XRPose: false,+ XRRay: false,+ XRReferenceSpace: false,+ XRReferenceSpaceEvent: false,+ XRRenderState: false,+ XRRigidTransform: false,+ XRSession: false,+ XRSessionEvent: false,+ XRSpace: false,+ XRSystem: false,+ XRTransientInputHitTestResult: false,+ XRTransientInputHitTestSource: false,+ XRView: false,+ XRViewerPose: false,+ XRViewport: false,+ XRWebGLBinding: false,+ XRWebGLDepthInformation: false,+ XRWebGLLayer: false,+ XSLTProcessor: false,+ addEventListener: false,+ ai: false,+ alert: false,+ atob: false,+ blur: false,+ btoa: false,+ caches: false,+ cancelAnimationFrame: false,+ cancelIdleCallback: false,+ clearInterval: false,+ clearTimeout: false,+ clientInformation: false,+ close: false,+ closed: false,+ confirm: false,+ console: false,+ cookieStore: false,+ createImageBitmap: false,+ credentialless: false,+ crossOriginIsolated: false,+ crypto: false,+ currentFrame: false,+ currentTime: false,+ customElements: false,+ devicePixelRatio: false,+ dispatchEvent: false,+ document: false,+ documentPictureInPicture: false,+ event: false,+ external: false,+ fence: false,+ fetch: false,+ fetchLater: false,+ find: false,+ focus: false,+ frameElement: false,+ frames: false,+ getComputedStyle: false,+ getScreenDetails: false,+ getSelection: false,+ history: false,+ indexedDB: false,+ innerHeight: false,+ innerWidth: false,+ isSecureContext: false,+ launchQueue: false,+ length: false,+ localStorage: false,+ location: true,+ locationbar: false,+ matchMedia: false,+ menubar: false,+ model: false,+ moveBy: false,+ moveTo: false,+ name: false,+ navigation: false,+ navigator: false,+ offscreenBuffering: false,+ onabort: true,+ onafterprint: true,+ onanimationcancel: true,+ onanimationend: true,+ onanimationiteration: true,+ onanimationstart: true,+ onappinstalled: true,+ onauxclick: true,+ onbeforeinput: true,+ onbeforeinstallprompt: true,+ onbeforematch: true,+ onbeforeprint: true,+ onbeforetoggle: true,+ onbeforeunload: true,+ onbeforexrselect: true,+ onblur: true,+ oncancel: true,+ oncanplay: true,+ oncanplaythrough: true,+ onchange: true,+ onclick: true,+ onclose: true,+ oncommand: true,+ oncontentvisibilityautostatechange: true,+ oncontextlost: true,+ oncontextmenu: true,+ oncontextrestored: true,+ oncopy: true,+ oncuechange: true,+ oncut: true,+ ondblclick: true,+ ondevicemotion: true,+ ondeviceorientation: true,+ ondeviceorientationabsolute: true,+ ondrag: true,+ ondragend: true,+ ondragenter: true,+ ondragleave: true,+ ondragover: true,+ ondragstart: true,+ ondrop: true,+ ondurationchange: true,+ onemptied: true,+ onended: true,+ onerror: true,+ onfocus: true,+ onformdata: true,+ ongamepadconnected: true,+ ongamepaddisconnected: true,+ ongotpointercapture: true,+ onhashchange: true,+ oninput: true,+ oninvalid: true,+ onkeydown: true,+ onkeypress: true,+ onkeyup: true,+ onlanguagechange: true,+ onload: true,+ onloadeddata: true,+ onloadedmetadata: true,+ onloadstart: true,+ onlostpointercapture: true,+ onmessage: true,+ onmessageerror: true,+ onmousedown: true,+ onmouseenter: true,+ onmouseleave: true,+ onmousemove: true,+ onmouseout: true,+ onmouseover: true,+ onmouseup: true,+ onmousewheel: true,+ onoffline: true,+ ononline: true,+ onpagehide: true,+ onpagereveal: true,+ onpageshow: true,+ onpageswap: true,+ onpaste: true,+ onpause: true,+ onplay: true,+ onplaying: true,+ onpointercancel: true,+ onpointerdown: true,+ onpointerenter: true,+ onpointerleave: true,+ onpointermove: true,+ onpointerout: true,+ onpointerover: true,+ onpointerrawupdate: true,+ onpointerup: true,+ onpopstate: true,+ onprogress: true,+ onratechange: true,+ onrejectionhandled: true,+ onreset: true,+ onresize: true,+ onscroll: true,+ onscrollend: true,+ onscrollsnapchange: true,+ onscrollsnapchanging: true,+ onsearch: true,+ onsecuritypolicyviolation: true,+ onseeked: true,+ onseeking: true,+ onselect: true,+ onselectionchange: true,+ onselectstart: true,+ onslotchange: true,+ onstalled: true,+ onstorage: true,+ onsubmit: true,+ onsuspend: true,+ ontimeupdate: true,+ ontoggle: true,+ ontransitioncancel: true,+ ontransitionend: true,+ ontransitionrun: true,+ ontransitionstart: true,+ onunhandledrejection: true,+ onunload: true,+ onvolumechange: true,+ onwaiting: true,+ onwheel: true,+ open: false,+ opener: false,+ origin: false,+ originAgentCluster: false,+ outerHeight: false,+ outerWidth: false,+ pageXOffset: false,+ pageYOffset: false,+ parent: false,+ performance: false,+ personalbar: false,+ postMessage: false,+ print: false,+ prompt: false,+ queryLocalFonts: false,+ queueMicrotask: false,+ registerProcessor: false,+ removeEventListener: false,+ reportError: false,+ requestAnimationFrame: false,+ requestIdleCallback: false,+ resizeBy: false,+ resizeTo: false,+ sampleRate: false,+ scheduler: false,+ screen: false,+ screenLeft: false,+ screenTop: false,+ screenX: false,+ screenY: false,+ scroll: false,+ scrollBy: false,+ scrollTo: false,+ scrollX: false,+ scrollY: false,+ scrollbars: false,+ self: false,+ sessionStorage: false,+ setInterval: false,+ setTimeout: false,+ sharedStorage: false,+ showDirectoryPicker: false,+ showOpenFilePicker: false,+ showSaveFilePicker: false,+ speechSynthesis: false,+ status: false,+ statusbar: false,+ stop: false,+ structuredClone: false,+ styleMedia: false,+ toolbar: false,+ top: false,+ trustedTypes: false,+ viewport: false,+ visualViewport: false,+ when: false,+ window: false,+};diff --git a/ui/scripts/eslintConventions.test.mjs b/ui/scripts/eslintConventions.test.mjsnew file mode 100644index 000000000..20a316b56--- /dev/null+++ b/ui/scripts/eslintConventions.test.mjs@@ -0,0 +1,161 @@+import { beforeAll, describe, expect, it } from 'vitest';+import { ESLint } from 'eslint';++import { effectivePolicyOf, policyDifferences } from './lintPolicy.mjs';++// Probes the real `eslint.config.js` rather than a stand-in, so an accidental+// loosening of the shared config fails here instead of quietly widening what+// the lint gate tolerates across the whole UI.+let eslint;++beforeAll(() => {+ eslint = new ESLint();+});++const TSX_PROBE = 'src/__probe__/Probe.tsx';+const TS_PROBE = 'src/__probe__/probe.ts';++async function messagesFor(code, filePath = TS_PROBE) {+ const [result] = await eslint.lintText(code, { filePath });+ return result.messages;+}++// Presence is not the property these probes defend. `npm run lint` tallies+// severity-2 messages only, so a rule quietly demoted to a warning keeps showing+// up in `messages` while no longer being enforced anywhere: the probe would still+// pass, the baseline would not grow, and the class would retire in silence.+// Every "still reports" case therefore asserts that the rule *errors*.+async function errorRuleIdsFor(code, filePath) {+ return (await messagesFor(code, filePath))+ .filter((message) => message.severity === 2)+ .map((message) => message.ruleId);+}++// The allowed-shape cases stay severity-blind on purpose — that is the stricter+// assertion. A rule that starts merely warning about a shape the convention+// permits is still noise this config exists to prevent.+async function ruleIdsFor(code, filePath) {+ return (await messagesFor(code, filePath)).map((message) => message.ruleId);+}++// ─── what this file is for ───────────────────────────────────────────────────+//+// The enforcement policy itself, and the set of files it applies to, are pinned+// in `scripts/lintPolicy.mjs` and measured at runtime by `npm run lint`: every+// repo-owned .ts/.tsx file, found by walking the tree, must resolve the full+// expected rule configuration. That is a total statement, so it does not belong+// here as a second hand-written copy — earlier revisions kept one (a severity+// map, then a per-entry `{name, files, ignores}` contract) and each was a+// projection with a blind complement, most recently `basePath`.+//+// What stays here is the consuming evidence: resolving a rule for a path is not+// the same as reporting on it, so these probes drive the real config end to end+// and assert the messages the cleanup's conventions depend on.++const rulesFor = async (filePath) => (await eslint.calculateConfigForFile(filePath))?.rules ?? {};++const policyDriftFor = async (filePath) =>+ policyDifferences(effectivePolicyOf(await eslint.calculateConfigForFile(filePath)));++// The runtime invariant can only measure files that exist. These two paths do+// not, which is the one thing it cannot cover: whoever adds the next module+// inherits the policy without anyone re-running anything.+describe('a source file nobody has written yet is already covered', () => {+ it('resolves the pinned policy for an arbitrary new .ts file', async () => {+ expect(await policyDriftFor('src/does/not/exist/yet/newModule.ts')).toEqual([]);+ });++ it('resolves the pinned policy for an arbitrary new .tsx file', async () => {+ expect(await policyDriftFor('src/does/not/exist/yet/NewComponent.tsx')).toEqual([]);+ });++ // Resolving rules for a path is not the same as reporting on it. This asserts+ // the whole way through to a severity-2 message, which is what the gate counts.+ it('errors on new debt in that unwritten file', async () => {+ expect(+ await errorRuleIdsFor('export const f = (v: any) => v;\n', 'src/does/not/exist/yet/newModule.ts'),+ ).toContain('@typescript-eslint/no-explicit-any');+ });++ it('keeps the build output out of the gate', async () => {+ expect(await eslint.isPathIgnored('dist/assets/index-abcdef12.js')).toBe(true);+ });++ // The documented boundary of the TypeScript-only policy. `npm run lint` opens+ // the gate script and the config itself, but the rule map they resolve is+ // exactly empty, so the only thing reportable for them is a fatal parse or+ // config error. Broadening the scope to JS/MJS is a separate decision; this+ // is where it would become visible.+ it('parses the gate script and the config without applying the rule set', async () => {+ expect(await rulesFor('scripts/lint-baseline.mjs')).toEqual({});+ expect(await rulesFor('eslint.config.js')).toEqual({});+ expect(await eslint.isPathIgnored('scripts/lint-baseline.mjs')).toBe(false);+ expect(await eslint.isPathIgnored('eslint.config.js')).toBe(false);+ });+});++const UNUSED = '@typescript-eslint/no-unused-vars';++describe('no-unused-vars honours the `_` opt-out convention', () => {+ it('allows an intentionally unused function parameter', async () => {+ expect(await ruleIdsFor('export const f = (_value: string) => 1;\n')).not.toContain(UNUSED);+ });++ it('allows an intentionally unused local binding', async () => {+ expect(await ruleIdsFor('export function f() {\n const _legacy = 1;\n return 2;\n}\n')).not.toContain(UNUSED);+ });++ it('allows an intentionally unused caught error', async () => {+ expect(await ruleIdsFor('export function f() {\n try {\n JSON.parse("1");\n } catch (_err) {\n return null;\n }\n return 1;\n}\n')).not.toContain(UNUSED);+ });++ it('allows an intentionally unused destructured array slot', async () => {+ expect(await ruleIdsFor('export function f(pair: [number, number]) {\n const [_drop, keep] = pair;\n return keep;\n}\n')).not.toContain(UNUSED);+ });+});++describe('no-unused-vars still errors on genuinely dead bindings', () => {+ it('errors on an unused function parameter that is not opted out', async () => {+ expect(await errorRuleIdsFor('export const f = (value: string) => 1;\n')).toContain(UNUSED);+ });++ it('errors on an unused local binding that is not opted out', async () => {+ expect(await errorRuleIdsFor('export function f() {\n const legacy = 1;\n return 2;\n}\n')).toContain(UNUSED);+ });++ it('errors on an unused caught error that is not opted out', async () => {+ expect(await errorRuleIdsFor('export function f() {\n try {\n JSON.parse("1");\n } catch (err) {\n return null;\n }\n return 1;\n}\n')).toContain(UNUSED);+ });+});++// `src/lib/useLatestRef.ts` carries the only `react-hooks/refs` exemption that is+// not a per-site judgement call. That is defensible only while the rule still+// applies everywhere else: switching it off in the shared config, or dropping it+// to a warning, would silently retire the whole class. Pin both directions.+const REFS = 'react-hooks/refs';+const componentUsing = (body) =>+ `import { useRef } from 'react';\nexport function C({ v }: { v: number }) {\n const r = useRef(v);\n${body}\n}\n`;++describe('react-hooks/refs still errors on the ordinary ref misuse', () => {+ it('errors on a ref read during render', async () => {+ expect(+ await errorRuleIdsFor(componentUsing(' return <div>{r.current}</div>;'), TSX_PROBE),+ ).toContain(REFS);+ });++ it('errors on a ref write during render', async () => {+ expect(+ await errorRuleIdsFor(componentUsing(' r.current = v;\n return <div>ok</div>;'), TSX_PROBE),+ ).toContain(REFS);+ });++ it('leaves a ref touched only from an effect alone', async () => {+ const code =+ "import { useEffect, useRef } from 'react';\n" ++ 'export function C({ v }: { v: number }) {\n' ++ ' const r = useRef(v);\n' ++ ' useEffect(() => {\n r.current = v;\n }, [v]);\n' ++ ' return <div>ok</div>;\n}\n';+ expect(await ruleIdsFor(code, TSX_PROBE)).not.toContain(REFS);+ });+});diff --git a/ui/scripts/lint-baseline.mjs b/ui/scripts/lint-baseline.mjsnew file mode 100644index 000000000..50207c4b3--- /dev/null+++ b/ui/scripts/lint-baseline.mjs@@ -0,0 +1,362 @@+// The lint gate. Runs the same ESLint pass as ``eslint .``, then measures the+// result against ``eslint-baseline.json`` — an explicit, per-file, per-rule+// ledger of the violations that predate the cleanup and are not being fixed in+// it (each rule's rationale lives in the ledger itself).+//+// The ledger tracks two things, because a rule can be silenced two ways:+// ``violations`` — errors ESLint reported.+// ``suppressions`` — messages an inline ``eslint-disable`` comment hid. Left+// unfrozen, adding one of those comments would be a free way past the gate,+// and a suppressed rule also stops the React Compiler analysing that+// component, so the unmeasured area would grow silently.+//+// Counting both still only measures what ESLint was *asked* to look at, so the+// run's own completeness is checked first, before any tally is trusted and+// before ``--update`` may write anything (see ``scripts/lintPolicy.mjs``):+// - every repo-owned ``.ts``/``.tsx`` file under ``ui/`` appears in the run and+// resolves the pinned effective policy, rules and options and all;+// - the walk that produced that list sees everything the run did, so the+// invariant cannot pass by measuring less;+// - no source carries inline configuration outside the ``eslint-disable``+// family, which is the one way to change policy that neither tally records;+// - nothing was reported that has no rule id to be ledgered under.+//+// What the gate rejects on top of that, exactly:+// - a ``(file, rule)`` pair the ledger never recorded;+// - a recorded pair violated more often than the ledger allows;+// - a recorded pair violated less often than the ledger allows, until the+// ledger is updated (``npm run lint:baseline``) — unrecorded slack would+// become budget for new violations, so improvements have to be booked;+// - all three of the above independently for inline suppressions;+// - a rule in the ledger that nobody wrote a rationale for;+// - a rule-less fatal problem: a parse failure, an unresolvable config, a+// plugin that threw. No ledger entry could ever cover one, and a file that+// does not parse reports no violations at all, which a tally reads as clean.+//+// What it does not reject, said plainly so nobody relies on more: the counter is+// keyed on ``(file, rule)``, not on a site. Deleting one baselined violation and+// introducing another of the same rule in the same file leaves the count+// unchanged and passes. That is the accepted residual of a count ratchet — the+// same trade-off ESLint's own ``suppressions-service`` makes — and it is bounded+// on three sides: the pair must already carry recorded debt, the count cannot+// grow, and once the real debt is paid down the stale check forces the allowance+// down with it.+//+// Why a ledger instead of ``eslint-disable`` comments or a relaxed config: both+// of those hide the debt at the site, so nobody can see how much there is or+// whether it is shrinking. One sorted JSON file can be read, diffed, and+// pointed at in review.++import fs from 'node:fs';+import path from 'node:path';+import { fileURLToPath } from 'node:url';++import { ESLint, Linter } from 'eslint';++import sharedConfig from '../eslint.config.js';+import {+ coverageGaps,+ effectivePolicyOf,+ forbiddenInlineConfig,+ groupByDifferences,+ intendedFiles,+ policyDifferences,+ withoutRules,+} from './lintPolicy.mjs';++const UI_ROOT = fileURLToPath(new URL('../', import.meta.url));+const BASELINE_FILE = path.join(UI_ROOT, 'eslint-baseline.json');++/**+ * Compare a fresh lint tally against the recorded one.+ *+ * Both arguments are ``{ [file]: { [rule]: count } }``. The lookup is per+ * (file, rule) — a file appearing in the baseline buys tolerance for the rules+ * recorded against it, nothing more. It is a count, not an identity: within one+ * already-recorded pair, which sites are violating is not compared. See the+ * residual noted in the file header.+ *+ * @returns `unclassified` (rule/file pair the ledger never recorded),+ * `expanded` (recorded pair violated more often than allowed), and `stale`+ * (recorded pair now violated less often, including not at all). Pure.+ */+export function compareToBaseline(baseline, current) {+ const unclassified = [];+ const expanded = [];+ const stale = [];++ for (const [file, rules] of Object.entries(current)) {+ for (const [rule, count] of Object.entries(rules)) {+ const allowed = baseline[file]?.[rule] ?? 0;+ if (allowed === 0) unclassified.push({ file, rule, count });+ else if (count > allowed) expanded.push({ file, rule, count, allowed });+ }+ }++ for (const [file, rules] of Object.entries(baseline)) {+ for (const [rule, allowed] of Object.entries(rules)) {+ const count = current[file]?.[rule] ?? 0;+ if (count < allowed) stale.push({ file, rule, count, allowed });+ }+ }++ return { unclassified, expanded, stale };+}++/**+ * Rule ids carried by a ledger with no entry in ``rationale``.+ *+ * A rule nobody had to explain is how an unrelated error class slips into the+ * ledger and stops being visible. Adding one costs a sentence. Pure.+ */+export function missingRationales(ledgers, rationale) {+ const rules = new Set();+ for (const ledger of ledgers) {+ for (const byRule of Object.values(ledger)) {+ for (const rule of Object.keys(byRule)) {+ if (!rationale?.[rule]) rules.add(rule);+ }+ }+ }+ return [...rules].sort();+}++/**+ * Key a (file, rule) pair.+ *+ * NUL cannot occur in a path or a rule id, so the join is unambiguous where a+ * space or a slash would not be. It is written as an escape rather than typed+ * as a literal byte: a raw NUL makes this whole file binary to git, and a gate+ * everyone is asked to trust has to stay visible in a diff. Pure.+ */+export const pairKey = (file, rule) => `${file}\0${rule}`;++/**+ * Problems ESLint reported with no rule id: a parse failure, an unresolvable+ * config, a plugin that threw.+ *+ * These can never be baselined, because there is no (file, rule) key to record+ * them under. They also cannot be caught by comparing tallies — a file that+ * fails to parse reports no violations at all, which a tally reads as clean.+ * So they are collected separately and fail the gate on their own. Pure.+ */+export function fatalProblems(results) {+ const problems = [];+ for (const result of results) {+ for (const message of result.messages ?? []) {+ if (message.ruleId || message.severity !== 2) continue;+ problems.push({ filePath: result.filePath, line: message.line ?? 0, message: message.message });+ }+ }+ return problems;+}++/** Tally messages into ``{ [file]: { [rule]: count } }`` with sorted keys. */+function tally(results, pick) {+ const byFile = {};+ for (const result of results) {+ const file = path.relative(UI_ROOT, result.filePath).split(path.sep).join('/');+ for (const message of pick(result)) {+ // Rule-less problems have no key to be tallied under; `fatalProblems`+ // owns them, and `reportLines` fails the gate on them unconditionally.+ if (!message.ruleId) continue;+ byFile[file] ??= {};+ byFile[file][message.ruleId] = (byFile[file][message.ruleId] ?? 0) + 1;+ }+ }+ return sortDeep(byFile);+}++function sortDeep(byFile) {+ return Object.fromEntries(+ Object.entries(byFile)+ .sort(([a], [b]) => (a < b ? -1 : 1))+ .map(([file, rules]) => [file, Object.fromEntries(Object.entries(rules).sort(([a], [b]) => (a < b ? -1 : 1)))]),+ );+}++const errorsOf = (result) => result.messages.filter((message) => message.severity === 2);+const suppressedOf = (result) => result.suppressedMessages ?? [];++function describe({ unclassified, expanded, stale }, label) {+ const lines = [];+ for (const { file, rule, count } of unclassified) {+ lines.push(` NEW ${file} ${rule} ${count} ${label} (not in the baseline)`);+ }+ for (const { file, rule, count, allowed } of expanded) {+ lines.push(` EXPANDED ${file} ${rule} ${count} ${label}, baseline allows ${allowed}`);+ }+ for (const { file, rule, count, allowed } of stale) {+ lines.push(` STALE ${file} ${rule} ${count} ${label}, baseline still records ${allowed}`);+ }+ return lines;+}++/**+ * Every reason the measurement itself cannot be trusted, as printable lines.+ * Empty means the run looked at everything it claims to.+ *+ * These are the checks a tally comparison structurally cannot make, so they are+ * kept out of the drift verdict and run ahead of it — including ahead of+ * ``--update``, because a baseline written from an incomplete run records the+ * wrong thing and then blesses it. The whole verdict lives in one pure function+ * so "an incomplete measurement fails even when every tally matches" is a+ * property a test can hold onto rather than a branch buried in the IO path. Pure.+ */+export function integrityLines({ fatals, coverage, policyGroups, inlineViolations }) {+ const lines = fatals.map(({ filePath, line, message }) => ` FATAL ${filePath}:${line} ${message}`);++ if (coverage.empty) {+ lines.push(' DOMAIN the walk found no TypeScript sources at all, so nothing was measured');+ }+ for (const file of coverage.missing) {+ lines.push(` UNLINTED ${file} is repo-owned TypeScript the lint run never opened`);+ }+ for (const file of coverage.unwalked) {+ lines.push(` UNWALKED ${file} was linted but the domain walk missed it, so the walk is blind`);+ }+ for (const { differences, files } of policyGroups) {+ lines.push(` POLICY ${files.length} file(s) resolve a different policy (${preview(files)}):`);+ for (const difference of differences) lines.push(` ${difference}`);+ }+ for (const { file, line, column, text } of inlineViolations) {+ lines.push(` INLINE ${file}:${line}:${column} inline configuration outside the eslint-disable family: ${text}`);+ }++ return lines;+}++const preview = (files, limit = 3) =>+ files.length <= limit ? files.join(', ') : `${files.slice(0, limit).join(', ')}, +${files.length - limit} more`;++/**+ * Every reason this run should fail on recorded debt, as printable lines. Empty+ * means pass. Pure.+ */+export function reportLines({ violationDrift, suppressionDrift, unexplained }) {+ return [+ ...describe(violationDrift, 'errors'),+ ...describe(suppressionDrift, 'suppressed messages'),+ ...unexplained.map((rule) => ` UNEXPLAINED ${rule} is in the baseline with no "rationale" entry`),+ ];+}++const total = (byFile) =>+ Object.values(byFile).reduce((sum, rules) => sum + Object.values(rules).reduce((a, b) => a + b, 0), 0);++const relative = (filePath) => path.relative(UI_ROOT, filePath).split(path.sep).join('/');++/**+ * Measure the run's completeness: what the domain contains, whether ESLint+ * opened all of it under the pinned policy, and whether any source rewrote that+ * policy inline.+ */+async function measureIntegrity(eslint, results) {+ const intended = intendedFiles(UI_ROOT);++ const perFile = [];+ for (const file of intended) {+ const config = await eslint.calculateConfigForFile(path.join(UI_ROOT, file));+ perFile.push({ file, differences: policyDifferences(effectivePolicyOf(config)) });+ }++ return {+ intended,+ fatals: fatalProblems(results).map((problem) => ({ ...problem, filePath: relative(problem.filePath) })),+ coverage: coverageGaps({ intended, lintedFiles: results.map((result) => relative(result.filePath)) }),+ policyGroups: groupByDifferences(perFile),+ inlineViolations: forbiddenInlineConfig({+ root: UI_ROOT,+ files: intended,+ config: withoutRules(sharedConfig),+ linter: new Linter(),+ }),+ };+}++async function main() {+ const update = process.argv.includes('--update');+ const eslint = new ESLint();+ const results = await eslint.lintFiles(['.']);++ // Unconditional, and first: an incomplete or bypassed measurement can neither+ // pass nor be written to the baseline.+ const measurement = await measureIntegrity(eslint, results);+ const integrity = integrityLines(measurement);+ if (integrity.length > 0) {+ console.error('Lint gate integrity check failed:');+ console.error(integrity.join('\n'));+ console.error(+ '\nThe lint run did not measure what it claims to, so neither its verdict nor\n' ++ '"npm run lint:baseline" means anything until this is fixed.',+ );+ process.exitCode = 1;+ return;+ }++ const violations = tally(results, errorsOf);+ const suppressions = tally(results, suppressedOf);++ if (update) {+ const previous = fs.existsSync(BASELINE_FILE) ? JSON.parse(fs.readFileSync(BASELINE_FILE, 'utf8')) : {};+ const next = { ...previous, violations, suppressions };+ fs.writeFileSync(BASELINE_FILE, `${JSON.stringify(next, null, 2)}\n`);+ console.log(+ `Wrote eslint-baseline.json: ${total(violations)} violations, ${total(suppressions)} suppressions.`,+ );+ return;+ }++ if (!fs.existsSync(BASELINE_FILE)) {+ throw new Error(`Missing ${path.relative(UI_ROOT, BASELINE_FILE)}. Run "npm run lint:baseline" to create it.`);+ }+ const baseline = JSON.parse(fs.readFileSync(BASELINE_FILE, 'utf8'));++ const violationDrift = compareToBaseline(baseline.violations ?? {}, violations);+ const lines = reportLines({+ violationDrift,+ suppressionDrift: compareToBaseline(baseline.suppressions ?? {}, suppressions),+ unexplained: missingRationales([baseline.violations ?? {}, baseline.suppressions ?? {}], baseline.rationale),+ });++ if (lines.length > 0) {+ // Show the offending code for anything that is new or has grown, so the+ // failure reads like a normal lint failure rather than a bookkeeping one.+ const offenders = new Set(+ [...violationDrift.unclassified, ...violationDrift.expanded].map(({ file, rule }) => pairKey(file, rule)),+ );+ const focused = results+ .map((result) => {+ const file = relative(result.filePath);+ const messages = errorsOf(result).filter((message) => offenders.has(pairKey(file, message.ruleId)));+ return { ...result, messages, warningCount: 0, suppressedMessages: [] };+ })+ .filter((result) => result.messages.length > 0);+ if (focused.length > 0) {+ const formatter = await eslint.loadFormatter('stylish');+ console.log(await formatter.format(focused));+ }++ console.error('Lint baseline check failed:');+ console.error(lines.join('\n'));+ console.error(+ '\nFix the reported problems. If a violation is genuinely intentional legacy debt,\n' ++ 'raising the baseline needs a reviewer to agree in the PR — it is not a routine step.\n' ++ 'If the drift is an improvement (STALE), record it with "npm run lint:baseline".',+ );+ process.exitCode = 1;+ return;+ }++ console.log(+ `Lint baseline check passed: ${measurement.intended.length} TypeScript sources all measured ` ++ `under the pinned policy, ${total(violations)} baselined violations, ` ++ `${total(suppressions)} baselined suppressions, no fatal problems, ` ++ 'no inline policy overrides, and no drift in any (file, rule) pair.',+ );+}++// ``import.meta.main`` is Node 24+; this checkout still supports Node 20.+if (process.argv[1] && fileURLToPath(import.meta.url) === path.resolve(process.argv[1])) {+ await main();+}diff --git a/ui/scripts/lintBaseline.test.mjs b/ui/scripts/lintBaseline.test.mjsnew file mode 100644index 000000000..b84b70727--- /dev/null+++ b/ui/scripts/lintBaseline.test.mjs@@ -0,0 +1,333 @@+import { spawnSync } from 'node:child_process';+import fs from 'node:fs';+import path from 'node:path';+import { fileURLToPath } from 'node:url';++import { describe, expect, it } from 'vitest';++import {+ compareToBaseline,+ fatalProblems,+ integrityLines,+ missingRationales,+ pairKey,+ reportLines,+} from './lint-baseline.mjs';++// The ratchet's whole value is in this comparison: it decides what counts as new+// debt. Every branch is pinned here so the gate can't be widened by accident —+// a bug that turns "unclassified" into "allowed" would silently reopen the door+// the baseline exists to close.++describe('compareToBaseline accepts the recorded debt unchanged', () => {+ it('reports nothing when the counts match exactly', () => {+ const ledger = { 'src/a.ts': { 'no-explicit-any': 3 }, 'src/b.ts': { 'set-state-in-effect': 1 } };+ expect(compareToBaseline(ledger, structuredClone(ledger))).toEqual({+ unclassified: [],+ expanded: [],+ stale: [],+ });+ });++ // The gate is a count ratchet, so a violation deleted at one site and+ // reintroduced at another inside the same (file, rule) pair passes. Recorded+ // as an intended property rather than left implicit: a reader who assumes+ // otherwise is relying on a guarantee this file does not make, and the same+ // trade-off is the one ESLint's own suppressions file makes.+ it('accepts a baselined violation replaced one-for-one within the same pair', () => {+ const ledger = { 'src/a.ts': { 'no-explicit-any': 3 } };+ expect(compareToBaseline(ledger, { 'src/a.ts': { 'no-explicit-any': 3 } })).toEqual({+ unclassified: [],+ expanded: [],+ stale: [],+ });+ });++ // The bound on that residual, in one place: a swap can only ever hide inside+ // debt that is already recorded, at a count that cannot grow, in the file that+ // already carries it.+ it('catches the same swap the moment it changes the count, the rule or the file', () => {+ const ledger = { 'src/a.ts': { 'no-explicit-any': 3 } };+ expect(compareToBaseline(ledger, { 'src/a.ts': { 'no-explicit-any': 4 } }).expanded).toHaveLength(1);+ expect(compareToBaseline(ledger, { 'src/a.ts': { 'no-explicit-any': 3, 'no-empty': 1 } }).unclassified)+ .toHaveLength(1);+ expect(compareToBaseline(ledger, { 'src/b.ts': { 'no-explicit-any': 3 } }).unclassified).toHaveLength(1);+ });+});++describe('compareToBaseline fails on new debt', () => {+ it('flags a rule violated in a file the baseline never listed', () => {+ const { unclassified } = compareToBaseline({}, { 'src/new.ts': { 'no-explicit-any': 1 } });+ expect(unclassified).toEqual([{ file: 'src/new.ts', rule: 'no-explicit-any', count: 1 }]);+ });++ it('flags a rule new to a file that already carries other baselined debt', () => {+ // The lookup has to be per (file, rule). A file-level check would let every+ // other rule in an already-listed file through unnoticed.+ const { unclassified, expanded } = compareToBaseline(+ { 'src/a.ts': { 'no-explicit-any': 3 } },+ { 'src/a.ts': { 'no-explicit-any': 3, 'set-state-in-effect': 2 } },+ );+ expect(unclassified).toEqual([{ file: 'src/a.ts', rule: 'set-state-in-effect', count: 2 }]);+ expect(expanded).toEqual([]);+ });++ it('flags a baselined rule violated more often than recorded', () => {+ const { expanded, unclassified } = compareToBaseline(+ { 'src/a.ts': { 'no-explicit-any': 3 } },+ { 'src/a.ts': { 'no-explicit-any': 4 } },+ );+ expect(expanded).toEqual([{ file: 'src/a.ts', rule: 'no-explicit-any', count: 4, allowed: 3 }]);+ expect(unclassified).toEqual([]);+ });+});++describe('compareToBaseline fails on a baseline that overstates the debt', () => {+ // Improvements have to be recorded, otherwise the freed-up headroom silently+ // becomes budget for new violations and the ratchet stops ratcheting.+ it('flags a rule now violated less often than recorded', () => {+ const { stale } = compareToBaseline(+ { 'src/a.ts': { 'no-explicit-any': 3 } },+ { 'src/a.ts': { 'no-explicit-any': 1 } },+ );+ expect(stale).toEqual([{ file: 'src/a.ts', rule: 'no-explicit-any', count: 1, allowed: 3 }]);+ });++ it('flags a rule that is now clean', () => {+ const { stale } = compareToBaseline({ 'src/a.ts': { 'no-explicit-any': 3 } }, {});+ expect(stale).toEqual([{ file: 'src/a.ts', rule: 'no-explicit-any', count: 0, allowed: 3 }]);+ });++ it('flags every rule of a file that no longer exists', () => {+ const { stale } = compareToBaseline(+ { 'src/gone.ts': { 'no-explicit-any': 2, 'set-state-in-effect': 1 } },+ { 'src/a.ts': { 'no-explicit-any': 1 } },+ );+ expect(stale).toEqual([+ { file: 'src/gone.ts', rule: 'no-explicit-any', count: 0, allowed: 2 },+ { file: 'src/gone.ts', rule: 'set-state-in-effect', count: 0, allowed: 1 },+ ]);+ // The unrelated file is new debt, not an excuse to drop the stale report.+ expect(compareToBaseline({ 'src/gone.ts': { 'no-explicit-any': 2 } }, { 'src/a.ts': { 'no-explicit-any': 1 } }).unclassified)+ .toEqual([{ file: 'src/a.ts', rule: 'no-explicit-any', count: 1 }]);+ });+});++describe('missingRationales keeps the ledger self-explaining', () => {+ const violations = { 'src/a.ts': { 'no-explicit-any': 3 } };+ const suppressions = { 'src/b.ts': { 'exhaustive-deps': 1 } };++ it('accepts a ledger where every rule is explained', () => {+ const rationale = { 'no-explicit-any': 'Untyped API payloads.', 'exhaustive-deps': 'Deliberate.' };+ expect(missingRationales([violations, suppressions], rationale)).toEqual([]);+ });++ it('names a rule that reached the ledger without an explanation', () => {+ expect(missingRationales([violations, suppressions], { 'no-explicit-any': 'Untyped API payloads.' }))+ .toEqual(['exhaustive-deps']);+ });++ it('treats an empty explanation as no explanation', () => {+ expect(missingRationales([violations], { 'no-explicit-any': '' })).toEqual(['no-explicit-any']);+ });++ it('names every unexplained rule once, sorted', () => {+ expect(missingRationales([{ 'src/a.ts': { zeta: 1, alpha: 1 }, 'src/b.ts': { alpha: 2 } }, {}], {}))+ .toEqual(['alpha', 'zeta']);+ });+});++describe('fatalProblems catches what the ledger structurally cannot', () => {+ // A parse failure, an invalid config or a plugin that threw is reported with+ // no rule id, so there is no (file, rule) key to baseline it under. Worse, a+ // file that does not parse yields no violations at all, so a pure tally+ // comparison reads it as clean. These have to fail the gate on their own.+ const message = (over = {}) => ({ ruleId: null, severity: 2, line: 1, message: 'Parsing error: ;', ...over });++ it('finds a rule-less error', () => {+ const results = [{ filePath: '/ui/src/broken.ts', messages: [message()] }];+ expect(fatalProblems(results)).toEqual([+ { filePath: '/ui/src/broken.ts', line: 1, message: 'Parsing error: ;' },+ ]);+ });++ it('ignores ordinary rule violations, which the ledger does own', () => {+ const results = [+ { filePath: '/ui/src/a.ts', messages: [{ ruleId: 'no-explicit-any', severity: 2, line: 3, message: 'any' }] },+ ];+ expect(fatalProblems(results)).toEqual([]);+ });++ it('ignores a rule-less warning, which does not gate anything', () => {+ const results = [{ filePath: '/ui/src/a.ts', messages: [message({ severity: 1 })] }];+ expect(fatalProblems(results)).toEqual([]);+ });++ it('tolerates a result with no messages array', () => {+ expect(fatalProblems([{ filePath: '/ui/src/a.ts' }])).toEqual([]);+ });+});++describe('reportLines turns recorded-debt drift into a verdict', () => {+ const clean = { unclassified: [], expanded: [], stale: [] };++ it('reports nothing when the run is genuinely clean', () => {+ expect(reportLines({ violationDrift: clean, suppressionDrift: clean, unexplained: [] })).toEqual([]);+ });++ it('reports drift and unexplained rules together', () => {+ const lines = reportLines({+ violationDrift: { unclassified: [{ file: 'src/a.ts', rule: 'no-explicit-any', count: 1 }], expanded: [], stale: [] },+ suppressionDrift: clean,+ unexplained: ['mystery-rule'],+ });+ expect(lines.filter((line) => line.includes('NEW'))).toHaveLength(1);+ expect(lines.filter((line) => line.includes('UNEXPLAINED'))).toHaveLength(1);+ });+});++describe('integrityLines fails on an incomplete measurement even when every tally matches', () => {+ // The unconditional half. `reportLines` can only speak about what was found;+ // everything here is a way the run looked at less than it claims to, which no+ // tally comparison can detect because the tally comes out clean.+ const sound = { fatals: [], coverage: { empty: false, missing: [], unwalked: [] }, policyGroups: [], inlineViolations: [] };++ it('reports nothing when the measurement is complete', () => {+ expect(integrityLines(sound)).toEqual([]);+ });++ it('fails when a file stopped parsing, which yields no violations to count', () => {+ const lines = integrityLines({+ ...sound,+ fatals: [{ filePath: 'src/broken.ts', line: 4, message: 'Parsing error: ;' }],+ });+ expect(lines).toHaveLength(1);+ expect(lines[0]).toContain('FATAL');+ expect(lines[0]).toContain('src/broken.ts');+ expect(lines[0]).toContain('Parsing error: ;');+ });++ it('fails when repo-owned TypeScript was never opened', () => {+ const lines = integrityLines({ ...sound, coverage: { empty: false, missing: ['vite.config.ts'], unwalked: [] } });+ expect(lines).toHaveLength(1);+ expect(lines[0]).toContain('UNLINTED');+ expect(lines[0]).toContain('vite.config.ts');+ });++ it('fails when the domain walk missed a file the run did open', () => {+ const lines = integrityLines({ ...sound, coverage: { empty: false, missing: [], unwalked: ['src/hidden.tsx'] } });+ expect(lines).toHaveLength(1);+ expect(lines[0]).toContain('UNWALKED');+ });++ it('fails when the walk found nothing, instead of passing vacuously', () => {+ const lines = integrityLines({ ...sound, coverage: { empty: true, missing: [], unwalked: [] } });+ expect(lines).toHaveLength(1);+ expect(lines[0]).toContain('DOMAIN');+ });++ it('fails when the effective policy drifted, printing one entry per distinct drift', () => {+ const lines = integrityLines({+ ...sound,+ policyGroups: [+ {+ differences: ['rule config changed — @typescript-eslint/no-explicit-any: expected [2], resolved [1]'],+ files: Array.from({ length: 514 }, (_, index) => `src/f${index}.ts`),+ },+ ],+ });+ // Grouped: a config-wide drift is one finding, not 514 copies of it.+ expect(lines).toHaveLength(2);+ expect(lines[0]).toContain('POLICY 514 file(s)');+ expect(lines[0]).toContain('+511 more');+ expect(lines[1]).toContain('no-explicit-any');+ });++ it('fails when a source rewrote policy inline', () => {+ const lines = integrityLines({+ ...sound,+ inlineViolations: [{ file: 'src/a.ts', line: 1, column: 1, text: '/* eslint no-var: "off" */' }],+ });+ expect(lines).toHaveLength(1);+ expect(lines[0]).toContain('INLINE');+ expect(lines[0]).toContain('src/a.ts:1:1');+ });++ it('reports every kind at once rather than stopping at the first', () => {+ const lines = integrityLines({+ fatals: [{ filePath: 'src/broken.ts', line: 4, message: 'Parsing error: ;' }],+ coverage: { empty: true, missing: ['vite.config.ts'], unwalked: ['src/hidden.tsx'] },+ policyGroups: [{ differences: ['parser: expected "x", resolved "y"'], files: ['src/a.ts'] }],+ inlineViolations: [{ file: 'src/a.ts', line: 1, column: 1, text: '/* eslint no-var: "off" */' }],+ });+ for (const label of ['FATAL', 'DOMAIN', 'UNLINTED', 'UNWALKED', 'POLICY', 'INLINE']) {+ expect(lines.some((line) => line.includes(label)), label).toBe(true);+ }+ });+});++describe('an incomplete measurement blocks --update too, not just the verdict', () => {+ // The ordering has to hold in the real script: `lint:baseline` exists to+ // rewrite the ledger, so if it ran before the integrity checks, any of the+ // failures above could be laundered into a freshly written green baseline.+ // Asserted against the actual command rather than an injected fake, because a+ // fake would only pin the ordering a test author already imagined.+ const UI_ROOT = fileURLToPath(new URL('../', import.meta.url));+ const BASELINE = path.join(UI_ROOT, 'eslint-baseline.json');+ const PROBE = path.join(UI_ROOT, 'update-integrity-probe.ts');++ const runGate = (args) =>+ spawnSync(process.execPath, ['scripts/lint-baseline.mjs', ...args], {+ cwd: UI_ROOT,+ encoding: 'utf8',+ timeout: 300_000,+ });++ it('refuses to write a baseline while an integrity check is failing', () => {+ const before = fs.readFileSync(BASELINE);+ try {+ fs.writeFileSync(PROBE, '/* eslint @typescript-eslint/no-explicit-any: "off" */\nexport const f = (v: any) => v;\n');+ const result = runGate(['--update']);+ expect(result.status).toBe(1);+ expect(result.stderr).toContain('INLINE');+ expect(result.stderr).toContain('update-integrity-probe.ts');+ expect(fs.readFileSync(BASELINE).equals(before)).toBe(true);+ } finally {+ fs.rmSync(PROBE, { force: true });+ fs.writeFileSync(BASELINE, before);+ }+ }, 300_000);+});++describe('the gate script stays reviewable text', () => {+ const source = fs.readFileSync(fileURLToPath(new URL('./lint-baseline.mjs', import.meta.url)));++ it('contains no raw NUL byte', () => {+ // The (file, rule) key joins on NUL. Written as a literal byte it makes the+ // whole script binary to git, so the gate everyone is asked to trust stops+ // showing up in diffs and review. The escape has identical runtime meaning.+ expect(source.includes(0)).toBe(false);+ });++ it('still joins the pair on a character neither half can contain', () => {+ expect(pairKey('src/a.ts', 'no-explicit-any')).toBe('src/a.ts\0no-explicit-any');+ });++ it('cannot confuse two different pairs that share a prefix', () => {+ expect(pairKey('src/a.ts', 'b/c')).not.toBe(pairKey('src/a.ts b', 'c'));+ });+});++describe('compareToBaseline cannot pass vacuously', () => {+ it('fails when the lint run produced nothing at all', () => {+ // A broken glob or a crashed ESLint run yields an empty report. That must+ // read as "the measurement is gone", never as "the code is clean".+ const { stale } = compareToBaseline({ 'src/a.ts': { 'no-explicit-any': 3 } }, {});+ expect(stale).toHaveLength(1);+ });++ it('reports an empty baseline against an empty run as clean', () => {+ // The one honest empty case: nothing recorded, nothing found.+ expect(compareToBaseline({}, {})).toEqual({ unclassified: [], expanded: [], stale: [] });+ });+});diff --git a/ui/scripts/lintPolicy.mjs b/ui/scripts/lintPolicy.mjsnew file mode 100644index 000000000..12ec80146--- /dev/null+++ b/ui/scripts/lintPolicy.mjs@@ -0,0 +1,394 @@+// The lint domain and the policy that applies across it, as one reviewable+// subject shared by the gate (``scripts/lint-baseline.mjs``) and its tests.+//+// ``eslint-baseline.json`` records what ESLint *found*, never what it was asked+// to *look at*. Anything that shrinks the second — a narrowed scope, a demoted+// rule, a swapped parser, an inline override — pays debt down on paper while the+// ledger stays green. Earlier revisions tried to close that with hand-written+// projections of the config (the warning ids, the disabled ids, a union of+// ``files``, each entry's ``{name, files, ignores}``), and every one of them had+// a blind complement: ``basePath`` narrows an entry's reach without touching any+// field those projections listed.+//+// So the domain is not enumerated here at all. It is *measured*: every+// repo-owned ``.ts``/``.tsx`` file under ``ui/``, found by walking the tree,+// minus only the two roots the declared policy already places outside it+// (``node_modules``, ``dist``). Each of those files must appear in the ESLint run+// and must resolve exactly ``EXPECTED_POLICY``. A new nested source file, a new+// root-level config script, a directory nobody remembered — all measured, with+// nothing to keep in sync.+//+// ``EXPECTED_POLICY`` is the full resolved configuration, not a projection of it:+// every rule with its options, plus the boundaries that can stop a rule running+// even when the rule map is intact (parser identity, ECMAScript and module+// settings, processor, plugin ids, linter options, globals). A dependency upgrade+// is meant to fail here — the diff is the review prompt, and it is the only place+// a change in enforcement policy becomes visible before it silently changes what+// the ledger is allowed to record.++import fs from 'node:fs';+import path from 'node:path';++import { EXPECTED_BROWSER_GLOBALS } from './browserGlobals.mjs';++/**+ * Directory names the declared lint policy already places outside the domain:+ * ``node_modules`` is not repo-owned, and ``dist`` is build output that+ * ``eslint.config.js`` globally ignores. Nothing else may be excluded — an+ * exclusion here is a hole in the invariant, so the list is meant to stay at two.+ */+export const DEPENDENCY_ROOTS = ['node_modules', 'dist'];++/** The extensions the shared config's rule-bearing entry claims. */+export const INTENDED_EXTENSIONS = ['.ts', '.tsx'];++/**+ * Every rule the shared config resolves for a TypeScript source, with its+ * options, sorted by rule id.+ *+ * Severity alone was not enough: a preset that keeps a rule at error while+ * loosening its options enforces less and reads as unchanged. The value here is+ * exactly what ``calculateConfigForFile`` returns, so the comparison is equality+ * against the whole thing.+ *+ * Level 0 is not "we switched it off". It is a base ESLint rule that+ * ``typescript-eslint``'s recommended preset disables because a type-aware+ * equivalent supersedes it.+ */+export const EXPECTED_RULES = {+ '@typescript-eslint/ban-ts-comment': [2],+ '@typescript-eslint/no-array-constructor': [2],+ '@typescript-eslint/no-duplicate-enum-values': [2],+ '@typescript-eslint/no-empty-object-type': [2],+ '@typescript-eslint/no-explicit-any': [2],+ '@typescript-eslint/no-extra-non-null-assertion': [2],+ '@typescript-eslint/no-misused-new': [2],+ '@typescript-eslint/no-namespace': [2],+ '@typescript-eslint/no-non-null-asserted-optional-chain': [2],+ '@typescript-eslint/no-require-imports': [2],+ '@typescript-eslint/no-this-alias': [2],+ '@typescript-eslint/no-unnecessary-type-constraint': [2],+ '@typescript-eslint/no-unsafe-declaration-merging': [2],+ '@typescript-eslint/no-unsafe-function-type': [2],+ '@typescript-eslint/no-unused-expressions': [2, { allowShortCircuit: false, allowTaggedTemplates: false, allowTernary: false }],+ // The `^_` opt-out convention the cleanup standardised on. Behaviourally+ // probed in `eslintConventions.test.mjs`; pinned as configuration here.+ '@typescript-eslint/no-unused-vars': [2, { argsIgnorePattern: '^_', varsIgnorePattern: '^_', caughtErrorsIgnorePattern: '^_', destructuredArrayIgnorePattern: '^_' }],+ '@typescript-eslint/no-wrapper-object-types': [2],+ '@typescript-eslint/prefer-as-const': [2],+ '@typescript-eslint/prefer-namespace-keyword': [2],+ '@typescript-eslint/triple-slash-reference': [2],+ 'constructor-super': [0],+ 'for-direction': [2],+ 'getter-return': [0, { allowImplicit: false }],+ 'no-array-constructor': [0],+ 'no-async-promise-executor': [2],+ 'no-case-declarations': [2],+ 'no-class-assign': [0],+ 'no-compare-neg-zero': [2],+ 'no-cond-assign': [2, 'except-parens'],+ 'no-const-assign': [0],+ 'no-constant-binary-expression': [2],+ 'no-constant-condition': [2, { checkLoops: 'allExceptWhileTrue' }],+ 'no-control-regex': [2],+ 'no-debugger': [2],+ 'no-delete-var': [2],+ 'no-dupe-args': [0],+ 'no-dupe-class-members': [0],+ 'no-dupe-else-if': [2],+ 'no-dupe-keys': [0],+ 'no-duplicate-case': [2],+ 'no-empty': [2, { allowEmptyCatch: false }],+ 'no-empty-character-class': [2],+ 'no-empty-pattern': [2, { allowObjectPatternsAsParameters: false }],+ 'no-empty-static-block': [2],+ 'no-ex-assign': [2],+ 'no-extra-boolean-cast': [2, {}],+ 'no-fallthrough': [2, { allowEmptyCase: false, reportUnusedFallthroughComment: false }],+ 'no-func-assign': [0],+ 'no-global-assign': [2, { exceptions: [] }],+ 'no-import-assign': [0],+ 'no-invalid-regexp': [2, {}],+ 'no-irregular-whitespace': [2, { skipComments: false, skipJSXText: false, skipRegExps: false, skipStrings: true, skipTemplates: false }],+ 'no-loss-of-precision': [2],+ 'no-misleading-character-class': [2, { allowEscape: false }],+ 'no-new-native-nonconstructor': [0],+ 'no-new-symbol': [0],+ 'no-nonoctal-decimal-escape': [2],+ 'no-obj-calls': [0],+ 'no-octal': [2],+ 'no-prototype-builtins': [2],+ 'no-redeclare': [0, { builtinGlobals: true }],+ 'no-regex-spaces': [2],+ 'no-self-assign': [2, { props: true }],+ 'no-setter-return': [0],+ 'no-shadow-restricted-names': [2, { reportGlobalThis: false }],+ 'no-sparse-arrays': [2],+ 'no-this-before-super': [0],+ 'no-undef': [0, { typeof: false }],+ 'no-unexpected-multiline': [2],+ 'no-unreachable': [0],+ 'no-unsafe-finally': [2],+ 'no-unsafe-negation': [0, { enforceForOrderingRelations: false }],+ 'no-unsafe-optional-chaining': [2, { disallowArithmeticOperators: false }],+ 'no-unused-expressions': [0, { allowShortCircuit: false, allowTernary: false, allowTaggedTemplates: false, enforceForJSX: false, ignoreDirectives: false }],+ 'no-unused-labels': [2],+ 'no-unused-private-class-members': [2],+ 'no-unused-vars': [0],+ 'no-useless-backreference': [2],+ 'no-useless-catch': [2],+ 'no-useless-escape': [2, { allowRegexCharacters: [] }],+ 'no-var': [2],+ 'no-with': [0],+ 'prefer-const': [2, { destructuring: 'any', ignoreReadBeforeAssign: false }],+ 'prefer-rest-params': [2],+ 'prefer-spread': [2],+ 'react-hooks/component-hook-factories': [2],+ 'react-hooks/config': [2],+ 'react-hooks/error-boundaries': [2],+ 'react-hooks/exhaustive-deps': [1], // deliberate: the remaining warnings are ledgered, not fixed+ 'react-hooks/gating': [2],+ 'react-hooks/globals': [2],+ 'react-hooks/immutability': [2],+ 'react-hooks/incompatible-library': [1], // deliberate: upstream advisory about libraries the compiler cannot analyse+ 'react-hooks/preserve-manual-memoization': [2],+ 'react-hooks/purity': [2],+ 'react-hooks/refs': [2],+ 'react-hooks/rules-of-hooks': [2],+ 'react-hooks/set-state-in-effect': [2],+ 'react-hooks/set-state-in-render': [2],+ 'react-hooks/static-components': [2],+ 'react-hooks/unsupported-syntax': [1], // deliberate: upstream advisory about syntax the compiler cannot analyse+ 'react-hooks/use-memo': [2],+ 'react-refresh/only-export-components': [2, { allowConstantExport: true }],+ 'require-yield': [2],+ 'use-isnan': [2, { enforceForIndexOf: false, enforceForSwitchCase: true }],+ 'valid-typeof': [2, { requireStringLiterals: false }],+};++/**+ * The whole effective policy an intended file must resolve.+ *+ * Everything outside ``rules`` is a boundary that can stop rules running while+ * the rule map still looks right: a parser that cannot see TypeScript reports+ * nothing, a processor rewrites what the rules are handed, a missing plugin id+ * makes its rules unresolvable, ``linterOptions`` decides whether unused+ * suppressions are surfaced, and ``globals`` decides which identifiers exist.+ *+ * Every field is a committed value. ``globals`` is the one that could not be+ * written inline — see ``./browserGlobals.mjs`` for why it is a snapshot and not+ * a read of the same dependency the resolved config derives from.+ */+export const EXPECTED_POLICY = {+ rules: EXPECTED_RULES,+ parser: 'typescript-eslint/parser',+ ecmaVersion: 2020,+ sourceType: 'module',+ parserOptions: {},+ processor: null,+ plugins: ['@', '@typescript-eslint', 'react-hooks', 'react-refresh'],+ linterOptions: { reportUnusedDisableDirectives: 1 },+ globals: EXPECTED_BROWSER_GLOBALS,+};++/**+ * Every repo-owned ``.ts``/``.tsx`` file under ``root``, relative and sorted.+ *+ * Dirent-based so nothing has to be listed by hand. Symlink handling mirrors+ * ESLint's own traversal exactly, because the two lists are compared in both+ * directions and any disagreement would read as a coverage failure that no edit+ * can fix: a symlinked *file* is linted and so is walked, a symlinked+ * *directory* is not descended into by either side. That also means the walk has+ * no cycle to guard against.+ */+export function intendedFiles(root, { excluded = DEPENDENCY_ROOTS } = {}) {+ const found = [];++ const walk = (dir) => {+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {+ const full = path.join(dir, entry.name);+ if (entry.isDirectory()) {+ if (!excluded.includes(entry.name)) walk(full);+ } else if (INTENDED_EXTENSIONS.some((extension) => entry.name.endsWith(extension))) {+ found.push(path.relative(root, full).split(path.sep).join('/'));+ }+ }+ };++ walk(root);+ return found.sort();+}++/**+ * Project a resolved ESLint config into the shape ``EXPECTED_POLICY`` pins.+ *+ * ``null`` in, ``null`` out: ``calculateConfigForFile`` returns nothing for a+ * path no config entry matches, which is precisely the failure a scope narrowing+ * produces. Pure.+ */+export function effectivePolicyOf(config) {+ if (!config) return null;+ const languageOptions = config.languageOptions ?? {};+ return {+ rules: config.rules ?? {},+ parser: languageOptions.parser?.meta?.name ?? languageOptions.parser?.name ?? null,+ ecmaVersion: languageOptions.ecmaVersion ?? null,+ sourceType: languageOptions.sourceType ?? null,+ parserOptions: languageOptions.parserOptions ?? {},+ processor: config.processor ?? null,+ plugins: Object.keys(config.plugins ?? {}).sort(),+ linterOptions: config.linterOptions ?? {},+ globals: languageOptions.globals ?? {},+ };+}++const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);+const preview = (ids, limit = 5) =>+ ids.length <= limit ? ids.join(', ') : `${ids.slice(0, limit).join(', ')}, +${ids.length - limit} more`;++/**+ * Every way ``actual`` departs from ``expected``, as printable lines.+ *+ * Empty means the file resolves the pinned policy exactly. Sorted and+ * deterministic, so identical drift on many files produces one identical+ * signature to group on. Pure.+ */+export function policyDifferences(actual, expected = EXPECTED_POLICY) {+ if (actual === null || actual === undefined) {+ return ['no ESLint configuration matches this file, so nothing about it is linted'];+ }++ const lines = [];++ const missing = Object.keys(expected.rules).filter((rule) => !(rule in actual.rules));+ const unexpected = Object.keys(actual.rules).filter((rule) => !(rule in expected.rules));+ const changed = Object.keys(expected.rules)+ .filter((rule) => rule in actual.rules && !same(actual.rules[rule], expected.rules[rule]))+ .map((rule) => `${rule}: expected ${JSON.stringify(expected.rules[rule])}, resolved ${JSON.stringify(actual.rules[rule])}`);+ if (missing.length > 0) lines.push(`${missing.length} pinned rule(s) no longer resolve: ${preview(missing.sort())}`);+ if (unexpected.length > 0) lines.push(`${unexpected.length} unpinned rule(s) resolve: ${preview(unexpected.sort())}`);+ for (const line of changed.sort()) lines.push(`rule config changed — ${line}`);++ for (const key of ['parser', 'ecmaVersion', 'sourceType', 'processor']) {+ if (!same(actual[key], expected[key])) {+ lines.push(`${key}: expected ${JSON.stringify(expected[key])}, resolved ${JSON.stringify(actual[key])}`);+ }+ }+ for (const key of ['parserOptions', 'plugins', 'linterOptions']) {+ if (!same(actual[key], expected[key])) {+ lines.push(`${key}: expected ${JSON.stringify(expected[key])}, resolved ${JSON.stringify(actual[key])}`);+ }+ }++ const globalsMissing = Object.keys(expected.globals).filter((name) => !(name in actual.globals));+ const globalsExtra = Object.keys(actual.globals).filter((name) => !(name in expected.globals));+ const globalsChanged = Object.keys(expected.globals).filter(+ (name) => name in actual.globals && actual.globals[name] !== expected.globals[name],+ );+ if (globalsMissing.length > 0) lines.push(`${globalsMissing.length} expected global(s) absent: ${preview(globalsMissing.sort())}`);+ if (globalsExtra.length > 0) lines.push(`${globalsExtra.length} unexpected global(s): ${preview(globalsExtra.sort())}`);+ if (globalsChanged.length > 0) lines.push(`${globalsChanged.length} global(s) changed writability: ${preview(globalsChanged.sort())}`);++ return lines;+}++/**+ * Fold per-file differences into one entry per distinct signature.+ *+ * A config-wide drift affects every intended file identically; printing it 514+ * times buries the one thing a reader needs. Pure.+ */+export function groupByDifferences(perFile) {+ const groups = new Map();+ for (const { file, differences } of perFile) {+ if (differences.length === 0) continue;+ const key = JSON.stringify(differences);+ const group = groups.get(key) ?? { differences, files: [] };+ group.files.push(file);+ groups.set(key, group);+ }+ return [...groups.values()]+ .map((group) => ({ differences: group.differences, files: group.files.slice().sort() }))+ .sort((a, b) => (a.files[0] < b.files[0] ? -1 : 1));+}++/**+ * Compare the measured lint domain with what ESLint actually opened.+ *+ * Both directions matter. ``missing`` is a file the invariant claims and the run+ * never saw — the scope narrowing this whole module exists to catch. ``unwalked``+ * is the reverse: ESLint opened a TypeScript file the walk did not produce, which+ * means the walk itself is blind and every other check here is measuring less+ * than it claims. ``empty`` is the vacuous case — no intended files at all — which+ * would otherwise make the invariant pass by measuring nothing. Pure.+ */+export function coverageGaps({ intended, lintedFiles }) {+ const walked = new Set(intended);+ const linted = new Set(lintedFiles);+ return {+ empty: intended.length === 0,+ missing: intended.filter((file) => !linted.has(file)),+ unwalked: [...linted]+ .filter((file) => INTENDED_EXTENSIONS.some((extension) => file.endsWith(extension)))+ .filter((file) => !walked.has(file))+ .sort(),+ };+}++/**+ * The shared config with every rule removed, for a parse-only pass.+ *+ * Keeps the real parser, the real ``files`` patterns and the real language+ * options — the only thing dropped is rule execution, because this pass exists to+ * read comments, not to report violations. Pure.+ */+export const withoutRules = (config) =>+ config.map((entry) => (entry && typeof entry === 'object' && 'rules' in entry ? { ...entry, rules: {} } : entry));++/**+ * Inline configuration comments that are not suppressions.+ *+ * ``eslint-disable`` and its family are accounted for: the gate freezes them in+ * the ledger's ``suppressions`` tally. Every other inline directive escapes both+ * tallies — an ``eslint rule-id: "off"`` comment produces no error to count and+ * no suppressed message either, so a file can switch a rule off with nothing+ * anywhere to show for it. ``global`` and ``exported`` are rejected on the same+ * ground: they change what rules see, per file, invisibly.+ *+ * The allow-list is node identity from ESLint's own directive parser rather than+ * a pattern match on comment text, so a directive spelling this file never+ * imagined is rejected by default instead of slipping through. Pure.+ */+export function inlineConfigViolations(sourceCode) {+ const suppressions = new Set(sourceCode.getDisableDirectives().directives.map((directive) => directive.node));+ return sourceCode+ .getInlineConfigNodes()+ .filter((node) => !suppressions.has(node))+ .map((node) => ({+ line: node.loc.start.line,+ column: node.loc.start.column + 1,+ text: `${node.value ?? ''}`.trim(),+ }));+}++/**+ * Run the parse-only pass over every intended file and collect what it rejects.+ *+ * A file the pass cannot produce a ``SourceCode`` for is reported rather than+ * skipped: unreadable is not the same as clean, and silently passing over it is+ * how the measurement would shrink again.+ */+export function forbiddenInlineConfig({ root, files, config, linter }) {+ const found = [];+ for (const file of files) {+ const code = fs.readFileSync(path.join(root, file), 'utf8');+ const messages = linter.verify(code, config, { filename: file, allowInlineConfig: false });+ const sourceCode = linter.getSourceCode();+ if (!sourceCode) {+ found.push({ file, line: 0, column: 0, text: messages[0]?.message ?? 'could not be parsed for inline directives' });+ continue;+ }+ for (const violation of inlineConfigViolations(sourceCode)) found.push({ file, ...violation });+ }+ return found;+}diff --git a/ui/scripts/lintPolicy.test.mjs b/ui/scripts/lintPolicy.test.mjsnew file mode 100644index 000000000..eaf84d9d1--- /dev/null+++ b/ui/scripts/lintPolicy.test.mjs@@ -0,0 +1,478 @@+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { fileURLToPath } from 'node:url';++import { afterAll, beforeAll, describe, expect, it } from 'vitest';+import { ESLint, Linter } from 'eslint';+import globals from 'globals';++import sharedConfig from '../eslint.config.js';+import { EXPECTED_BROWSER_GLOBALS } from './browserGlobals.mjs';+import {+ DEPENDENCY_ROOTS,+ EXPECTED_POLICY,+ coverageGaps,+ effectivePolicyOf,+ forbiddenInlineConfig,+ groupByDifferences,+ inlineConfigViolations,+ intendedFiles,+ policyDifferences,+ withoutRules,+} from './lintPolicy.mjs';++// What the gate measures, measured. Every case here is a way the lint run could+// look at less than it claims to while `eslint-baseline.json` stays green — the+// failure mode the ledger structurally cannot see, because it records what was+// found and never what was looked at.++const UI_ROOT = fileURLToPath(new URL('../', import.meta.url));+const SCRIPTS_ROOT = fileURLToPath(new URL('./', import.meta.url));++let eslint;+beforeAll(() => {+ eslint = new ESLint();+});++// ─── the domain ──────────────────────────────────────────────────────────────++describe('intendedFiles walks the whole repo-owned TypeScript tree', () => {+ let tree;++ beforeAll(() => {+ tree = fs.mkdtempSync(path.join(os.tmpdir(), 'lint-domain-'));+ const write = (relative, body = 'export const x = 1;\n') => {+ fs.mkdirSync(path.join(tree, path.dirname(relative)), { recursive: true });+ fs.writeFileSync(path.join(tree, relative), body);+ };+ write('root.ts');+ write('Root.tsx');+ write('deeply/nested/under/many/levels/module.ts');+ write('src/component/Widget.tsx');+ write('notes.md', '# not code\n');+ write('script.js');+ write('node_modules/some-package/index.ts');+ write('dist/assets/bundle.ts');+ write('src/keep/real.ts');+ fs.symlinkSync(path.join(tree, 'src/keep'), path.join(tree, 'src/linkedDir'), 'dir');+ fs.symlinkSync(path.join(tree, 'root.ts'), path.join(tree, 'linked.ts'));+ });++ afterAll(() => {+ fs.rmSync(tree, { recursive: true, force: true });+ });++ it('finds every .ts and .tsx file at any depth, including the repo root', () => {+ expect(intendedFiles(tree)).toEqual([+ 'Root.tsx',+ 'deeply/nested/under/many/levels/module.ts',+ 'linked.ts',+ 'root.ts',+ 'src/component/Widget.tsx',+ 'src/keep/real.ts',+ ]);+ });++ it('treats symlinks the way ESLint does, so the two lists can be compared', async () => {+ // Disagreement here would show up as a permanent coverage failure with+ // nothing to fix, so the walk is pinned against the real enumerator: a+ // symlinked file is linted, a symlinked directory is not descended into.+ const linted = await new ESLint({ cwd: tree, overrideConfigFile: true, overrideConfig: sharedConfig }).lintFiles([+ '.',+ ]);+ const relative = linted.map((result) => path.relative(tree, result.filePath).split(path.sep).join('/'));+ expect(relative.filter((file) => file.endsWith('.ts') || file.endsWith('.tsx')).sort()).toEqual(intendedFiles(tree));+ });++ it('excludes exactly the two roots the declared policy already places outside the domain', () => {+ expect(DEPENDENCY_ROOTS).toEqual(['node_modules', 'dist']);+ expect(intendedFiles(tree).some((file) => file.startsWith('node_modules/') || file.startsWith('dist/'))).toBe(false);+ // Nothing else may be dropped: an extra exclusion is a hole in the invariant,+ // so the parameter exists only to make that visible in a test.+ expect(intendedFiles(tree, { excluded: [] })).toContain('node_modules/some-package/index.ts');+ });++ it('cannot be hung by a symlink cycle, because it never descends one', () => {+ fs.symlinkSync(tree, path.join(tree, 'src/loop'), 'dir');+ try {+ expect(intendedFiles(tree)).toContain('src/keep/real.ts');+ } finally {+ fs.rmSync(path.join(tree, 'src/loop'), { force: true });+ }+ });+});++describe('the real UI tree is what the gate measures', () => {+ it('covers the root config file the previous scope contract could not see', () => {+ // `basePath` narrowed the rule-bearing entry to `src/` with every field the+ // old hand-written contract listed left byte-identical, and `vite.config.ts`+ // silently stopped being linted. It is in the domain by construction now.+ expect(intendedFiles(UI_ROOT)).toContain('vite.config.ts');+ });++ it('covers nested sources without anyone listing them', () => {+ const found = intendedFiles(UI_ROOT);+ expect(found.length).toBeGreaterThan(100);+ expect(found.every((file) => file.endsWith('.ts') || file.endsWith('.tsx'))).toBe(true);+ expect(found.some((file) => file.split('/').length > 3)).toBe(true);+ });++ it('resolves exactly the pinned policy for every one of them', async () => {+ const drifted = [];+ for (const file of intendedFiles(UI_ROOT)) {+ const differences = policyDifferences(effectivePolicyOf(await eslint.calculateConfigForFile(path.join(UI_ROOT, file))));+ if (differences.length > 0) drifted.push({ file, differences });+ }+ expect(groupByDifferences(drifted)).toEqual([]);+ });+});++// ─── the policy ──────────────────────────────────────────────────────────────++const resolved = async (filePath = 'src/__probe__/probe.ts') =>+ effectivePolicyOf(await eslint.calculateConfigForFile(filePath));++describe('policyDifferences pins the whole effective policy, not a projection of it', () => {+ let actual;+ beforeAll(async () => {+ actual = await resolved();+ });++ it('accepts the policy the shared config actually resolves', () => {+ expect(policyDifferences(actual)).toEqual([]);+ });++ it('rejects a path no configuration matches at all', () => {+ expect(policyDifferences(null)).toEqual([+ 'no ESLint configuration matches this file, so nothing about it is linted',+ ]);+ });++ it('rejects a rule that stopped resolving', () => {+ const { 'react-hooks/globals': _dropped, ...rules } = actual.rules;+ expect(policyDifferences({ ...actual, rules })).toEqual([+ '1 pinned rule(s) no longer resolve: react-hooks/globals',+ ]);+ });++ it('rejects a rule demoted to a warning', () => {+ const rules = { ...actual.rules, '@typescript-eslint/no-explicit-any': [1] };+ expect(policyDifferences({ ...actual, rules })).toEqual([+ 'rule config changed — @typescript-eslint/no-explicit-any: expected [2], resolved [1]',+ ]);+ });++ // Severity alone was the projection this replaces. A preset can keep a rule at+ // error and loosen its options, enforcing less with the severity map unchanged.+ it('rejects options loosened while the severity stays at error', () => {+ const rules = {+ ...actual.rules,+ '@typescript-eslint/no-unused-vars': [2, { argsIgnorePattern: '.*', varsIgnorePattern: '.*' }],+ };+ const lines = policyDifferences({ ...actual, rules });+ expect(lines).toHaveLength(1);+ expect(lines[0]).toContain('rule config changed — @typescript-eslint/no-unused-vars');+ });++ it('rejects a rule nobody pinned appearing from an upgrade', () => {+ const rules = { ...actual.rules, 'brand-new/rule': [2] };+ expect(policyDifferences({ ...actual, rules })).toEqual(['1 unpinned rule(s) resolve: brand-new/rule']);+ });++ it('names each drifting boundary that can stop rules running', () => {+ const cases = {+ parser: 'espree',+ ecmaVersion: 5,+ sourceType: 'script',+ processor: 'some-plugin/markdown',+ parserOptions: { project: './tsconfig.json' },+ plugins: ['@'],+ linterOptions: { reportUnusedDisableDirectives: 0 },+ };+ for (const [key, value] of Object.entries(cases)) {+ const lines = policyDifferences({ ...actual, [key]: value });+ expect(lines, key).toHaveLength(1);+ expect(lines[0], key).toContain(`${key}: expected`);+ }+ });++ it('holds the browser globals to the contract the config declares', () => {+ expect(policyDifferences({ ...actual, globals: {} })).toEqual([+ expect.stringContaining(`${Object.keys(EXPECTED_BROWSER_GLOBALS).length} expected global(s) absent`),+ ]);+ expect(policyDifferences({ ...actual, globals: { ...actual.globals, __injected__: 'readonly' } })).toEqual([+ '1 unexpected global(s): __injected__',+ ]);+ expect(policyDifferences({ ...actual, globals: { ...actual.globals, window: 'writable' } })).toEqual([+ '1 global(s) changed writability: window',+ ]);+ });++ it('reports a one-name catalog change as the only difference there is', () => {+ // What a `globals` upgrade actually looks like in the resolved config: one+ // name appears, one disappears, or one stops being readonly. Each has to+ // surface on its own, with the rest of the policy reading as unchanged —+ // otherwise the failure is unattributable and gets waved through.+ const { structuredClone: _dropped, ...withoutOne } = actual.globals;+ const cases = [+ ['upstream addition', { ...actual.globals, upstreamAddition: false }, '1 unexpected global(s): upstreamAddition'],+ ['upstream removal', withoutOne, '1 expected global(s) absent: structuredClone'],+ ['loosened to writable', { ...actual.globals, structuredClone: true }, '1 global(s) changed writability: structuredClone'],+ ];+ for (const [label, catalog, expected] of cases) {+ expect(policyDifferences({ ...actual, globals: catalog }), label).toEqual([expected]);+ }+ });++ it('pins the resolved parser rather than whatever the config happens to name', () => {+ expect(EXPECTED_POLICY.parser).toBe('typescript-eslint/parser');+ expect(actual.parser).toBe(EXPECTED_POLICY.parser);+ });+});++describe('the expected browser globals are a committed value, not a read of the dependency', () => {+ // The last hole in the policy contract, and a different shape from the earlier+ // ones: the subject was complete — all 1169 names and writability values were+ // compared — but the *reference* was `globals.browser` itself, the same export+ // `eslint.config.js` resolves from. On that one axis the comparison was+ // `X === X`, so an upstream catalog change moved both sides together and passed,+ // and the only trace was a version bump in the lockfile.++ const importsOf = (filename) => {+ const linter = new Linter();+ const code = fs.readFileSync(path.join(SCRIPTS_ROOT, filename), 'utf8');+ linter.verify(code, { languageOptions: { ecmaVersion: 'latest', sourceType: 'module' } }, { filename });+ const sourceCode = linter.getSourceCode();+ if (sourceCode === null) throw new Error(`${filename} did not parse`);+ return sourceCode.ast.body.filter((node) => node.type === 'ImportDeclaration').map((node) => node.source.value);+ };++ it('does not move when the installed catalog moves under it', () => {+ const snapshot = { ...EXPECTED_POLICY.globals };+ const original = { structuredClone: globals.browser.structuredClone, window: globals.browser.window };+ try {+ globals.browser.upstreamAddition = false;+ delete globals.browser.structuredClone;+ globals.browser.window = true;++ expect(EXPECTED_POLICY.globals).toEqual(snapshot);+ expect(EXPECTED_POLICY.globals).not.toHaveProperty('upstreamAddition');+ expect(EXPECTED_POLICY.globals.structuredClone).toBe(false);+ expect(EXPECTED_POLICY.globals.window).toBe(false);+ } finally {+ delete globals.browser.upstreamAddition;+ Object.assign(globals.browser, original);+ }+ });++ it('is not the installed catalog, by identity either', () => {+ expect(EXPECTED_BROWSER_GLOBALS).not.toBe(globals.browser);+ expect(EXPECTED_POLICY.globals).toBe(EXPECTED_BROWSER_GLOBALS);+ });++ it('is reached without the policy modules importing the dependency at all', () => {+ // A copy taken at load time would pass the mutation case above and still move+ // on every upgrade, so independence is also asserted where it is decided: the+ // module graph. Nothing in the expected side may reach `globals`.+ expect(importsOf('browserGlobals.mjs')).toEqual([]);+ expect(importsOf('lintPolicy.mjs')).not.toContain('globals');+ });++ it('is checked against the installed catalog in exactly one place, loudly', () => {+ // A snapshot has to be a snapshot *of* something. This is that statement, and+ // it is the whole reason the snapshot may be trusted as a reference: when the+ // dependency changes, this fails by name here instead of passing silently+ // everywhere.+ expect(EXPECTED_BROWSER_GLOBALS).toEqual(globals.browser);+ });+});++describe('a scope narrowing takes files out of the policy, and that is what fails', () => {+ const narrow = (mutate) =>+ new ESLint({+ overrideConfigFile: true,+ overrideConfig: sharedConfig.map((entry) =>+ entry && typeof entry === 'object' && 'files' in entry ? mutate(entry) : entry,+ ),+ });++ it('catches a basePath that quietly drops the repo root', async () => {+ // The exact defect: every `{name, files, ignores}` field stays byte-identical.+ const narrowed = narrow((entry) => ({ ...entry, basePath: 'src' }));+ expect(policyDifferences(effectivePolicyOf(await narrowed.calculateConfigForFile('src/App.tsx')))).toEqual([]);+ expect(policyDifferences(effectivePolicyOf(await narrowed.calculateConfigForFile('vite.config.ts')))).not.toEqual([]);+ });++ it('catches an ignores that exempts one nested subtree', async () => {+ const narrowed = narrow((entry) => ({ ...entry, ignores: ['src/lib/**'] }));+ expect(policyDifferences(effectivePolicyOf(await narrowed.calculateConfigForFile('src/App.tsx')))).toEqual([]);+ expect(+ policyDifferences(effectivePolicyOf(await narrowed.calculateConfigForFile('src/lib/useLatestRef.ts'))),+ ).not.toEqual([]);+ });+});++describe('groupByDifferences keeps a config-wide drift readable', () => {+ const drift = ['parser: expected "typescript-eslint/parser", resolved "espree"'];++ it('folds an identical failure on many files into one entry', () => {+ const perFile = ['src/a.ts', 'src/b.ts', 'src/c.ts'].map((file) => ({ file, differences: drift }));+ expect(groupByDifferences(perFile)).toEqual([{ differences: drift, files: ['src/a.ts', 'src/b.ts', 'src/c.ts'] }]);+ });++ it('keeps genuinely different failures apart', () => {+ const other = ['1 pinned rule(s) no longer resolve: no-var'];+ expect(+ groupByDifferences([+ { file: 'src/b.ts', differences: other },+ { file: 'src/a.ts', differences: drift },+ ]),+ ).toEqual([+ { differences: drift, files: ['src/a.ts'] },+ { differences: other, files: ['src/b.ts'] },+ ]);+ });++ it('drops files that resolved the policy exactly', () => {+ expect(groupByDifferences([{ file: 'src/a.ts', differences: [] }])).toEqual([]);+ });+});++// ─── the coverage ────────────────────────────────────────────────────────────++describe('coverageGaps compares the domain with what ESLint opened, both ways', () => {+ it('accepts a run that opened everything in the domain', () => {+ expect(coverageGaps({ intended: ['src/a.ts'], lintedFiles: ['src/a.ts', 'eslint.config.js'] })).toEqual({+ empty: false,+ missing: [],+ unwalked: [],+ });+ });++ it('names a nested intended file the run never opened', () => {+ expect(+ coverageGaps({ intended: ['src/a.ts', 'src/deep/nested/b.tsx'], lintedFiles: ['src/a.ts'] }).missing,+ ).toEqual(['src/deep/nested/b.tsx']);+ });++ it('names a linted TypeScript file the walk missed, so the walk cannot go blind', () => {+ expect(coverageGaps({ intended: ['src/a.ts'], lintedFiles: ['src/a.ts', 'src/hidden.tsx'] }).unwalked).toEqual([+ 'src/hidden.tsx',+ ]);+ });++ it('refuses to pass vacuously when the walk produced nothing', () => {+ expect(coverageGaps({ intended: [], lintedFiles: [] }).empty).toBe(true);+ });+});++// ─── the inline escape hatch ─────────────────────────────────────────────────++const parseOnly = withoutRules(sharedConfig);++function violationsIn(code, filename = 'src/__probe__/probe.ts') {+ const linter = new Linter();+ linter.verify(code, parseOnly, { filename, allowInlineConfig: false });+ return inlineConfigViolations(linter.getSourceCode());+}++describe('inline configuration outside the eslint-disable family is rejected', () => {+ // Neither tally can see these: an inline severity override produces no error to+ // count and no suppressed message either, so the rule simply stops applying to+ // that file with nothing recorded anywhere.+ it('rejects an inline rule switched off', () => {+ const found = violationsIn('/* eslint @typescript-eslint/no-explicit-any: "off" */\nexport const f = (v: any) => v;\n');+ expect(found).toHaveLength(1);+ expect(found[0]).toMatchObject({ line: 1, column: 1 });+ expect(found[0].text).toContain('no-explicit-any');+ });++ it('rejects an inline rule demoted to a warning', () => {+ expect(violationsIn('/* eslint @typescript-eslint/no-explicit-any: "warn" */\nexport const f = (v: any) => v;\n')).toHaveLength(1);+ });++ it('rejects the declaration directives on the same ground', () => {+ expect(violationsIn('/* global someInjectedThing */\nexport const f = 1;\n')).toHaveLength(1);+ expect(violationsIn('/* globals a, b */\nexport const f = 1;\n')).toHaveLength(1);+ expect(violationsIn('/* exported f */\nexport const f = 1;\n')).toHaveLength(1);+ });++ it('allows every spelling of a suppression, which the ledger does freeze', () => {+ expect(violationsIn('/* eslint-disable @typescript-eslint/no-explicit-any */\nexport const f = (v: any) => v;\n')).toEqual([]);+ expect(violationsIn('// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const f = (v: any) => v;\n')).toEqual([]);+ expect(violationsIn('export const f = (v: any) => v; // eslint-disable-line @typescript-eslint/no-explicit-any\n')).toEqual([]);+ expect(+ violationsIn('/* eslint-disable no-var */\nvar a = 1;\n/* eslint-enable no-var */\nexport const f = a;\n'),+ ).toEqual([]);+ });++ it('leaves an ordinary comment alone', () => {+ expect(violationsIn('// this mentions eslint but configures nothing\nexport const f = 1;\n')).toEqual([]);+ });++ it('still lets an allowed suppression reach the ledger, which is what freezes it', async () => {+ const [result] = await eslint.lintText(+ '// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const f = (v: any) => v;\n',+ { filePath: 'src/__probe__/probe.ts' },+ );+ expect(result.suppressedMessages.map((message) => message.ruleId)).toEqual(['@typescript-eslint/no-explicit-any']);+ expect(result.messages).toEqual([]);+ });+});++describe('forbiddenInlineConfig sweeps the whole domain', () => {+ let tree;++ beforeAll(() => {+ tree = fs.mkdtempSync(path.join(os.tmpdir(), 'lint-inline-'));+ fs.writeFileSync(path.join(tree, 'clean.ts'), 'export const a = 1;\n');+ fs.writeFileSync(path.join(tree, 'suppressed.ts'), '/* eslint-disable no-var */\nexport const b = 1;\n');+ fs.writeFileSync(path.join(tree, 'override.ts'), '/* eslint no-var: "off" */\nexport const c = 1;\n');+ });++ afterAll(() => {+ fs.rmSync(tree, { recursive: true, force: true });+ });++ it('reports only the file that rewrote policy inline', () => {+ const found = forbiddenInlineConfig({+ root: tree,+ files: ['clean.ts', 'override.ts', 'suppressed.ts'],+ config: parseOnly,+ linter: new Linter(),+ });+ expect(found.map(({ file }) => file)).toEqual(['override.ts']);+ });++ it('reports a file it could not parse rather than passing over it', () => {+ fs.writeFileSync(path.join(tree, 'broken.ts'), 'export const = ;\n');+ const found = forbiddenInlineConfig({+ root: tree,+ files: ['broken.ts'],+ config: parseOnly,+ linter: new Linter(),+ });+ expect(found).toHaveLength(1);+ expect(found[0].file).toBe('broken.ts');+ });+});++describe('withoutRules keeps the real config and drops only rule execution', () => {+ it('empties every rule map while leaving scope and language intact', () => {+ const stripped = withoutRules(sharedConfig);+ expect(stripped).toHaveLength(sharedConfig.length);+ for (const [index, entry] of stripped.entries()) {+ if ('rules' in entry) expect(entry.rules).toEqual({});+ expect(entry.files).toEqual(sharedConfig[index].files);+ expect(entry.ignores).toEqual(sharedConfig[index].ignores);+ expect(entry.languageOptions).toEqual(sharedConfig[index].languageOptions);+ }+ });++ it('does not mutate the shared config it was handed', () => {+ const before = JSON.stringify(sharedConfig.map((entry) => Object.keys(entry.rules ?? {}).length));+ withoutRules(sharedConfig);+ expect(JSON.stringify(sharedConfig.map((entry) => Object.keys(entry.rules ?? {}).length))).toBe(before);+ });+});diff --git a/ui/src/App.tsx b/ui/src/App.tsxindex 77cc00bae..abcbbaf14 100644--- a/ui/src/App.tsx+++ b/ui/src/App.tsx@@ -34,15 +34,15 @@ import { SettingsLogsPage } from './components/settings/SettingsLogsPage';import { SettingsMessagingPage } from './components/settings/SettingsMessagingPage';import { SettingsPlatformsPage } from './components/settings/SettingsPlatformsPage';import { SettingsServicePage } from './components/settings/SettingsServicePage';-import { StatusProvider } from './context/StatusContext';+import { StatusProvider } from './context/StatusProvider';import { ApiProvider, useApi, ApiError } from './context/ApiContext';import { useWindowManager } from './context/WindowManagerContext';-import { ToastProvider } from './context/ToastContext';-import { ThemeProvider } from './context/ThemeContext';+import { ToastProvider } from './context/ToastProvider';+import { ThemeProvider } from './context/ThemeProvider';import { VaultSandboxAppearanceBridge } from './components/VaultSandboxAppearanceBridge';-import { WorkbenchInboxProvider } from './context/WorkbenchInboxContext';-import { WorkbenchProjectsProvider } from './context/WorkbenchProjectsContext';-import { ComposerBridgeProvider } from './context/ComposerBridgeContext';+import { WorkbenchInboxProvider } from './context/WorkbenchInboxProvider';+import { WorkbenchProjectsProvider } from './context/WorkbenchProjectsProvider';+import { ComposerBridgeProvider } from './context/ComposerBridgeProvider';import { UnsavedChangesProvider } from './context/UnsavedChangesProvider';import { AgentationToggle } from './components/AgentationToggle';import { PwaLoopbackLinkGuard } from './components/PwaLoopbackLinkGuard';@@ -347,6 +347,12 @@ const AuthGuard = ({ children }: { children: ReactNode }) => {// bridge, the stale setup-required state immediately redirects back to// /setup, so the first finish appears to "not take" even though the// config was already saved with setup_completed=true.+ //+ // Reading a ref during render is normally wrong because the component+ // will not re-render when it changes. Here that is the intent: this+ // branch only bridges the single frame before the re-validation effect+ // (which owns the re-render) flips `guardStatus` to loading.+ // eslint-disable-next-line react-hooks/refs -- Deliberate one-frame bridge; see above.if (previousIsSetupRouteRef.current) {return <div className="min-h-screen flex items-center justify-center bg-bg text-text">{t('common.loading')}</div>;}diff --git a/ui/src/apps/AppBodyLoading.tsx b/ui/src/apps/AppBodyLoading.tsxnew file mode 100644index 000000000..afdf3dfbd--- /dev/null+++ b/ui/src/apps/AppBodyLoading.tsx@@ -0,0 +1,10 @@+import { useTranslation } from 'react-i18next';++// The Suspense fallback for a lazily-loaded app body. Its own module because+// `registry.tsx` is a data module — a component defined next to the registry+// object can never be hot-replaced, so every app body would need a full reload+// to pick up a change here.+export const AppBodyLoading: React.FC = () => {+ const { t } = useTranslation();+ return <div className="grid h-full w-full place-items-center bg-surface text-[12px] text-muted">{t('common.loading')}</div>;+};diff --git a/ui/src/apps/appLibrary.ts b/ui/src/apps/appLibrary.tsindex 9cc7178ac..77b2372d4 100644--- a/ui/src/apps/appLibrary.ts+++ b/ui/src/apps/appLibrary.ts@@ -3,7 +3,7 @@// layer (LibraryApp / ShowPagesView) resolves each row's icon, title, and badge// from the registry + loaded Show Pages.-import { showDockId } from '../context/DockContext';+import { showDockId } from '../context/dockDoc';export type AppRowKind = 'builtin' | 'showpage';diff --git a/ui/src/apps/registry.tsx b/ui/src/apps/registry.tsxindex 8cfdf369c..674e1cb15 100644--- a/ui/src/apps/registry.tsx+++ b/ui/src/apps/registry.tsx@@ -1,8 +1,8 @@import { Suspense, lazy } from 'react';import { CodeXml, Eye, Folder, LayoutGrid, MonitorPlay, SquareTerminal } from 'lucide-react';-import { useTranslation } from 'react-i18next';import type { LucideIcon } from 'lucide-react';+import { AppBodyLoading } from './AppBodyLoading';import { sessionChatPath, showPagePrivatePath } from './showPageAvatar';// The catalogue of windowed apps. The WindowManager + Dock are headless of any@@ -45,11 +45,6 @@ export interface AppDefinition {chatHref?: (params?: Record<string, unknown>) => string | undefined;}-const Loading: React.FC = () => {- const { t } = useTranslation();- return <div className="grid h-full w-full place-items-center bg-surface text-[12px] text-muted">{t('common.loading')}</div>;-};-const FilesBody = lazy(() =>import('../components/workbench/AppsFileBrowserPage').then((m) => ({ default: m.AppsFileBrowserPage })),);@@ -73,7 +68,7 @@ export const APP_REGISTRY: Record<AppId, AppDefinition> = {accent: '--cyan',defaultSize: { width: 920, height: 600 },Component: ({ windowId }) => (- <Suspense fallback={<Loading />}>+ <Suspense fallback={<AppBodyLoading />}><FilesBody windowed windowId={windowId} /></Suspense>),@@ -86,7 +81,7 @@ export const APP_REGISTRY: Record<AppId, AppDefinition> = {defaultSize: { width: 820, height: 540 },lockTheme: 'dark',Component: ({ windowId, params }) => (- <Suspense fallback={<Loading />}>+ <Suspense fallback={<AppBodyLoading />}>{/* Each windowed terminal takes a bounded, reused session slot internally soit gets its own backend session without leaking ids (see AppsTerminalPage).windowId + params thread through so the tab layout persists across reloads. */}@@ -102,7 +97,7 @@ export const APP_REGISTRY: Record<AppId, AppDefinition> = {defaultSize: { width: 1000, height: 640 },lockTheme: 'dark',Component: ({ windowId, params }) => (- <Suspense fallback={<Loading />}>+ <Suspense fallback={<AppBodyLoading />}><EditorBody windowId={windowId} params={params} /></Suspense>),@@ -118,7 +113,7 @@ export const APP_REGISTRY: Record<AppId, AppDefinition> = {accent: '--gold',defaultSize: { width: 900, height: 640 },Component: ({ windowId, params }) => (- <Suspense fallback={<Loading />}>+ <Suspense fallback={<AppBodyLoading />}><PreviewBody windowId={windowId} params={params} /></Suspense>),@@ -134,7 +129,7 @@ export const APP_REGISTRY: Record<AppId, AppDefinition> = {accent: '--mint',defaultSize: { width: 1040, height: 720 },Component: ({ windowId, params }) => (- <Suspense fallback={<Loading />}>+ <Suspense fallback={<AppBodyLoading />}><ShowPageBody windowId={windowId} params={params} /></Suspense>),@@ -159,7 +154,7 @@ export const APP_REGISTRY: Record<AppId, AppDefinition> = {accent: '--gold',defaultSize: { width: 940, height: 640 },Component: ({ windowId, params }) => (- <Suspense fallback={<Loading />}>+ <Suspense fallback={<AppBodyLoading />}><LibraryBody windowId={windowId} params={params} /></Suspense>),diff --git a/ui/src/components/AppShell.tsx b/ui/src/components/AppShell.tsxindex ce4334fae..47f795a2c 100644--- a/ui/src/components/AppShell.tsx+++ b/ui/src/components/AppShell.tsx@@ -15,8 +15,8 @@ import { VersionBadge } from './VersionBadge';import { WorkbenchSidebar } from './workbench/WorkbenchSidebar';import { AppsLauncher } from './AppsLauncher';import { ErrorBoundary } from './ui/error-boundary';-import { WindowManagerProvider } from '../context/WindowManagerContext';-import { DockProvider } from '../context/DockContext';+import { WindowManagerProvider } from '../context/WindowManagerProvider';+import { DockProvider } from '../context/DockProvider';import { ShowPageDragProvider } from '../context/ShowPageDragProvider';import { WindowLayer } from './apps/WindowLayer';import { MobileDockDrawer } from './apps/MobileDockDrawer';diff --git a/ui/src/components/VersionBadge.tsx b/ui/src/components/VersionBadge.tsxindex b7b600df8..0a79229b8 100644--- a/ui/src/components/VersionBadge.tsx+++ b/ui/src/components/VersionBadge.tsx@@ -5,7 +5,7 @@ import { Download, X, RefreshCw, Check, AlertCircle, GitCommitHorizontal } fromimport clsx from 'clsx';import { ToggleSwitch } from './settings/SettingsPrimitives';import { Button } from './ui/button';-import { badgeVariants } from './ui/badge';+import { badgeVariants } from './ui/badge-variants';import { cn } from '@/lib/utils';import { scheduleUpgradeReload } from '../lib/upgradeReload';diff --git a/ui/src/components/apps/AppWindow.tsx b/ui/src/components/apps/AppWindow.tsxindex e86ce3d94..a39957ccd 100644--- a/ui/src/components/apps/AppWindow.tsx+++ b/ui/src/components/apps/AppWindow.tsx@@ -10,7 +10,8 @@ import { ShowPageAvatarContent } from '../../apps/showPageAvatarTile';import { useWindowManager, type WindowInstance } from '../../context/WindowManagerContext';import { useUnsavedChangesActionGuard } from '../../context/useUnsavedChangesActionGuard';import { clampToLayer, resizeBounds, type ResizeDir } from '../../lib/windowBounds';-import { WindowBodyGestureShield, shouldShieldWindowBody } from './windowGesture';+import { WindowBodyGestureShield } from './WindowBodyGestureShield';+import { shouldShieldWindowBody } from './windowGesture';import { ErrorBoundary } from '../ui/error-boundary';import { ShowPageAnnotateControl } from '../workbench/ShowPageAnnotateControl';import { useShowPageAnnotationHost } from '../workbench/ShowPageAnnotationHostContext';diff --git a/ui/src/components/apps/Dock.tsx b/ui/src/components/apps/Dock.tsxindex 2355a90b1..f25506d2e 100644--- a/ui/src/components/apps/Dock.tsx+++ b/ui/src/components/apps/Dock.tsx@@ -7,7 +7,8 @@ import clsx from 'clsx';import { APP_REGISTRY, type AppDefinition, type AppId } from '../../apps/registry';import { showPageAvatar, showPageIconUrl, showPagePrivatePath } from '../../apps/showPageAvatar';import { ShowPageAvatarContent } from '../../apps/showPageAvatarTile';-import { dockIdToSession, useDock } from '../../context/DockContext';+import { useDock } from '../../context/DockContext';+import { dockIdToSession } from '../../context/dockDoc';import { useWindowManager } from '../../context/WindowManagerContext';import { ContextMenu, ContextMenuItem } from '../ui/context-menu';import { useShowPageInventory } from '../useShowPages';diff --git a/ui/src/components/apps/MobileDockDrawer.tsx b/ui/src/components/apps/MobileDockDrawer.tsxindex de0ab5f24..e4abe7e85 100644--- a/ui/src/components/apps/MobileDockDrawer.tsx+++ b/ui/src/components/apps/MobileDockDrawer.tsx@@ -6,7 +6,8 @@ import { LayoutGrid, Minus, MoreHorizontal, PinOff, Settings, UserRound, X } froimport { APP_REGISTRY, type AppDefinition, type AppId } from '../../apps/registry';import { showPageAvatar, showPageIconUrl } from '../../apps/showPageAvatar';import { ShowPageAvatarContent } from '../../apps/showPageAvatarTile';-import { dockIdToSession, useDock } from '../../context/DockContext';+import { useDock } from '../../context/DockContext';+import { dockIdToSession } from '../../context/dockDoc';import { useAuthAccount } from '../../lib/useAuthAccount';import { useShowPageInventory } from '../useShowPages';import { MoreAccountSection, MoreAppearanceSection, MoreConnectionSection } from '../workbench/MorePage';diff --git a/ui/src/components/apps/WindowBodyGestureShield.tsx b/ui/src/components/apps/WindowBodyGestureShield.tsxnew file mode 100644index 000000000..51bfa10fc--- /dev/null+++ b/ui/src/components/apps/WindowBodyGestureShield.tsx@@ -0,0 +1,7 @@+/** A transparent, non-iframe overlay filling the window body during a drag/resize.+ * Any pointer event over the body lands here (a plain div, no handlers) instead of+ * the iframe document, and the iframe's cursor can't show through. Sits below the+ * z-30 resize grips and the title bar, so those stay grabbable. Renders nothing when+ * inactive. See `windowGesture.ts` for why the shield exists at all. */+export const WindowBodyGestureShield: React.FC<{ active: boolean }> = ({ active }) =>+ active ? <div aria-hidden data-gesture-shield className="absolute inset-0 z-20" /> : null;diff --git a/ui/src/components/apps/WindowLayer.tsx b/ui/src/components/apps/WindowLayer.tsxindex a7dd96527..05bb87ec9 100644--- a/ui/src/components/apps/WindowLayer.tsx+++ b/ui/src/components/apps/WindowLayer.tsx@@ -3,7 +3,8 @@ import { useTranslation } from 'react-i18next';import { APP_REGISTRY, type AppId } from '../../apps/registry';import { dockIndexFromShortcut } from '../../apps/dockShortcuts';-import { dockIdToSession, useDock } from '../../context/DockContext';+import { useDock } from '../../context/DockContext';+import { dockIdToSession } from '../../context/dockDoc';import { useApi } from '../../context/ApiContext';import { useWindowManager, type WindowInstance } from '../../context/WindowManagerContext';import { useShowPageInventory } from '../useShowPages';diff --git a/ui/src/components/apps/mobileDock.test.ts b/ui/src/components/apps/mobileDock.test.tsindex 5586bd724..c2171b0f8 100644--- a/ui/src/components/apps/mobileDock.test.ts+++ b/ui/src/components/apps/mobileDock.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest';-import { showDockId } from '../../context/DockContext';+import { showDockId } from '../../context/dockDoc';import { mobileRouteForDockId, showAppRoutePath } from './mobileDock';describe('showAppRoutePath', () => {diff --git a/ui/src/components/apps/mobileDock.ts b/ui/src/components/apps/mobileDock.tsindex 82f8d6400..42c9785e0 100644--- a/ui/src/components/apps/mobileDock.ts+++ b/ui/src/components/apps/mobileDock.ts@@ -4,7 +4,7 @@// there is no window layer, so every Dock tile opens as a full-screen `/apps/*`// route instead of a workbench window (§7.1b).-import { dockIdToSession } from '../../context/DockContext';+import { dockIdToSession } from '../../context/dockDoc';/*** The in-shell route that frames a pinned Show Page full-screen on mobilediff --git a/ui/src/components/apps/windowGesture.test.tsx b/ui/src/components/apps/windowGesture.test.tsxindex bf2ab6612..8ffb9b7f9 100644--- a/ui/src/components/apps/windowGesture.test.tsx+++ b/ui/src/components/apps/windowGesture.test.tsx@@ -1,7 +1,8 @@import { renderToStaticMarkup } from 'react-dom/server';import { describe, expect, it } from 'vitest';-import { WindowBodyGestureShield, shouldShieldWindowBody } from './windowGesture';+import { WindowBodyGestureShield } from './WindowBodyGestureShield';+import { shouldShieldWindowBody } from './windowGesture';describe('shouldShieldWindowBody (§7.1i arm/disarm predicate)', () => {it('shields only a visible window while a gesture is active', () => {diff --git a/ui/src/components/apps/windowGesture.ts b/ui/src/components/apps/windowGesture.tsnew file mode 100644index 000000000..dd4da5642--- /dev/null+++ b/ui/src/components/apps/windowGesture.ts@@ -0,0 +1,13 @@+// Window drag/resize gesture helpers (§7.1i). An in-window iframe (a showpage+// window body) steals pointer events once a title-bar/resize gesture drags over it —+// the parent's move handlers stop firing and the drag freezes. The primary fix is+// pointer capture on the gesture element (AppWindow.startGesture); the belt-and-braces+// shield is a transparent overlay over each window body while ANY window is mid-gesture,+// so a stray pointer event can't reach an iframe and the cursor can't flicker over it.+// This module owns when to arm it; `WindowBodyGestureShield.tsx` renders it.++/** Whether a window should shield its body while a gesture is active. Only visible+ * windows have a body to shield — a minimized window is hidden, so skip it. Pure. */+export function shouldShieldWindowBody(gestureActive: boolean, minimized: boolean): boolean {+ return gestureActive && !minimized;+}diff --git a/ui/src/components/apps/windowGesture.tsx b/ui/src/components/apps/windowGesture.tsxdeleted file mode 100644index 7631d73b2..000000000--- a/ui/src/components/apps/windowGesture.tsx+++ /dev/null@@ -1,21 +0,0 @@-// Window drag/resize gesture helpers (§7.1i). An in-window iframe (a showpage-// window body) steals pointer events once a title-bar/resize gesture drags over it —-// the parent's move handlers stop firing and the drag freezes. The primary fix is-// pointer capture on the gesture element (AppWindow.startGesture); this module is the-// belt-and-braces shield: a transparent overlay over each window body while ANY-// window is mid-gesture, so a stray pointer event can't reach an iframe and the-// cursor can't flicker over it.--/** Whether a window should shield its body while a gesture is active. Only visible- * windows have a body to shield — a minimized window is hidden, so skip it. Pure. */-export function shouldShieldWindowBody(gestureActive: boolean, minimized: boolean): boolean {- return gestureActive && !minimized;-}--/** A transparent, non-iframe overlay filling the window body during a drag/resize.- * Any pointer event over the body lands here (a plain div, no handlers) instead of- * the iframe document, and the iframe's cursor can't show through. Sits below the- * z-30 resize grips and the title bar, so those stay grabbable. Renders nothing when- * inactive. */-export const WindowBodyGestureShield: React.FC<{ active: boolean }> = ({ active }) =>- active ? <div aria-hidden data-gesture-shield className="absolute inset-0 z-20" /> : null;diff --git a/ui/src/components/settings/BackendLifecycleChip.tsx b/ui/src/components/settings/BackendLifecycleChip.tsxindex 1b287983e..52f4fb5ce 100644--- a/ui/src/components/settings/BackendLifecycleChip.tsx+++ b/ui/src/components/settings/BackendLifecycleChip.tsx@@ -5,7 +5,7 @@ import clsx from 'clsx';import { useApi, type BackendRuntimeInfo } from '../../context/ApiContext';import { useToast } from '../../context/ToastContext';import { Button } from '../ui/button';-import { badgeVariants } from '../ui/badge';+import { badgeVariants } from '../ui/badge-variants';import { cn } from '@/lib/utils';type CliStatus = 'unknown' | 'ok' | 'missing';diff --git a/ui/src/components/settings/BackendOAuthPanel.tsx b/ui/src/components/settings/BackendOAuthPanel.tsxindex 63822e0d5..e8ed76a3d 100644--- a/ui/src/components/settings/BackendOAuthPanel.tsx+++ b/ui/src/components/settings/BackendOAuthPanel.tsx@@ -8,6 +8,7 @@ import { OAuthDeviceCodeRow, OAuthLinkRow, OAuthSubmitRow } from './oauth/OAuthFimport { useApi } from '@/context/ApiContext';import type { OAuthWebState } from '@/context/ApiContext';import { useToast } from '@/context/ToastContext';+import { errorMessage } from '@/lib/errorMessage';type Backend = 'claude' | 'codex' | 'opencode';@@ -177,8 +178,8 @@ export const BackendOAuthPanel: React.FC<BackendOAuthPanelProps> = ({return;}scheduleNextPoll(currentFlowId);- } catch (err: any) {- setError(err?.message || 'poll_failed');+ } catch (err) {+ setError(errorMessage(err) || 'poll_failed');setState('failed');stopPolling();}@@ -204,8 +205,8 @@ export const BackendOAuthPanel: React.FC<BackendOAuthPanelProps> = ({setState(result.state || 'starting');pollDeadlineRef.current = Date.now() + POLL_DEADLINE_MS;scheduleNextPoll(result.flow_id);- } catch (err: any) {- setError(err?.message || 'start_failed');+ } catch (err) {+ setError(errorMessage(err) || 'start_failed');setState('failed');} finally {setStarting(false);@@ -220,7 +221,7 @@ export const BackendOAuthPanel: React.FC<BackendOAuthPanelProps> = ({stopPolling();try {await api.cancelOAuthWeb(backend, flowId);- } catch (err) {+ } catch {// Swallow — even if the cancel rountrip failed, the UI should still// return to the idle state so the user can retry without a stuck// panel. The server-side flow times out on its own at 900s.@@ -248,8 +249,8 @@ export const BackendOAuthPanel: React.FC<BackendOAuthPanelProps> = ({// so the UI hides the code input immediately rather than waiting for// the next poll tick.setState('verifying');- } catch (err: any) {- setError(err?.message || 'submit_failed');+ } catch (err) {+ setError(errorMessage(err) || 'submit_failed');} finally {setSubmitting(false);}@@ -295,9 +296,9 @@ export const BackendOAuthPanel: React.FC<BackendOAuthPanelProps> = ({showToast(t('settings.backends.oauthRemoved'), 'success');}onSuccessRef.current?.();- } catch (err: any) {+ } catch (err) {showToast(- t('settings.backends.oauthRemoveFailed', { detail: err?.message || 'unknown' }),+ t('settings.backends.oauthRemoveFailed', { detail: errorMessage(err) || 'unknown' }),'error',);} finally {diff --git a/ui/src/components/settings/BackendTestPanel.tsx b/ui/src/components/settings/BackendTestPanel.tsxindex 2a5448a45..513aae8a5 100644--- a/ui/src/components/settings/BackendTestPanel.tsx+++ b/ui/src/components/settings/BackendTestPanel.tsx@@ -8,6 +8,7 @@ import { Select } from '@/components/ui/select';import { useApi } from '@/context/ApiContext';import type { BackendAuthTestResult } from '@/context/ApiContext';import { useToast } from '@/context/ToastContext';+import { errorMessage } from '@/lib/errorMessage';type Backend = 'claude' | 'codex';@@ -103,8 +104,8 @@ export const BackendTestPanel: React.FC<BackendTestPanelProps> = ({ backend }) =} else {showToast(failureSentence(result), 'error');}- } catch (err: any) {- const fallback = { ok: false, error: err?.message || 'test_failed' } as BackendAuthTestResult;+ } catch (err) {+ const fallback = { ok: false, error: errorMessage(err) || 'test_failed' } as BackendAuthTestResult;setLastResult(fallback);showToast(t('settings.backends.testConnectionFailedToast', { detail: fallback.error }), 'error');} finally {diff --git a/ui/src/components/settings/OpencodeProviderTestPanel.tsx b/ui/src/components/settings/OpencodeProviderTestPanel.tsxindex 127fe9086..30fdbf6e1 100644--- a/ui/src/components/settings/OpencodeProviderTestPanel.tsx+++ b/ui/src/components/settings/OpencodeProviderTestPanel.tsx@@ -8,6 +8,7 @@ import { Select } from '@/components/ui/select';import { useApi } from '@/context/ApiContext';import type { BackendAuthTestResult } from '@/context/ApiContext';import { useToast } from '@/context/ToastContext';+import { errorMessage } from '@/lib/errorMessage';export type OpencodeProviderTestPanelProps = {providerId: string;@@ -94,8 +95,8 @@ export const OpencodeProviderTestPanel: React.FC<OpencodeProviderTestPanelProps>} else {showToast(failureSentence(result), 'error');}- } catch (err: any) {- const fallback = { ok: false, error: err?.message || 'test_failed' } as BackendAuthTestResult;+ } catch (err) {+ const fallback = { ok: false, error: errorMessage(err) || 'test_failed' } as BackendAuthTestResult;setLastResult(fallback);showToast(t('settings.backends.testConnectionFailedToast', { detail: fallback.error }),diff --git a/ui/src/components/settings/SettingsBackendsPage.tsx b/ui/src/components/settings/SettingsBackendsPage.tsxindex a990be97a..2326b792d 100644--- a/ui/src/components/settings/SettingsBackendsPage.tsx+++ b/ui/src/components/settings/SettingsBackendsPage.tsx@@ -10,6 +10,7 @@ import { SettingsPageShell } from './SettingsPageShell';import { useApi } from '@/context/ApiContext';import { useToast } from '@/context/ToastContext';import { AGENT_BACKENDS, DEFAULT_AGENT_STATE } from '@/lib/agentBackends';+import { errorMessage } from '@/lib/errorMessage';// Mirrors design.pen qVHh4 (VR/CM/Backends): three horizontal cards// (OpenCode/Claude/Codex). Each card@@ -112,8 +113,8 @@ export const SettingsBackendsPage: React.FC = () => {agents: nextAgents,});showToast(t('common.saved'), 'success');- } catch (e: any) {- showToast(e?.message || t('common.saveFailed'), 'error');+ } catch (e) {+ showToast(errorMessage(e) || t('common.saveFailed'), 'error');}};diff --git a/ui/src/components/settings/SettingsDependenciesPage.tsx b/ui/src/components/settings/SettingsDependenciesPage.tsxindex 4f8d6eede..b92199245 100644--- a/ui/src/components/settings/SettingsDependenciesPage.tsx+++ b/ui/src/components/settings/SettingsDependenciesPage.tsx@@ -23,6 +23,7 @@ import { SettingsResourceRow } from './SettingsPrimitives';import { useApi } from '@/context/ApiContext';import type { DependencyItem } from '@/context/ApiContext';import { useToast } from '@/context/ToastContext';+import { errorMessage } from '@/lib/errorMessage';// Mirrors design.pen "vibe-remote — Settings · Dependencies": one card per// required local runtime (icon tile + name/REQUIRED + detail + status pill +@@ -73,8 +74,8 @@ export const SettingsDependenciesPage: React.FC = () => {res.ok ? 'success' : 'error');await refresh();- } catch (e: any) {- showToast(e?.message || t('settings.dependencies.installFailed'), 'error');+ } catch (e) {+ showToast(errorMessage(e) || t('settings.dependencies.installFailed'), 'error');} finally {setBusy(null);}diff --git a/ui/src/components/settings/models/AddApiKeyDialog.tsx b/ui/src/components/settings/models/AddApiKeyDialog.tsxindex 832ec6952..94120ab6b 100644--- a/ui/src/components/settings/models/AddApiKeyDialog.tsx+++ b/ui/src/components/settings/models/AddApiKeyDialog.tsx@@ -23,6 +23,7 @@ import { Field } from './dialogFields';import { adoptionVerdict } from './sufficiency';import { DEFAULT_VENDOR, VENDOR_OPTIONS } from './vendorMeta';import type { Source } from './types';+import { errorMessage } from '@/lib/errorMessage';/** Nothing created yet. `skipped_by: null` rather than `[]` for the reason the* reader defaults it that way: 「nobody was left out」 is a claim, and no@@ -104,9 +105,12 @@ export const AddApiKeyDialog: React.FC<{// the same answer this site gave before the field existed.if (adoptionVerdict(adopted_by, skipped_by).kind === 'covered')closeTimer.current = window.setTimeout(onClose, 1500);- } catch (e: any) {+ } catch (e) {if (submitSeq.current !== seq) return;- const code = e?.code || e?.message || 'discovery_failed';+ // The engine reports a machine-readable `code`; fall back to the message+ // and then to a generic key so the copy lookup always has something.+ const rawCode = (e as { code?: unknown } | null | undefined)?.code;+ const code = (typeof rawCode === 'string' ? rawCode : undefined) || errorMessage(e) || 'discovery_failed';setError(code === 'engine_down' ? (t('settings.models.errors.engineDown') as string) : code);setPhase('error');}diff --git a/ui/src/components/settings/models/AgentCard.test.tsx b/ui/src/components/settings/models/AgentCard.test.tsxindex 82be715b7..98f614137 100644--- a/ui/src/components/settings/models/AgentCard.test.tsx+++ b/ui/src/components/settings/models/AgentCard.test.tsx@@ -6,7 +6,7 @@ import { describe, expect, it, vi } from 'vitest';import en from '../../../i18n/en.json';import zh from '../../../i18n/zh.json';-import { ToastProvider } from '@/context/ToastContext';+import { ToastProvider } from '@/context/ToastProvider';import { AgentCard } from './AgentCard';import { modelChainKey, type ModelChainIndex } from './modelRows';import type { AgentChain, AgentSupply, Source } from './types';diff --git a/ui/src/components/settings/models/MigrationBanner.tsx b/ui/src/components/settings/models/MigrationBanner.tsxindex d27f46ba7..dcb6a13b2 100644--- a/ui/src/components/settings/models/MigrationBanner.tsx+++ b/ui/src/components/settings/models/MigrationBanner.tsx@@ -12,15 +12,10 @@ import { useTranslation } from 'react-i18next';import { Button } from '@/components/ui/button';import { isMigrationDismissed, writeMigrationDismissed } from '@/lib/modelHubMigrationDismiss';import { MigrationDialog } from './MigrationDialog';-import { modelsApi } from './modelsApi';+import { scanMigrationWhenEnabled } from './migrationScan';import type { MigrationItem } from './types';import { useModelHubCapability } from './useModelHubCapability';-export const scanMigrationWhenEnabled = async (- enabled: boolean,- scan: typeof modelsApi.scanMigration = modelsApi.scanMigration,-) => (enabled ? scan() : null);-export const MigrationBanner: React.FC<{/** Bubble the applied count so a host page can refresh sources/agents. */onApplied?: (applied: number) => void;diff --git a/ui/src/components/settings/models/ModelHubCapabilityGate.test.tsx b/ui/src/components/settings/models/ModelHubCapabilityGate.test.tsxindex 314e39885..65e9f2f20 100644--- a/ui/src/components/settings/models/ModelHubCapabilityGate.test.tsx+++ b/ui/src/components/settings/models/ModelHubCapabilityGate.test.tsx@@ -1,12 +1,12 @@import { renderToStaticMarkup } from 'react-dom/server';-import { describe, expect, it } from 'vitest';+import { describe, expect, it, vi } from 'vitest';+import { ModelHubRenderBoundary } from './ModelHubCapabilityGate';import {MODEL_HUB_DISABLED_REDIRECT,MODEL_HUB_SETTINGS_PATH,- ModelHubRenderBoundary,modelHubRouteTarget,-} from './ModelHubCapabilityGate';+} from './modelHubRoutes';describe('Model Hub capability route gate', () => {it('redirects both current and legacy model routes while disabled', () => {@@ -15,11 +15,7 @@ describe('Model Hub capability route gate', () => {});it('does not render the Models child while disabled or unresolved', () => {- let childRenders = 0;- const ModelsChunk = () => {- childRenders += 1;- return <div>models chunk</div>;- };+ const ModelsChunk = vi.fn(() => <div>models chunk</div>);const disabledHtml = renderToStaticMarkup(<ModelHubRenderBoundary enabled={false} disabled={<div>disabled</div>}>@@ -34,15 +30,11 @@ describe('Model Hub capability route gate', () => {expect(disabledHtml).toContain('disabled');expect(unresolvedHtml).toBe('');- expect(childRenders).toBe(0);+ expect(ModelsChunk).not.toHaveBeenCalled();});it('renders the Models child only after the backend enables it', () => {- let childRenders = 0;- const ModelsChunk = () => {- childRenders += 1;- return <div>models chunk</div>;- };+ const ModelsChunk = vi.fn(() => <div>models chunk</div>);expect(renderToStaticMarkup(@@ -51,6 +43,6 @@ describe('Model Hub capability route gate', () => {</ModelHubRenderBoundary>,),).toContain('models chunk');- expect(childRenders).toBe(1);+ expect(ModelsChunk).toHaveBeenCalledTimes(1);});});diff --git a/ui/src/components/settings/models/ModelHubCapabilityGate.tsx b/ui/src/components/settings/models/ModelHubCapabilityGate.tsxindex c4936ec3e..676929749 100644--- a/ui/src/components/settings/models/ModelHubCapabilityGate.tsx+++ b/ui/src/components/settings/models/ModelHubCapabilityGate.tsx@@ -2,12 +2,7 @@ import * as React from 'react';import { Navigate } from 'react-router-dom';import { useModelHubCapability } from './useModelHubCapability';--export const MODEL_HUB_SETTINGS_PATH = '/admin/settings/models';-export const MODEL_HUB_DISABLED_REDIRECT = '/admin/settings/backends';--export const modelHubRouteTarget = (requestedPath: string, enabled: boolean): string =>- enabled ? requestedPath : MODEL_HUB_DISABLED_REDIRECT;+import { MODEL_HUB_DISABLED_REDIRECT, MODEL_HUB_SETTINGS_PATH, modelHubRouteTarget } from './modelHubRoutes';export const ModelHubRenderBoundary: React.FC<{enabled: boolean | null;diff --git a/ui/src/components/settings/models/RuntimeNotStartedAction.test.tsx b/ui/src/components/settings/models/RuntimeNotStartedAction.test.tsxindex 50c1859af..5e04d5988 100644--- a/ui/src/components/settings/models/RuntimeNotStartedAction.test.tsx+++ b/ui/src/components/settings/models/RuntimeNotStartedAction.test.tsx@@ -8,12 +8,8 @@ import { I18nextProvider, initReactI18next } from 'react-i18next';import { describe, expect, it, vi } from 'vitest';import zh from '../../../i18n/zh.json';-import {- ModelsPageActions,- pollRuntimeStatus,- RuntimeNotStartedAction,- startRuntimeWithStatusRefresh,-} from './SettingsModelsPage';+import { pollRuntimeStatus, startRuntimeWithStatusRefresh } from './runtimeLifecycle';+import { ModelsPageActions, RuntimeNotStartedAction } from './SettingsModelsPage';import type { RuntimeDependency } from './types';const i18n = createInstance();diff --git a/ui/src/components/settings/models/SettingsModelsPage.tsx b/ui/src/components/settings/models/SettingsModelsPage.tsxindex f587a152d..5b4950ff1 100644--- a/ui/src/components/settings/models/SettingsModelsPage.tsx+++ b/ui/src/components/settings/models/SettingsModelsPage.tsx@@ -32,7 +32,8 @@ import {} from './eventFeed';import { AddCustomModelDialog } from './menus/AddCustomModelDialog';import { OpenCodeMenuDrawer } from './menus/OpenCodeMenuDrawer';-import { modelsApi, type ModelsApi } from './modelsApi';+import { modelsApi } from './modelsApi';+import { pollRuntimeStatus, startRuntimeWithStatusRefresh } from './runtimeLifecycle';import { connectOutcome, isSupplyWarning } from './sufficiency';import {manualModelSources,@@ -128,47 +129,6 @@ export const ModelsPageActions: React.FC<{);};-export async function startRuntimeWithStatusRefresh(- api: Pick<ModelsApi, 'startRuntime' | 'getRuntimeStatus'>,-): Promise<{ runtime: RuntimeDependency | null; failed: boolean }> {- try {- const runtime = await api.startRuntime();- return { runtime, failed: runtime.status.health !== 'ok' };- } catch {- // A failed start changes supervisor health. Read that authoritative state- // back so the persistent page does not keep presenting lazy-start idleness.- const runtime = await api.getRuntimeStatus().catch(() => null);- return { runtime, failed: runtime?.status.health !== 'ok' };- }-}--export function pollRuntimeStatus(- api: Pick<ModelsApi, 'getRuntimeStatus'>,- onRuntime: (runtime: RuntimeDependency) => void,- intervalMs = 5_000,-): () => void {- let active = true;- let timeout: ReturnType<typeof globalThis.setTimeout> | undefined;- const schedule = () => {- timeout = globalThis.setTimeout(() => void refresh(), intervalMs);- };- const refresh = async () => {- try {- const runtime = await api.getRuntimeStatus();- if (active) onRuntime(runtime);- } catch {- // Keep the last authoritative snapshot and try again on the next tick.- } finally {- if (active) schedule();- }- };- schedule();- return () => {- active = false;- if (timeout !== undefined) globalThis.clearTimeout(timeout);- };-}-const CHAIN_READ_CONCURRENCY = 6;const readModelChains = async (agents: AgentSupply[]): Promise<ModelChainIndex> => {diff --git a/ui/src/components/settings/models/SourceRow.test.tsx b/ui/src/components/settings/models/SourceRow.test.tsxindex 91ef04ebb..7241cda18 100644--- a/ui/src/components/settings/models/SourceRow.test.tsx+++ b/ui/src/components/settings/models/SourceRow.test.tsx@@ -3,7 +3,7 @@ import { renderToStaticMarkup } from 'react-dom/server';import { I18nextProvider, initReactI18next } from 'react-i18next';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { ToastProvider } from '@/context/ToastContext';+import { ToastProvider } from '@/context/ToastProvider';import en from '../../../i18n/en.json';import zh from '../../../i18n/zh.json';import { SourceRow } from './SourceRow';diff --git a/ui/src/components/settings/models/MigrationBanner.test.ts b/ui/src/components/settings/models/migrationScan.test.tssimilarity index 91%rename from ui/src/components/settings/models/MigrationBanner.test.tsrename to ui/src/components/settings/models/migrationScan.test.tsindex d2101261c..1670212f2 100644--- a/ui/src/components/settings/models/MigrationBanner.test.ts+++ b/ui/src/components/settings/models/migrationScan.test.ts@@ -1,6 +1,6 @@import { describe, expect, it, vi } from 'vitest';-import { scanMigrationWhenEnabled } from './MigrationBanner';+import { scanMigrationWhenEnabled } from './migrationScan';describe('scanMigrationWhenEnabled', () => {it('does not issue a migration scan while Model Hub is disabled', async () => {diff --git a/ui/src/components/settings/models/migrationScan.ts b/ui/src/components/settings/models/migrationScan.tsnew file mode 100644index 000000000..9b895f120--- /dev/null+++ b/ui/src/components/settings/models/migrationScan.ts@@ -0,0 +1,9 @@+// Whether a migration scan may run at all. Gated on the Model Hub capability so a+// disabled instance issues no scan request; separated from MigrationBanner so the+// gate is testable without rendering the strip.+import { modelsApi } from './modelsApi';++export const scanMigrationWhenEnabled = async (+ enabled: boolean,+ scan: typeof modelsApi.scanMigration = modelsApi.scanMigration,+) => (enabled ? scan() : null);diff --git a/ui/src/components/settings/models/modelHubRoutes.ts b/ui/src/components/settings/models/modelHubRoutes.tsnew file mode 100644index 000000000..34a65b886--- /dev/null+++ b/ui/src/components/settings/models/modelHubRoutes.ts@@ -0,0 +1,8 @@+// Where a Model Hub route lands, by capability. Pure so the redirect contract can be+// asserted without mounting the router (see ModelHubCapabilityGate.test.tsx).++export const MODEL_HUB_SETTINGS_PATH = '/admin/settings/models';+export const MODEL_HUB_DISABLED_REDIRECT = '/admin/settings/backends';++export const modelHubRouteTarget = (requestedPath: string, enabled: boolean): string =>+ enabled ? requestedPath : MODEL_HUB_DISABLED_REDIRECT;diff --git a/ui/src/components/settings/models/runtimeLifecycle.ts b/ui/src/components/settings/models/runtimeLifecycle.tsnew file mode 100644index 000000000..a91fac3e7--- /dev/null+++ b/ui/src/components/settings/models/runtimeLifecycle.ts@@ -0,0 +1,48 @@+// Starting and observing the model runtime. Both helpers read supervisor health+// back from the server rather than trusting the local optimistic guess, so the+// persistent Models page never keeps presenting lazy-start idleness after a+// failed start. Pure of React so the contract is unit-testable+// (see RuntimeNotStartedAction.test.tsx).+import type { ModelsApi } from './modelsApi';+import type { RuntimeDependency } from './types';++export async function startRuntimeWithStatusRefresh(+ api: Pick<ModelsApi, 'startRuntime' | 'getRuntimeStatus'>,+): Promise<{ runtime: RuntimeDependency | null; failed: boolean }> {+ try {+ const runtime = await api.startRuntime();+ return { runtime, failed: runtime.status.health !== 'ok' };+ } catch {+ // A failed start changes supervisor health. Read that authoritative state+ // back so the persistent page does not keep presenting lazy-start idleness.+ const runtime = await api.getRuntimeStatus().catch(() => null);+ return { runtime, failed: runtime?.status.health !== 'ok' };+ }+}++export function pollRuntimeStatus(+ api: Pick<ModelsApi, 'getRuntimeStatus'>,+ onRuntime: (runtime: RuntimeDependency) => void,+ intervalMs = 5_000,+): () => void {+ let active = true;+ let timeout: ReturnType<typeof globalThis.setTimeout> | undefined;+ const schedule = () => {+ timeout = globalThis.setTimeout(() => void refresh(), intervalMs);+ };+ const refresh = async () => {+ try {+ const runtime = await api.getRuntimeStatus();+ if (active) onRuntime(runtime);+ } catch {+ // Keep the last authoritative snapshot and try again on the next tick.+ } finally {+ if (active) schedule();+ }+ };+ schedule();+ return () => {+ active = false;+ if (timeout !== undefined) globalThis.clearTimeout(timeout);+ };+}diff --git a/ui/src/components/settings/models/vendorMeta.tsx b/ui/src/components/settings/models/vendorMeta.tssimilarity index 100%rename from ui/src/components/settings/models/vendorMeta.tsxrename to ui/src/components/settings/models/vendorMeta.tsdiff --git a/ui/src/components/settings/providers/ClaudeProviderConfig.tsx b/ui/src/components/settings/providers/ClaudeProviderConfig.tsxindex f651125d0..b073e2f5d 100644--- a/ui/src/components/settings/providers/ClaudeProviderConfig.tsx+++ b/ui/src/components/settings/providers/ClaudeProviderConfig.tsx@@ -28,6 +28,7 @@ import { useOAuthFlowLock } from '../shared/useOAuthFlowLock';import { useApi } from '@/context/ApiContext';import type { ClaudeAuthMode, ClaudeAuthState } from '@/context/ApiContext';import { useToast } from '@/context/ToastContext';+import { errorMessage } from '@/lib/errorMessage';const BACKEND_ID = 'claude';const DEFAULT_CLI = 'claude';@@ -157,9 +158,9 @@ export const ClaudeProviderConfig: React.FC<{} else {showToast(t('settings.backends.claudeApiKeyRemoved'), 'success');}- } catch (err: any) {+ } catch (err) {showToast(- t('settings.backends.claudeApiKeyRemoveFailed', { detail: err?.message || 'unknown' }),+ t('settings.backends.claudeApiKeyRemoveFailed', { detail: errorMessage(err) || 'unknown' }),'error',);} finally {@@ -204,8 +205,8 @@ export const ClaudeProviderConfig: React.FC<{} else {showToast(t('settings.backends.claudeSaveSuccess'), 'success');}- } catch (err: any) {- showToast(err?.message || t('settings.backends.claudeSaveFailed'), 'error');+ } catch (err) {+ showToast(errorMessage(err) || t('settings.backends.claudeSaveFailed'), 'error');} finally {setAuthSaving(false);}diff --git a/ui/src/components/settings/providers/CodexProviderConfig.tsx b/ui/src/components/settings/providers/CodexProviderConfig.tsxindex 6e1d3981e..b2c7ca392 100644--- a/ui/src/components/settings/providers/CodexProviderConfig.tsx+++ b/ui/src/components/settings/providers/CodexProviderConfig.tsx@@ -19,6 +19,7 @@ import { SegmentedRadio } from '../shared/SegmentedRadio';import { surfaceBackendNotices } from '../shared/surfaceBackendNotices';import { useBackendRuntime } from '../shared/useBackendRuntime';import { useOAuthFlowLock } from '../shared/useOAuthFlowLock';+import { errorMessage } from '@/lib/errorMessage';const BACKEND_ID = 'codex';const DEFAULT_CLI = 'codex';@@ -148,9 +149,9 @@ export const CodexProviderConfig: React.FC<{setEditingKey(false);showToast(t('settings.backends.codexApiKeyRemoved'), 'success');surfaceBackendNotices(result.notices, showToast, t);- } catch (err: any) {+ } catch (err) {showToast(- t('settings.backends.codexApiKeyRemoveFailed', { detail: err?.message || 'unknown' }),+ t('settings.backends.codexApiKeyRemoveFailed', { detail: errorMessage(err) || 'unknown' }),'error',);} finally {@@ -202,8 +203,8 @@ export const CodexProviderConfig: React.FC<{showToast(t('settings.backends.codexSaveSuccess'), 'success');}surfaceBackendNotices(result.notices, showToast, t);- } catch (err: any) {- showToast(err?.message || t('settings.backends.codexSaveFailed'), 'error');+ } catch (err) {+ showToast(errorMessage(err) || t('settings.backends.codexSaveFailed'), 'error');} finally {setSaving(false);}diff --git a/ui/src/components/settings/providers/OpencodeProviderConfig.tsx b/ui/src/components/settings/providers/OpencodeProviderConfig.tsxindex ffeb42fec..866b9254e 100644--- a/ui/src/components/settings/providers/OpencodeProviderConfig.tsx+++ b/ui/src/components/settings/providers/OpencodeProviderConfig.tsx@@ -44,6 +44,7 @@ import type {OpencodeProviderListResult,} from '@/context/ApiContext';import { useToast } from '@/context/ToastContext';+import { errorMessage } from '@/lib/errorMessage';type FilterMode = 'all' | 'configured' | 'oauth' | 'local';type CustomProviderAdapter = 'openai-compatible' | 'anthropic-compatible';@@ -222,9 +223,9 @@ export const OpencodeProviderConfig: React.FC<{setProviders((prev) => prev ?? []);setProvidersError(result.message || t('settings.backends.opencodeProvidersError'));}- } catch (e: any) {+ } catch (e) {setProviders((prev) => prev ?? []);- setProvidersError(e?.message || t('settings.backends.opencodeProvidersError'));+ setProvidersError(errorMessage(e) || t('settings.backends.opencodeProvidersError'));} finally {setProvidersLoading(false);}@@ -432,10 +433,10 @@ export const OpencodeProviderConfig: React.FC<{...prev,[nextId]: { ...(prev[nextId] || emptyEdit()), baseUrl },}));- } catch (e: any) {+ } catch (e) {updateCustomProviderDraft({saving: false,- error: e?.message || (t('settings.backends.opencodeCustomProviderSaveFailed') as string),+ error: errorMessage(e) || (t('settings.backends.opencodeCustomProviderSaveFailed') as string),});}};@@ -460,10 +461,10 @@ export const OpencodeProviderConfig: React.FC<{notifyOpenCodeModelOptionsChanged();if (expandedId === provider.id) setExpandedId(null);await loadProviders();- } catch (e: any) {+ } catch (e) {updateEdit(provider.id, {deletingProvider: false,- error: e?.message || (t('settings.backends.opencodeCustomProviderRemoveFailed') as string),+ error: errorMessage(e) || (t('settings.backends.opencodeCustomProviderRemoveFailed') as string),});}};@@ -518,10 +519,10 @@ export const OpencodeProviderConfig: React.FC<{if (!applyMutationCatalogRefresh(result)) {await loadProviders();}- } catch (e: any) {+ } catch (e) {updateEdit(provider.id, {saving: false,- error: e?.message || (t('settings.backends.opencodeProviderSaveFailed') as string),+ error: errorMessage(e) || (t('settings.backends.opencodeProviderSaveFailed') as string),});}};@@ -550,10 +551,10 @@ export const OpencodeProviderConfig: React.FC<{showToast(t('settings.backends.opencodeProviderRemoved'), 'success');notifyOpenCodeModelOptionsChanged();await loadProviders();- } catch (e: any) {+ } catch (e) {updateEdit(provider.id, {removing: false,- error: e?.message || (t('settings.backends.opencodeProviderRemoveFailed') as string),+ error: errorMessage(e) || (t('settings.backends.opencodeProviderRemoveFailed') as string),});}};@@ -605,10 +606,10 @@ export const OpencodeProviderConfig: React.FC<{showToast(t('settings.backends.opencodeProviderModelSaved'), 'success');notifyOpenCodeModelOptionsChanged();await loadProviders();- } catch (e: any) {+ } catch (e) {updateEdit(provider.id, {modelSaving: false,- error: e?.message || (t('settings.backends.opencodeProviderModelSaveFailed') as string),+ error: errorMessage(e) || (t('settings.backends.opencodeProviderModelSaveFailed') as string),});}};@@ -628,10 +629,10 @@ export const OpencodeProviderConfig: React.FC<{showToast(t('settings.backends.opencodeProviderModelRemoved'), 'success');notifyOpenCodeModelOptionsChanged();await loadProviders();- } catch (e: any) {+ } catch (e) {updateEdit(provider.id, {removingModelId: null,- error: e?.message || (t('settings.backends.opencodeProviderModelRemoveFailed') as string),+ error: errorMessage(e) || (t('settings.backends.opencodeProviderModelRemoveFailed') as string),});}};@@ -678,8 +679,8 @@ export const OpencodeProviderConfig: React.FC<{showToast(t('settings.backends.opencodeDefaultSaved', { name: provider.name }), 'success');setDefaultPopoverOpen(false);setDefaultSearchQuery('');- } catch (e: any) {- showToast(e?.message || (t('settings.backends.opencodeDefaultSaveFailed') as string), 'error');+ } catch (e) {+ showToast(errorMessage(e) || (t('settings.backends.opencodeDefaultSaveFailed') as string), 'error');} finally {setSettingDefault(false);}diff --git a/ui/src/components/settings/shared/useBackendRuntime.ts b/ui/src/components/settings/shared/useBackendRuntime.tsindex 73a3b2e14..b36a5e799 100644--- a/ui/src/components/settings/shared/useBackendRuntime.ts+++ b/ui/src/components/settings/shared/useBackendRuntime.ts@@ -3,6 +3,7 @@ import { useTranslation } from 'react-i18next';import { useApi } from '@/context/ApiContext';import { useToast } from '@/context/ToastContext';+import { errorMessage } from '@/lib/errorMessage';export type CliStatus = 'unknown' | 'ok' | 'missing';@@ -126,9 +127,9 @@ export function useBackendRuntime({const nextPath = result.path || cliPath || defaultCli;setCliPath(nextPath);setCliStatus(result.found ? 'ok' : 'missing');- } catch (e: any) {+ } catch (e) {setCliStatus('missing');- showToast(e?.message || t('common.saveFailed'), 'error');+ showToast(errorMessage(e) || t('common.saveFailed'), 'error');} finally {setDetecting(false);}@@ -189,9 +190,9 @@ export function useBackendRuntime({} else {showToast(result.message || t('common.saveFailed'), 'error');}- } catch (e: any) {+ } catch (e) {setInstallResult({ ok: false, message: String(e), output: null });- showToast(e?.message || String(e), 'error');+ showToast(errorMessage(e) || String(e), 'error');} finally {setInstalling(false);}@@ -216,8 +217,8 @@ export function useBackendRuntime({assertBackendRuntimeApplied(saved, t('common.saveFailed'));setSavedCliPath(cliPath);showToast(t('common.saved'), 'success');- } catch (e: any) {- showToast(e?.message || t('common.saveFailed'), 'error');+ } catch (e) {+ showToast(errorMessage(e) || t('common.saveFailed'), 'error');} finally {setSavingRuntime(false);}@@ -246,8 +247,8 @@ export function useBackendRuntime({});saved = true;assertBackendRuntimeApplied(savedConfig, t('common.saveFailed'));- } catch (e: any) {- showToast(e?.message || t('common.saveFailed'), 'error');+ } catch (e) {+ showToast(errorMessage(e) || t('common.saveFailed'), 'error');if (!saved) setEnabled(!next);}})();diff --git a/ui/src/components/settings/shared/useOAuthFlowLock.ts b/ui/src/components/settings/shared/useOAuthFlowLock.tsindex 7f25ecda5..b7062dfa7 100644--- a/ui/src/components/settings/shared/useOAuthFlowLock.ts+++ b/ui/src/components/settings/shared/useOAuthFlowLock.ts@@ -1,7 +1,8 @@-import { useCallback, useRef, useState } from 'react';+import { useCallback, useState } from 'react';import { useTranslation } from 'react-i18next';import { useToast } from '@/context/ToastContext';+import { useLatestRef } from '@/lib/useLatestRef';export interface UseOAuthFlowLockOptions<TMode extends string> {/** The real auth-mode setter that the page owns. */@@ -53,13 +54,11 @@ export function useOAuthFlowLock<TMode extends string>({// Ref so the guard always sees the latest value without rebuilding the// callback (and therefore the SegmentedRadio's ``onChange`` reference)// on every render.- const oauthFlowActiveRef = useRef(oauthFlowActive);- oauthFlowActiveRef.current = oauthFlowActive;+ const oauthFlowActiveRef = useLatestRef(oauthFlowActive);const guardedSetAuthMode = useCallback((next: TMode) => {if (oauthFlowActiveRef.current) {- // eslint-disable-next-line no-consoleconsole.warn('[%s] rejected change to %s while OAuth flow active',warnTag,diff --git a/ui/src/components/steps/ChannelList.tsx b/ui/src/components/steps/ChannelList.tsxindex 1d7c0caa4..70be0e437 100644--- a/ui/src/components/steps/ChannelList.tsx+++ b/ui/src/components/steps/ChannelList.tsx@@ -1023,7 +1023,6 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onBcounts[p] = { total, active };}return counts;- // eslint-disable-next-line react-hooks/exhaustive-deps}, [config, platform, channels, configs, allChannelsByPlatform, allConfigsByPlatform]);const allTabCounts = useMemo(() => {@@ -2156,7 +2155,7 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onBif (isWizardMultiPlatform) {// Merge configs from all visited platformsconst allConfigs = { ...wizardConfigsMap, [wizardActivePlatform]: configs };- onNext && onNext({+ onNext?.({channelConfigsByPlatform: {...(data.channelConfigsByPlatform || {}),...allConfigs,@@ -2164,7 +2163,7 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB...(getEnabledPlatforms(data).includes('discord') ? { discordGuildAllowlist } : {}),});} else {- onNext && onNext({+ onNext?.({channelConfigsByPlatform: {...(data.channelConfigsByPlatform || {}),[platform]: configs,diff --git a/ui/src/components/steps/DiscordConfig.tsx b/ui/src/components/steps/DiscordConfig.tsxindex 89a4f1876..d73893802 100644--- a/ui/src/components/steps/DiscordConfig.tsx+++ b/ui/src/components/steps/DiscordConfig.tsx@@ -24,6 +24,7 @@ import { ProxyUrlField } from '../shared/ProxyUrlField';import { StepHeader, StepShell } from '../shared/WizardStep';import { Button } from '../ui/button';import { Input } from '../ui/input';+import { errorMessage } from '@/lib/errorMessage';interface DiscordConfigProps {data: any;@@ -85,8 +86,8 @@ export const DiscordConfig: React.FC<DiscordConfigProps> = ({ data, onNext, onBatry {const result = await api.discordAuthTest(botToken, proxyUrl);setAuthResult(result);- } catch (err: any) {- setAuthResult({ ok: false, error: err?.message || 'Request failed' });+ } catch (err) {+ setAuthResult({ ok: false, error: errorMessage(err) || 'Request failed' });} finally {setChecking(false);}diff --git a/ui/src/components/steps/LarkConfig.tsx b/ui/src/components/steps/LarkConfig.tsxindex 307401f46..3e62394cf 100644--- a/ui/src/components/steps/LarkConfig.tsx+++ b/ui/src/components/steps/LarkConfig.tsx@@ -32,6 +32,7 @@ import { ProxyUrlField } from '../shared/ProxyUrlField';import { StepHeader, StepShell } from '../shared/WizardStep';import { Button } from '../ui/button';import { Input } from '../ui/input';+import { errorMessage } from '@/lib/errorMessage';const LinkButton: React.FC<{ url: string; label: string }> = ({ url, label }) => (<Button variant="brand" size="sm" onClick={() => window.open(url, '_blank')} disabled={!url}>@@ -150,8 +151,8 @@ export const LarkConfig: React.FC<LarkConfigProps> = ({ data, onNext, onBack, emsetWsStatus('error');}}- } catch (err: any) {- setAuthResult({ ok: false, error: err?.message || 'Request failed' });+ } catch (err) {+ setAuthResult({ ok: false, error: errorMessage(err) || 'Request failed' });} finally {setChecking(false);}diff --git a/ui/src/components/steps/SlackConfig.tsx b/ui/src/components/steps/SlackConfig.tsxindex 9b061db87..4645b399c 100644--- a/ui/src/components/steps/SlackConfig.tsx+++ b/ui/src/components/steps/SlackConfig.tsx@@ -11,6 +11,7 @@ import { ProxyUrlField } from '../shared/ProxyUrlField';import { StepHeader, StepShell } from '../shared/WizardStep';import { Button } from '../ui/button';import { Input } from '../ui/input';+import { errorMessage } from '@/lib/errorMessage';interface SlackConfigProps {data: any;@@ -110,8 +111,8 @@ export const SlackConfig: React.FC<SlackConfigProps> = ({ data, onNext, onBack,try {const result = await api.slackAuthTest(botToken, proxyUrl);setAuthResult(result);- } catch (err: any) {- setAuthResult({ ok: false, error: err?.message || 'Request failed' });+ } catch (err) {+ setAuthResult({ ok: false, error: errorMessage(err) || 'Request failed' });} finally {setChecking(false);}diff --git a/ui/src/components/steps/Summary.tsx b/ui/src/components/steps/Summary.tsxindex 6702ea741..3cf98281f 100644--- a/ui/src/components/steps/Summary.tsx+++ b/ui/src/components/steps/Summary.tsx@@ -22,6 +22,7 @@ import { withoutConfiguredSecretMarker, withSecretDraft, withSecretDrafts } fromimport { EyebrowBadge, WizardCard } from '../visual';import { ToggleSwitch } from '../settings/SettingsPrimitives';import { Button } from '../ui/button';+import { errorMessage } from '@/lib/errorMessage';interface SummaryProps {data: any;@@ -161,8 +162,8 @@ export const Summary: React.FC<SummaryProps> = ({ data, onBack }) => {setTimeout(() => {navigate('/');}, 1000);- } catch (exc: any) {- const message = exc && exc.message ? exc.message : 'Failed to save configuration';+ } catch (exc) {+ const message = errorMessage(exc) || 'Failed to save configuration';setError(message);} finally {setSaving(false);diff --git a/ui/src/components/steps/TelegramConfig.tsx b/ui/src/components/steps/TelegramConfig.tsxindex 2b7373a9a..192d19954 100644--- a/ui/src/components/steps/TelegramConfig.tsx+++ b/ui/src/components/steps/TelegramConfig.tsx@@ -24,6 +24,7 @@ import { StepHeader, StepShell } from '../shared/WizardStep';import { ToggleSwitch } from '../settings/SettingsPrimitives';import { Button } from '../ui/button';import { Input } from '../ui/input';+import { errorMessage } from '@/lib/errorMessage';interface TelegramConfigProps {data: any;@@ -78,8 +79,8 @@ export const TelegramConfig: React.FC<TelegramConfigProps> = ({ data, onNext, ontry {const result = await api.telegramAuthTest(botToken, proxyUrl);setAuthResult(result);- } catch (err: any) {- setAuthResult({ ok: false, error: err?.message || 'Request failed' });+ } catch (err) {+ setAuthResult({ ok: false, error: errorMessage(err) || 'Request failed' });} finally {setChecking(false);}diff --git a/ui/src/components/steps/WeChatConfig.tsx b/ui/src/components/steps/WeChatConfig.tsxindex b3c619e98..0813ae317 100644--- a/ui/src/components/steps/WeChatConfig.tsx+++ b/ui/src/components/steps/WeChatConfig.tsx@@ -19,6 +19,7 @@ import { EmbeddedConfigShell, EyebrowBadge, WizardCard } from '../visual';import { ProxyUrlField } from '../shared/ProxyUrlField';import { Button } from '../ui/button';import { Input } from '../ui/input';+import { errorMessage } from '@/lib/errorMessage';interface WeChatConfigProps {data: Record<string, any>;@@ -113,7 +114,7 @@ export const WeChatConfig: React.FC<WeChatConfigProps> = ({activeSessionKeyRef.current = result.session_key;startPolling(result.session_key);}- } catch (err: any) {+ } catch (err) {try {await new Promise((resolve) => setTimeout(resolve, 800));const retryResult = await api.wechatStartLogin();@@ -129,9 +130,9 @@ export const WeChatConfig: React.FC<WeChatConfigProps> = ({activeSessionKeyRef.current = retryResult.session_key;startPolling(retryResult.session_key);}- } catch (retryErr: any) {+ } catch (retryErr) {setLoginState('error');- setMessage(retryErr?.message || err?.message || t('wechatConfig.startFailed'));+ setMessage(errorMessage(retryErr) || errorMessage(err) || t('wechatConfig.startFailed'));}} finally {setStarting(false);@@ -278,8 +279,8 @@ export const WeChatConfig: React.FC<WeChatConfigProps> = ({return;}startPolling(key);- } catch (err: any) {- setMessage(err?.message || t('wechatConfig.pollError'));+ } catch (err) {+ setMessage(errorMessage(err) || t('wechatConfig.pollError'));startPolling(key);}};diff --git a/ui/src/components/ui/badge-variants.ts b/ui/src/components/ui/badge-variants.tsnew file mode 100644index 000000000..493264320--- /dev/null+++ b/ui/src/components/ui/badge-variants.ts@@ -0,0 +1,27 @@+// The Badge class recipe, kept beside the component rather than inside it: the+// chips that only need the classes (a Link, a native <span> in a table cell)+// import the recipe, and a component module stays exporting only components.+import { cva } from 'class-variance-authority';++export const badgeVariants = cva(+ 'inline-flex items-center gap-1.5 whitespace-nowrap rounded-full px-2.5 py-0.5 text-[11px] font-semibold tracking-wide transition-colors focus:outline-none',+ {+ variants: {+ variant: {+ default: 'border border-border-strong bg-surface text-foreground',+ secondary: 'border border-border bg-surface text-muted',+ outline: 'border border-border-strong bg-transparent text-foreground',+ success: 'border border-mint/40 bg-mint-soft text-mint',+ warning: 'border border-gold/40 bg-gold/10 text-gold',+ info: 'border border-cyan/40 bg-cyan-soft text-cyan',+ destructive: 'border border-destructive/40 bg-destructive/10 text-destructive',+ // Eyebrow — JetBrains Mono cyan w/ glow (design.pen Badge/Eyebrow mtcmf).+ eyebrow:+ 'rounded-full border border-cyan/50 bg-cyan/[0.16] px-3 py-1.5 font-mono text-[11px] font-bold uppercase tracking-[0.14em] text-cyan shadow-[0_0_24px_-4px_rgba(63,224,229,0.33)]',+ },+ },+ defaultVariants: {+ variant: 'default',+ },+ }+);diff --git a/ui/src/components/ui/badge.tsx b/ui/src/components/ui/badge.tsxindex b67621862..e415cebb0 100644--- a/ui/src/components/ui/badge.tsx+++ b/ui/src/components/ui/badge.tsx@@ -1,35 +1,11 @@import * as React from 'react';-import { cva, type VariantProps } from 'class-variance-authority';+import { type VariantProps } from 'class-variance-authority';import { cn } from '@/lib/utils';--const badgeVariants = cva(- 'inline-flex items-center gap-1.5 whitespace-nowrap rounded-full px-2.5 py-0.5 text-[11px] font-semibold tracking-wide transition-colors focus:outline-none',- {- variants: {- variant: {- default: 'border border-border-strong bg-surface text-foreground',- secondary: 'border border-border bg-surface text-muted',- outline: 'border border-border-strong bg-transparent text-foreground',- success: 'border border-mint/40 bg-mint-soft text-mint',- warning: 'border border-gold/40 bg-gold/10 text-gold',- info: 'border border-cyan/40 bg-cyan-soft text-cyan',- destructive: 'border border-destructive/40 bg-destructive/10 text-destructive',- // Eyebrow — JetBrains Mono cyan w/ glow (design.pen Badge/Eyebrow mtcmf).- eyebrow:- 'rounded-full border border-cyan/50 bg-cyan/[0.16] px-3 py-1.5 font-mono text-[11px] font-bold uppercase tracking-[0.14em] text-cyan shadow-[0_0_24px_-4px_rgba(63,224,229,0.33)]',- },- },- defaultVariants: {- variant: 'default',- },- }-);+import { badgeVariants } from './badge-variants';export type BadgeProps = React.HTMLAttributes<HTMLSpanElement> & VariantProps<typeof badgeVariants>;export const Badge = ({ className, variant, ...props }: BadgeProps) => (<span className={cn(badgeVariants({ variant }), className)} {...props} />);--export { badgeVariants };diff --git a/ui/src/components/ui/button-variants.ts b/ui/src/components/ui/button-variants.tsnew file mode 100644index 000000000..f77d6ec17--- /dev/null+++ b/ui/src/components/ui/button-variants.ts@@ -0,0 +1,65 @@+// The Button class recipe, kept beside the component rather than inside it: the+// call sites that need Button's look on a non-button element (an anchor, a Radix+// trigger) import the recipe, and a component module stays exporting only components.+import { cva } from 'class-variance-authority';++export const buttonVariants = cva(+ 'inline-flex items-center justify-center whitespace-nowrap rounded-lg font-medium transition disabled:cursor-not-allowed disabled:opacity-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background [&_svg]:shrink-0',+ {+ variants: {+ variant: {+ // Mint primary — flat, no glow shadow (design.pen Button/Default).+ default: 'gap-1.5 bg-primary text-primary-foreground hover:brightness-110',+ // Brand CTA — bright bg + brand-color glow shadow + bold text + brighten on hover.+ // Foreground tokens flip in light mode (--primary/--accent/--gold-foreground).+ brand:+ 'gap-2 bg-mint font-bold text-primary-foreground shadow-[0_0_24px_-4px_rgba(91,255,160,0.6)] hover:brightness-105 disabled:shadow-none',+ 'brand-cyan':+ 'gap-2 bg-cyan font-bold text-accent-foreground shadow-[0_0_24px_-4px_rgba(63,224,229,0.6)] hover:brightness-105 disabled:shadow-none',+ 'brand-gold':+ 'gap-2 bg-gold font-bold text-gold-foreground shadow-[0_0_24px_-4px_rgba(255,200,87,0.55)] hover:brightness-105 disabled:shadow-none',+ 'brand-violet':+ 'gap-2 bg-violet font-bold text-white shadow-[0_0_24px_-4px_rgba(124,91,255,0.55)] hover:brightness-105 disabled:shadow-none',+ secondary: 'gap-1.5 border border-border bg-secondary text-secondary-foreground hover:border-border-strong',+ // Outline — bg matches page surface so it sits cleanly on glow gradients.+ outline:+ 'gap-1.5 border border-border bg-background text-foreground shadow-[0_1px_2px_rgba(0,0,0,0.05)] hover:bg-surface-2',+ // Cyan outline — for "Read Vibe Remote" / docs style CTAs.+ 'outline-cyan':+ 'gap-1.5 border border-cyan/40 bg-cyan/[0.06] text-cyan hover:bg-cyan/[0.10]',+ ghost: 'gap-1.5 text-foreground hover:bg-surface-2',+ destructive: 'gap-1.5 bg-destructive text-destructive-foreground hover:opacity-90',+ // Pink-soft destructive — design.pen T09T8Z. Pink fill + pink border+ // + pink text/icon, used for in-panel delete CTAs where a full+ // destructive shouts too loud. Drives the --pink / --pink-soft tokens+ // (see index.css); the old bg-[#FF5B8A14] one-off plus an unresolved+ // `pink` token left the border falling back to currentColor (black in+ // light, white in dark) and the fill near-invisible.+ // Fill is pink/15 (not the 10% --pink-soft token) so it carries the+ // same visual weight as the mint-soft "Run" button it usually sits next+ // to — a balanced soft pair rather than a near-invisible wash.+ 'destructive-soft':+ 'gap-1.5 border border-pink/45 bg-pink/15 text-pink hover:border-pink/60 hover:bg-pink/[0.22]',+ link: 'text-primary underline-offset-4 hover:underline',+ accent: 'gap-1.5 border border-cyan/40 bg-cyan-soft text-cyan hover:bg-cyan/15',+ },+ size: {+ // h-8 toolbar buttons (LogsPanel/DoctorPanel/SettingsServicePage/AgentDetection toolbar).+ xs: 'h-8 px-3 text-[12px] [&_svg]:size-3.5',+ // h-9 config-inline CTAs (Slack/Discord/Telegram/...).+ sm: 'h-9 px-4 text-[13px] [&_svg]:size-3.5',+ // h-10 wizard "下一步" — most common.+ default: 'h-10 px-5 text-[13px] [&_svg]:size-3.5',+ // h-12 prominent CTAs (Summary main step CTA).+ lg: 'h-12 px-7 text-[14px] [&_svg]:size-4',+ // Welcome-only hero CTA.+ hero: 'h-[52px] rounded-xl px-8 text-[15px] [&_svg]:size-4',+ icon: 'h-9 w-9',+ },+ },+ defaultVariants: {+ variant: 'default',+ size: 'default',+ },+ }+);diff --git a/ui/src/components/ui/button.tsx b/ui/src/components/ui/button.tsxindex 7e0bebcba..0a293fa6d 100644--- a/ui/src/components/ui/button.tsx+++ b/ui/src/components/ui/button.tsx@@ -1,69 +1,9 @@import * as React from 'react';import { Slot } from '@radix-ui/react-slot';-import { cva, type VariantProps } from 'class-variance-authority';+import { type VariantProps } from 'class-variance-authority';import { cn } from '@/lib/utils';--const buttonVariants = cva(- 'inline-flex items-center justify-center whitespace-nowrap rounded-lg font-medium transition disabled:cursor-not-allowed disabled:opacity-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background [&_svg]:shrink-0',- {- variants: {- variant: {- // Mint primary — flat, no glow shadow (design.pen Button/Default).- default: 'gap-1.5 bg-primary text-primary-foreground hover:brightness-110',- // Brand CTA — bright bg + brand-color glow shadow + bold text + brighten on hover.- // Foreground tokens flip in light mode (--primary/--accent/--gold-foreground).- brand:- 'gap-2 bg-mint font-bold text-primary-foreground shadow-[0_0_24px_-4px_rgba(91,255,160,0.6)] hover:brightness-105 disabled:shadow-none',- 'brand-cyan':- 'gap-2 bg-cyan font-bold text-accent-foreground shadow-[0_0_24px_-4px_rgba(63,224,229,0.6)] hover:brightness-105 disabled:shadow-none',- 'brand-gold':- 'gap-2 bg-gold font-bold text-gold-foreground shadow-[0_0_24px_-4px_rgba(255,200,87,0.55)] hover:brightness-105 disabled:shadow-none',- 'brand-violet':- 'gap-2 bg-violet font-bold text-white shadow-[0_0_24px_-4px_rgba(124,91,255,0.55)] hover:brightness-105 disabled:shadow-none',- secondary: 'gap-1.5 border border-border bg-secondary text-secondary-foreground hover:border-border-strong',- // Outline — bg matches page surface so it sits cleanly on glow gradients.- outline:- 'gap-1.5 border border-border bg-background text-foreground shadow-[0_1px_2px_rgba(0,0,0,0.05)] hover:bg-surface-2',- // Cyan outline — for "Read Vibe Remote" / docs style CTAs.- 'outline-cyan':- 'gap-1.5 border border-cyan/40 bg-cyan/[0.06] text-cyan hover:bg-cyan/[0.10]',- ghost: 'gap-1.5 text-foreground hover:bg-surface-2',- destructive: 'gap-1.5 bg-destructive text-destructive-foreground hover:opacity-90',- // Pink-soft destructive — design.pen T09T8Z. Pink fill + pink border- // + pink text/icon, used for in-panel delete CTAs where a full- // destructive shouts too loud. Drives the --pink / --pink-soft tokens- // (see index.css); the old bg-[#FF5B8A14] one-off plus an unresolved- // `pink` token left the border falling back to currentColor (black in- // light, white in dark) and the fill near-invisible.- // Fill is pink/15 (not the 10% --pink-soft token) so it carries the- // same visual weight as the mint-soft "Run" button it usually sits next- // to — a balanced soft pair rather than a near-invisible wash.- 'destructive-soft':- 'gap-1.5 border border-pink/45 bg-pink/15 text-pink hover:border-pink/60 hover:bg-pink/[0.22]',- link: 'text-primary underline-offset-4 hover:underline',- accent: 'gap-1.5 border border-cyan/40 bg-cyan-soft text-cyan hover:bg-cyan/15',- },- size: {- // h-8 toolbar buttons (LogsPanel/DoctorPanel/SettingsServicePage/AgentDetection toolbar).- xs: 'h-8 px-3 text-[12px] [&_svg]:size-3.5',- // h-9 config-inline CTAs (Slack/Discord/Telegram/...).- sm: 'h-9 px-4 text-[13px] [&_svg]:size-3.5',- // h-10 wizard "下一步" — most common.- default: 'h-10 px-5 text-[13px] [&_svg]:size-3.5',- // h-12 prominent CTAs (Summary main step CTA).- lg: 'h-12 px-7 text-[14px] [&_svg]:size-4',- // Welcome-only hero CTA.- hero: 'h-[52px] rounded-xl px-8 text-[15px] [&_svg]:size-4',- icon: 'h-9 w-9',- },- },- defaultVariants: {- variant: 'default',- size: 'default',- },- }-);+import { buttonVariants } from './button-variants';export type ButtonProps = React.ButtonHTMLAttributes<HTMLButtonElement> &VariantProps<typeof buttonVariants> & { asChild?: boolean };@@ -83,5 +23,3 @@ export const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(});Button.displayName = 'Button';--export { buttonVariants };diff --git a/ui/src/components/ui/chat-image.tsx b/ui/src/components/ui/chat-image.tsxindex 7c7a901f9..9acfec1b3 100644--- a/ui/src/components/ui/chat-image.tsx+++ b/ui/src/components/ui/chat-image.tsx@@ -3,7 +3,7 @@ import { useTranslation } from 'react-i18next';import { Download } from 'lucide-react';import { Button } from '@/components/ui/button';-import { useImageViewer } from '@/components/ui/image-viewer';+import { useImageViewer } from '@/components/ui/image-viewer-context';import { handleMediaDownloadClick, mediaDownloadHref } from '@/lib/downloadMedia';import { cn } from '@/lib/utils';diff --git a/ui/src/components/ui/directory-browser.tsx b/ui/src/components/ui/directory-browser.tsxindex 10a6e1132..aebd7e9e0 100644--- a/ui/src/components/ui/directory-browser.tsx+++ b/ui/src/components/ui/directory-browser.tsx@@ -23,6 +23,7 @@ import { useTranslation } from 'react-i18next';import clsx from 'clsx';import { useApi } from '../../context/ApiContext';+import { errorMessage } from '@/lib/errorMessage';interface DirectoryBrowserProps {/** Initial path to show when opening */@@ -188,9 +189,9 @@ export const DirectoryBrowser: React.FC<DirectoryBrowserProps> = ({}setError(result.error ?? 'Unknown error');return null;- } catch (e: any) {+ } catch (e) {if (!mountedRef.current || reqIdRef.current !== id) return null;- setError(e.message ?? String(e));+ setError(errorMessage(e) ?? String(e));return null;} finally {if (mountedRef.current && reqIdRef.current === id) {@@ -296,8 +297,8 @@ export const DirectoryBrowser: React.FC<DirectoryBrowserProps> = ({setCreating(false);setNewFolderName('');await fetchPath(currentPath);- } catch (err: any) {- const message: string = err?.message ?? String(err);+ } catch (err) {+ const message: string = errorMessage(err) ?? String(err);if (/exists/i.test(message)) {setCreateError(t('directoryBrowser.newFolderExists'));} else {diff --git a/ui/src/components/ui/error-boundary.tsx b/ui/src/components/ui/error-boundary.tsxindex 37defe269..1a56f847f 100644--- a/ui/src/components/ui/error-boundary.tsx+++ b/ui/src/components/ui/error-boundary.tsx@@ -1,9 +1,6 @@import * as React from 'react';-import { useTranslation } from 'react-i18next';-import { AlertTriangle, RotateCcw } from 'lucide-react';-import clsx from 'clsx';-import { Button } from './button';+import { ErrorFallback } from './error-fallback';// A React error boundary: catches a render error in its subtree and shows a recoverable card instead// of letting the throw unmount the whole app (a blank white screen). Wrap independent regions — each@@ -50,7 +47,6 @@ export class ErrorBoundary extends React.Component<Props, State> {componentDidCatch(error: unknown, info: React.ErrorInfo): void {// The boundary swallows the throw so it can never white-screen the app — but the detail must not// be lost, so always surface it to the console (and any wired reporter via onError).- // eslint-disable-next-line no-consoleconsole.error('ErrorBoundary caught a render error:', error, info.componentStack);this.props.onError?.(error, info);}@@ -71,34 +67,3 @@ export class ErrorBoundary extends React.Component<Props, State> {return this.props.children;}}--// Kept dependency-light on purpose: this renders precisely when something else just threw, so it must-// not itself rely on app data that might be the cause. i18n `t` returns the key if missing (no throw).-const ErrorFallback: React.FC<{ error: unknown; reset: () => void; variant: 'page' | 'inline' }> = ({ error, reset, variant }) => {- const { t } = useTranslation();- const detail = error instanceof Error ? error.message : typeof error === 'string' ? error : '';- return (- <div className={clsx('grid h-full w-full place-items-center bg-surface p-6 text-center', variant === 'page' && 'min-h-[60vh]')}>- <div className="flex max-w-sm flex-col items-center gap-3">- <span className="grid size-12 shrink-0 place-items-center rounded-2xl border border-gold/40 bg-gold/[0.08]">- <AlertTriangle className="size-6 text-gold" />- </span>- <div className="text-[15px] font-semibold text-foreground">{t('errorBoundary.title')}</div>- <div className="text-[12.5px] text-muted">{t('errorBoundary.body')}</div>- {detail && (- <div className="max-w-full truncate rounded bg-surface-3 px-2 py-1 font-mono text-[11px] text-muted" title={detail}>- {detail}- </div>- )}- <div className="mt-1 flex items-center gap-2">- <Button type="button" size="sm" variant="brand" className="gap-1.5" onClick={reset}>- <RotateCcw className="size-3.5" /> {t('errorBoundary.retry')}- </Button>- <Button type="button" size="sm" variant="outline" onClick={() => window.location.reload()}>- {t('errorBoundary.reload')}- </Button>- </div>- </div>- </div>- );-};diff --git a/ui/src/components/ui/error-fallback.tsx b/ui/src/components/ui/error-fallback.tsxnew file mode 100644index 000000000..59d5e1318--- /dev/null+++ b/ui/src/components/ui/error-fallback.tsx@@ -0,0 +1,36 @@+import { useTranslation } from 'react-i18next';+import { AlertTriangle, RotateCcw } from 'lucide-react';+import clsx from 'clsx';++import { Button } from './button';++// Kept dependency-light on purpose: this renders precisely when something else just threw, so it must+// not itself rely on app data that might be the cause. i18n `t` returns the key if missing (no throw).+export const ErrorFallback: React.FC<{ error: unknown; reset: () => void; variant: 'page' | 'inline' }> = ({ error, reset, variant }) => {+ const { t } = useTranslation();+ const detail = error instanceof Error ? error.message : typeof error === 'string' ? error : '';+ return (+ <div className={clsx('grid h-full w-full place-items-center bg-surface p-6 text-center', variant === 'page' && 'min-h-[60vh]')}>+ <div className="flex max-w-sm flex-col items-center gap-3">+ <span className="grid size-12 shrink-0 place-items-center rounded-2xl border border-gold/40 bg-gold/[0.08]">+ <AlertTriangle className="size-6 text-gold" />+ </span>+ <div className="text-[15px] font-semibold text-foreground">{t('errorBoundary.title')}</div>+ <div className="text-[12.5px] text-muted">{t('errorBoundary.body')}</div>+ {detail && (+ <div className="max-w-full truncate rounded bg-surface-3 px-2 py-1 font-mono text-[11px] text-muted" title={detail}>+ {detail}+ </div>+ )}+ <div className="mt-1 flex items-center gap-2">+ <Button type="button" size="sm" variant="brand" className="gap-1.5" onClick={reset}>+ <RotateCcw className="size-3.5" /> {t('errorBoundary.retry')}+ </Button>+ <Button type="button" size="sm" variant="outline" onClick={() => window.location.reload()}>+ {t('errorBoundary.reload')}+ </Button>+ </div>+ </div>+ </div>+ );+};diff --git a/ui/src/components/ui/file-card.tsx b/ui/src/components/ui/file-card.tsxindex 5468aa1ab..58a7d5edb 100644--- a/ui/src/components/ui/file-card.tsx+++ b/ui/src/components/ui/file-card.tsx@@ -7,7 +7,7 @@ import { Button } from '@/components/ui/button';import { apiFetch } from '@/lib/apiFetch';import { isProxyMediaUrl } from '@/lib/mediaProxy';import { handleMediaDownloadClick, mediaDownloadHref } from '@/lib/downloadMedia';-import { useFileViewer } from '@/components/ui/file-viewer';+import { useFileViewer } from '@/components/ui/file-viewer-context';import { previewRenderKind, formatBytes } from '@/lib/filePreview';import { cn } from '@/lib/utils';diff --git a/ui/src/components/ui/file-preview.tsx b/ui/src/components/ui/file-preview.tsxindex a191e6f1a..27fa8842f 100644--- a/ui/src/components/ui/file-preview.tsx+++ b/ui/src/components/ui/file-preview.tsx@@ -19,6 +19,7 @@ import {previewRenderKind,} from '@/lib/filePreview';import { FIT_VIEW, type ImageView, clampPan, maxScale, oneToOneScale, toggleScale, zoomPercent, zoomToPoint } from '@/lib/imageZoom';+import { useLatestRef } from '@/lib/useLatestRef';// ── Shared file-preview kernel ("Quick Look") ───────────────────────────────// One read-only renderer for every previewable file, reused by the File Browser overlay, the editor's@@ -638,8 +639,7 @@ type TextKind = 'svg' | 'html' | 'markdown' | 'json' | 'csv' | 'code';const TextPreview: React.FC<{ source: PreviewSource; kind: TextKind; onText?: (text: string) => void; className?: string }> = ({ source, kind, onText, className }) => {const { t } = useTranslation();- const onTextRef = React.useRef(onText);- onTextRef.current = onText;+ const onTextRef = useLatestRef(onText);const [state, setState] = React.useState<{ phase: 'loading' | 'ready' | 'error' | 'toolarge'; text: string }>(() =>source.text != null ? { phase: 'ready', text: source.text } : { phase: 'loading', text: '' },);diff --git a/ui/src/components/ui/file-viewer-context.ts b/ui/src/components/ui/file-viewer-context.tsnew file mode 100644index 000000000..e1080d7ce--- /dev/null+++ b/ui/src/components/ui/file-viewer-context.ts@@ -0,0 +1,25 @@+import * as React from 'react';++// The file-preview handle, split from the provider so a FileCard can ask for a+// preview without importing the provider (and the lazy modal) it lives under.+// ``useFileViewer()`` returns null where no provider is mounted, which is the+// documented fallback signal, not an error.++export type FilePreviewTarget =+ | { kind?: 'media'; url: string; name?: string }+ | {+ kind: 'local';+ path: string;+ name: string;+ size: number | null;+ mime: string | null;+ ext: string | null;+ };++type FileViewerContextValue = { open: (target: FilePreviewTarget) => void };++export const FileViewerContext = React.createContext<FileViewerContextValue | null>(null);++export function useFileViewer(): FileViewerContextValue | null {+ return React.useContext(FileViewerContext);+}diff --git a/ui/src/components/ui/file-viewer-modal.tsx b/ui/src/components/ui/file-viewer-modal.tsxindex 21e3df4c0..27241b4be 100644--- a/ui/src/components/ui/file-viewer-modal.tsx+++ b/ui/src/components/ui/file-viewer-modal.tsx@@ -11,7 +11,7 @@ import { contentUrl, downloadFile } from '@/lib/filesApi';import { isProxyMediaUrl } from '@/lib/mediaProxy';import { formatBytes } from '@/lib/filePreview';import { copyTextToClipboard } from '@/lib/utils';-import type { FilePreviewTarget } from '@/components/ui/file-viewer';+import type { FilePreviewTarget } from '@/components/ui/file-viewer-context';// The chat file viewer: a Dialog shell (header + copy/download) around the shared <FilePreview>// kernel, which owns every renderer (Shiki, the JSON tree, papaparse, the Office parsers, images, PDF,diff --git a/ui/src/components/ui/file-viewer.tsx b/ui/src/components/ui/file-viewer.tsxindex bd21cfe6e..e7f60db09 100644--- a/ui/src/components/ui/file-viewer.tsx+++ b/ui/src/components/ui/file-viewer.tsx@@ -1,5 +1,7 @@import * as React from 'react';+import { FileViewerContext, type FilePreviewTarget } from './file-viewer-context';+// Session-scoped in-app file preview. ChatPage mounts the provider; a FileCard// with a previewable proxy file or a classified local rich file opens the modal. The// heavy modal (Shiki, the JSON viewer, the CSV parser) is ``React.lazy``-loaded,@@ -8,25 +10,6 @@ import * as React from 'react';// structurally consistent; FileCard falls back to a plain link where no// provider is mounted (``useFileViewer()`` returns null).-export type FilePreviewTarget =- | { kind?: 'media'; url: string; name?: string }- | {- kind: 'local';- path: string;- name: string;- size: number | null;- mime: string | null;- ext: string | null;- };--type FileViewerContextValue = { open: (target: FilePreviewTarget) => void };--const FileViewerContext = React.createContext<FileViewerContextValue | null>(null);--export function useFileViewer(): FileViewerContextValue | null {- return React.useContext(FileViewerContext);-}-const FileViewerModal = React.lazy(() => import('@/components/ui/file-viewer-modal'));export const FileViewerProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {diff --git a/ui/src/components/ui/image-viewer-context.ts b/ui/src/components/ui/image-viewer-context.tsnew file mode 100644index 000000000..c24fdbbc4--- /dev/null+++ b/ui/src/components/ui/image-viewer-context.ts@@ -0,0 +1,14 @@+import * as React from 'react';++// The lightbox handle, split from the provider so the shared Markdown renderer+// and chat images can ask to open one without importing the lightbox itself.+// ``useImageViewer()`` returns null where no provider is mounted (e.g. the+// agent-config editor preview), which makes the click a documented no-op.++type ImageViewerContextValue = { open: (src: string) => void };++export const ImageViewerContext = React.createContext<ImageViewerContextValue | null>(null);++export function useImageViewer(): ImageViewerContextValue | null {+ return React.useContext(ImageViewerContext);+}diff --git a/ui/src/components/ui/image-viewer.tsx b/ui/src/components/ui/image-viewer.tsxindex 681e2338c..db56dd0a3 100644--- a/ui/src/components/ui/image-viewer.tsx+++ b/ui/src/components/ui/image-viewer.tsx@@ -5,6 +5,7 @@ import { TransformWrapper, TransformComponent, type ReactZoomPanPinchRef } fromimport { Button } from '@/components/ui/button';import { handleMediaDownloadClick, mediaDownloadHref } from '@/lib/downloadMedia';+import { ImageViewerContext } from './image-viewer-context';// A session-scoped image lightbox. ChatPage computes the ordered list of media-// proxy image URLs in the transcript and wraps the page in a provider; any chat@@ -13,14 +14,6 @@ import { handleMediaDownloadClick, mediaDownloadHref } from '@/lib/downloadMedia// through the optional context so the shared Markdown renderer keeps working// (no-op) where there's no provider (e.g. the agent-config editor preview).-type ImageViewerContextValue = { open: (src: string) => void };--const ImageViewerContext = React.createContext<ImageViewerContextValue | null>(null);--export function useImageViewer(): ImageViewerContextValue | null {- return React.useContext(ImageViewerContext);-}-// Overlay controls sit on a dark backdrop, so the shared Button's themed// foreground/hover (tuned for app surfaces) would be invisible here — override// to white-on-translucent while still inheriting Button's sizing/focus/disableddiff --git a/ui/src/components/ui/secret-request-card.tsx b/ui/src/components/ui/secret-request-card.tsxindex 2790ab458..488f5ccbe 100644--- a/ui/src/components/ui/secret-request-card.tsx+++ b/ui/src/components/ui/secret-request-card.tsx@@ -1,7 +1,7 @@import { useEffect, useState } from 'react';import { CheckCircle2, KeyRound, Loader2 } from 'lucide-react';import { useTranslation } from 'react-i18next';-import { badgeVariants } from './badge';+import { badgeVariants } from './badge-variants';import { VaultSecretDialog } from './vault-secret-dialog';import { useApi, type VaultRequest } from '@/context/ApiContext';import { cn } from '@/lib/utils';diff --git a/ui/src/components/ui/vault-approval-card.tsx b/ui/src/components/ui/vault-approval-card.tsxindex c3f705cf2..f7626b1ae 100644--- a/ui/src/components/ui/vault-approval-card.tsx+++ b/ui/src/components/ui/vault-approval-card.tsx@@ -19,7 +19,8 @@ import { Badge } from './badge';import { Button } from './button';import { SegmentedRadio } from './segmented';import { Switch } from './switch';-import { VaultRequestSessionLink, vaultRequestSessionDisplay } from './vault-request-session-link';+import { vaultRequestSessionDisplay } from './vault-request-session';+import { VaultRequestSessionLink } from './vault-request-session-link';/** The three approver-chosen grant-duration options (protocol v2 §7.1), as SegmentedRadio ids. */type GrantDurationChoice = 'one-time' | '300' | '900';diff --git a/ui/src/components/ui/vault-chat-requests.tsx b/ui/src/components/ui/vault-chat-requests.tsxindex d96ad98a4..6673ebe76 100644--- a/ui/src/components/ui/vault-chat-requests.tsx+++ b/ui/src/components/ui/vault-chat-requests.tsx@@ -4,7 +4,7 @@ import { useTranslation } from 'react-i18next';import { cn } from '@/lib/utils';import type { VaultRequest } from '@/context/ApiContext';-import { buttonVariants } from './button';+import { buttonVariants } from './button-variants';import { VaultApprovalDialog } from './vault-approval-dialog';import { VaultRequestCard } from './vault-request-card';diff --git a/ui/src/components/ui/vault-request-session-link.tsx b/ui/src/components/ui/vault-request-session-link.tsxindex 92e6d08df..7912bd694 100644--- a/ui/src/components/ui/vault-request-session-link.tsx+++ b/ui/src/components/ui/vault-request-session-link.tsx@@ -1,31 +1,7 @@import { Link } from 'react-router-dom';-import type { VaultRequest } from '@/context/ApiContext';import { cn } from '@/lib/utils';--export type VaultRequestSessionDisplay = {- id: string;- label: string;- isWorkbench: boolean;- isIdFallback: boolean;-};--export function vaultRequestSessionDisplay(request: VaultRequest): VaultRequestSessionDisplay | null {- const card = (request.card ?? {}) as { session_id?: unknown };- const cardSessionId = typeof card.session_id === 'string' && card.session_id.trim() ? card.session_id.trim() : null;- const session = request.session ?? null;- const id = session?.id?.trim() || cardSessionId;- if (!id) return null;- const title = session?.title?.trim();- const sessionLabel = session?.label?.trim();- const label = title || sessionLabel || id;- return {- id,- label,- isWorkbench: Boolean(session?.is_workbench),- isIdFallback: label === id && !title && (!sessionLabel || sessionLabel === id),- };-}+import type { VaultRequestSessionDisplay } from './vault-request-session';export const VaultRequestSessionLink: React.FC<{session: VaultRequestSessionDisplay;diff --git a/ui/src/components/ui/vault-request-session.ts b/ui/src/components/ui/vault-request-session.tsnew file mode 100644index 000000000..7afe92ac0--- /dev/null+++ b/ui/src/components/ui/vault-request-session.ts@@ -0,0 +1,28 @@+// How a vault request names the session that asked for it. Pure projection of the+// request payload — the card and the Vaults page render the same answer, and+// `vault-request-session-link.tsx` only decides how to link it.+import type { VaultRequest } from '@/context/ApiContext';++export type VaultRequestSessionDisplay = {+ id: string;+ label: string;+ isWorkbench: boolean;+ isIdFallback: boolean;+};++export function vaultRequestSessionDisplay(request: VaultRequest): VaultRequestSessionDisplay | null {+ const card = (request.card ?? {}) as { session_id?: unknown };+ const cardSessionId = typeof card.session_id === 'string' && card.session_id.trim() ? card.session_id.trim() : null;+ const session = request.session ?? null;+ const id = session?.id?.trim() || cardSessionId;+ if (!id) return null;+ const title = session?.title?.trim();+ const sessionLabel = session?.label?.trim();+ const label = title || sessionLabel || id;+ return {+ id,+ label,+ isWorkbench: Boolean(session?.is_workbench),+ isIdFallback: label === id && !title && (!sessionLabel || sessionLabel === id),+ };+}diff --git a/ui/src/components/workbench/AgentsPage.tsx b/ui/src/components/workbench/AgentsPage.tsxindex b03d1d3e8..4253a5c77 100644--- a/ui/src/components/workbench/AgentsPage.tsx+++ b/ui/src/components/workbench/AgentsPage.tsx@@ -49,6 +49,7 @@ import {BACKEND_TEXT as BACKEND_ICON_CLASS,type Backend,} from '../../lib/backendAccent';+import { errorMessage } from '@/lib/errorMessage';type AgentsTabKey = 'definitions' | 'running';const AGENTS_TAB_ORDER: AgentsTabKey[] = ['definitions', 'running'];@@ -90,8 +91,8 @@ export const AgentsPage: React.FC = () => {const fresh = result.agents.find((a) => a.name === selected.name);if (!fresh) setSelected(null);}- } catch (err: any) {- setError(err?.message ?? String(err));+ } catch (err) {+ setError(errorMessage(err) ?? String(err));} finally {setLoading(false);}@@ -224,8 +225,8 @@ export const AgentsPage: React.FC = () => {// never optimistically, or a failed fetch hides the list with no panel.if (openDetail) setDetailOpen(true);}- } catch (err: any) {- setError(err?.message ?? String(err));+ } catch (err) {+ setError(errorMessage(err) ?? String(err));}},[api],@@ -268,8 +269,8 @@ export const AgentsPage: React.FC = () => {setSelected(result.agent);refresh();}- } catch (err: any) {- setError(err?.message ?? String(err));+ } catch (err) {+ setError(errorMessage(err) ?? String(err));}};@@ -301,8 +302,8 @@ export const AgentsPage: React.FC = () => {} else if (result.message) {setError(result.message);}- } catch (err: any) {- setError(err?.message ?? String(err));+ } catch (err) {+ setError(errorMessage(err) ?? String(err));}};@@ -330,8 +331,8 @@ export const AgentsPage: React.FC = () => {'error',);}- } catch (err: any) {- showToast(t('agents.importFailed', { error: err?.message ?? String(err) }), 'error');+ } catch (err) {+ showToast(t('agents.importFailed', { error: errorMessage(err) ?? String(err) }), 'error');} finally {setImporting(null);}@@ -740,8 +741,8 @@ const AgentDetailPanel: React.FC<DetailProps> = ({ agent, isDefault, onChange, oawait api.updateVibeAgent(agent.name, { name: trimmed });showToast(t('agents.renameSuccess'), 'success');onRenamed(trimmed);- } catch (err: any) {- showToast(err?.message ?? String(err), 'error');+ } catch (err) {+ showToast(errorMessage(err) ?? String(err), 'error');setName(agent.name);} finally {setRenaming(false);@@ -754,8 +755,8 @@ const AgentDetailPanel: React.FC<DetailProps> = ({ agent, isDefault, onChange, otry {await onSetDefault();showToast(t('agents.detail.defaultSet', { name: agent.name }), 'success');- } catch (err: any) {- showToast(err?.message ?? String(err), 'error');+ } catch (err) {+ showToast(errorMessage(err) ?? String(err), 'error');} finally {setSettingDefault(false);}diff --git a/ui/src/components/workbench/ChatArchivedReadOnly.test.tsx b/ui/src/components/workbench/ChatArchivedReadOnly.test.tsxindex 5a9e25672..f91258e8d 100644--- a/ui/src/components/workbench/ChatArchivedReadOnly.test.tsx+++ b/ui/src/components/workbench/ChatArchivedReadOnly.test.tsx@@ -7,11 +7,12 @@ import { describe, expect, it } from 'vitest';import en from '../../i18n/en.json';import zh from '../../i18n/zh.json';-import { selectApiErrorFields } from '../../context/ApiContext';+import { selectApiErrorFields } from '../../context/apiErrorParse';import type { VaultRequest, VibeAgentBrief, WorkbenchMessage, WorkbenchSession } from '../../context/ApiContext';-import { ToastProvider } from '../../context/ToastContext';+import { ToastProvider } from '../../context/ToastProvider';import { isVoiceControlDisabled } from '../../lib/voiceRecording';-import { ChatHeaderBar, MessageRow, ThinkingBubble, sessionAgentDisplayName } from './ChatPage';+import { ChatHeaderBar, MessageRow, ThinkingBubble } from './ChatPage';+import { sessionAgentDisplayName } from './sessionAgentName';import { Composer } from './Composer';import { QuickReplies } from './QuickReplies';import {diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsxindex 97b924106..82dcdcf23 100644--- a/ui/src/components/workbench/ChatPage.tsx+++ b/ui/src/components/workbench/ChatPage.tsx@@ -5,7 +5,8 @@ import { Activity, ArrowLeft, ArrowRight, ArrowUpRight, Bell, Bot, ChevronDown,import type { LucideIcon } from 'lucide-react';import clsx from 'clsx';-import { selectApiErrorFields, useApi } from '../../context/ApiContext';+import { useApi } from '../../context/ApiContext';+import { selectApiErrorFields } from '../../context/apiErrorParse';import { useToast } from '../../context/ToastContext';import { useWorkbenchInbox } from '../../context/WorkbenchInboxContext';import { useRegisterComposerTarget, type ComposerInsertTarget } from '../../context/ComposerBridgeContext';@@ -66,7 +67,8 @@ import { Button } from '../ui/button';import { ChatImage } from '../ui/chat-image';import { FileCard } from '../ui/file-card';import { ImageViewerProvider } from '../ui/image-viewer';-import { FileViewerProvider, useFileViewer } from '../ui/file-viewer';+import { FileViewerProvider } from '../ui/file-viewer';+import { useFileViewer } from '../ui/file-viewer-context';import { Input } from '../ui/input';import { Markdown } from '../ui/markdown';import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover';@@ -92,6 +94,9 @@ import {type LiveActivityState,type TurnActivityGroupWire,} from '../../lib/agentActivity';+import { errorMessage } from '@/lib/errorMessage';+import { useLatestRef } from '@/lib/useLatestRef';+import { sessionAgentDisplayName } from './sessionAgentName';// While a turn is in flight, reconcile the working/Stop state against the// controller on this cadence (the backend ``GET /turn-state`` is authoritative).@@ -101,18 +106,6 @@ import {// ``in_flight:true``; only an idle reading (past the post-send grace) clears it.const WORKING_RECONCILE_INTERVAL_MS = 60 * 1000;-export function sessionAgentDisplayName(- session: Pick<WorkbenchSession, 'agent_id' | 'agent_name'>,- agents: VibeAgentBrief[],-): string | null {- const agentName = session.agent_name?.trim() || null;- if (!agentName) return null;- const agent =- (session.agent_id ? agents.find((candidate) => candidate.id === session.agent_id) : undefined) ??- agents.find((candidate) => candidate.name === agentName);- return agent?.display_name?.trim() || agentName;-}-// Grace window after we optimistically set ``working`` from a local send before// an idle ``/turn-state`` reading is trusted to CLEAR it. A just-sent turn isn't// registered in the controller's in-flight map until POST→dispatch_async lands,@@ -1028,10 +1021,10 @@ export const ChatPage: React.FC = () => {// for the fresh page, so clear directly (Codex P2).if (bootstrap.turn_state.foreground === 'running') markWorking();else if (bootstrap.turn_state.foreground === 'idle') setWorking(false);- } catch (err: any) {+ } catch (err) {// Only surface the error if we're still on the session that failed — a// stale failure must not stamp an error onto the chat the user moved to.- if (sessionId === sessionIdRef.current) setError(err?.message ?? String(err));+ if (sessionId === sessionIdRef.current) setError(errorMessage(err) ?? String(err));} finally {// Same guard: a stale load finishing must not flip the new session out of// its own loading state into a premature not-found / error view (Codex P2).@@ -1413,10 +1406,10 @@ export const ChatPage: React.FC = () => {appendMessage(body as WorkbenchMessage);}}- } catch (err: any) {+ } catch (err) {if (sessionId === sessionIdRef.current) {setWorking(false);- setError(err?.message ?? String(err));+ setError(errorMessage(err) ?? String(err));// Signal the composer the send didn't start so it restores the text +// uploaded chips — the user can retry without re-uploading (Codex r5).return false;@@ -1595,9 +1588,9 @@ export const ChatPage: React.FC = () => {setError(res.detail ? String(res.detail) : t('chat.stopFailed'));}}- } catch (err: any) {+ } catch (err) {// The cancel request itself threw (network) — surface it; keep Stop.- if (sessionId === sessionIdRef.current) setError(err?.message ?? String(err));+ if (sessionId === sessionIdRef.current) setError(errorMessage(err) ?? String(err));}}, [api, sessionId, working, t, syncTurnState]);@@ -1668,12 +1661,12 @@ export const ChatPage: React.FC = () => {setWorking(false);void refreshQueue();}- } catch (err: any) {+ } catch (err) {// Same session guard as the success path: a rejection after a chat switch// must not clear the new chat's working / stamp this error on it (Codex P2).if (sessionId === sessionIdRef.current) {setWorking(false);- setError(err?.message ?? String(err));+ setError(errorMessage(err) ?? String(err));}}}, [api, sessionId, queue, t, refreshQueue, markWorking]);@@ -1851,7 +1844,7 @@ export const ChatPage: React.FC = () => {// the sessionIdRef guards on send/cancel.if (patchedId !== sessionIdRef.current) return;setSession(updated);- } catch (err: any) {+ } catch (err) {if (patchedId !== sessionIdRef.current) return;// The archive itself has already converged through the shared// ``onSessionArchived`` subscription (the title editor and route picker are@@ -1859,7 +1852,7 @@ export const ChatPage: React.FC = () => {// wording is per-verb: the global ``errors.session_archived`` copy that// ``handleApiError`` resolved is Show-Page-worded, which is wrong for a// rename or a re-route.- setError(isSessionArchivedError(err) ? t('chat.archived.editBlocked') : (err?.message ?? String(err)));+ setError(isSessionArchivedError(err) ? t('chat.archived.editBlocked') : (errorMessage(err) ?? String(err)));}},[api, session, t],@@ -3017,8 +3010,7 @@ const Transcript: React.FC<TranscriptProps> = ({const settleTimerRef = useRef<number | null>(null);// Mirror loadingOlder so the settle timer (which closes over a stale value)// can avoid re-arming while a page load is still in flight.- const loadingOlderPropRef = useRef(loadingOlder);- loadingOlderPropRef.current = loadingOlder;+ const loadingOlderPropRef = useLatestRef(loadingOlder);// A failed load adds no content → no anchor restore → the viewport stays at the// top, where the position gate below would never re-arm. Mark it so the settle// re-arms regardless of position and a later scroll can retry. Re-arming atdiff --git a/ui/src/components/workbench/CreateViaChatDialog.tsx b/ui/src/components/workbench/CreateViaChatDialog.tsxindex d036629cf..f859dc62e 100644--- a/ui/src/components/workbench/CreateViaChatDialog.tsx+++ b/ui/src/components/workbench/CreateViaChatDialog.tsx@@ -7,6 +7,7 @@ import { useApi } from '../../context/ApiContext';import type { WorkbenchProject } from '../../context/ApiContext';import { Button } from '../ui/button';import { Select } from '../ui/select';+import { errorMessage } from '@/lib/errorMessage';export type CreateViaChatKind = 'task' | 'watch';@@ -81,8 +82,8 @@ export const CreateViaChatDialog: React.FC<CreateViaChatDialogProps> = ({ kind,navigate(`/chat/${encodeURIComponent(session.id)}`, {state: { initialMessage: prompt },});- } catch (err: any) {- setError(err?.message ?? String(err));+ } catch (err) {+ setError(errorMessage(err) ?? String(err));setSubmitting(false);}};diff --git a/ui/src/components/workbench/HarnessPage.test.tsx b/ui/src/components/workbench/HarnessPage.test.tsxindex f27985729..cdde9e4d8 100644--- a/ui/src/components/workbench/HarnessPage.test.tsx+++ b/ui/src/components/workbench/HarnessPage.test.tsx@@ -19,11 +19,9 @@ import {RunDetail,RunTriggerChip,WatchDetail,- agentDisplayName,- harnessEmptyStateKey,- harnessTabFromParam,} from './HarnessPage';-import { loadHarnessAgentCatalog } from './harnessAgents';+import { agentDisplayName, loadHarnessAgentCatalog } from './harnessAgents';+import { harnessEmptyStateKey, harnessTabFromParam } from './harnessTabs';import { RUN_TYPES, harnessSessionState, runRowTitle, runStatusLabel, runTypeLabel, runTypeOptions } from './harnessRuns';const i18n = createInstance();diff --git a/ui/src/components/workbench/HarnessPage.tsx b/ui/src/components/workbench/HarnessPage.tsxindex bb4a66943..ce514321c 100644--- a/ui/src/components/workbench/HarnessPage.tsx+++ b/ui/src/components/workbench/HarnessPage.tsx@@ -29,6 +29,7 @@ import clsx from 'clsx';import { Link, useSearchParams } from 'react-router-dom';import { useApi } from '../../context/ApiContext';+import { DEFAULT_TAB, harnessEmptyStateKey, harnessTabFromParam, TAB_ORDER, type TabKey } from './harnessTabs';import type {HarnessDefinitionCounts,HarnessDefinitionStatus,@@ -79,10 +80,11 @@ import type {HarnessLifecycleState,HarnessRowAlert,} from './harnessLifecycle';-import { loadHarnessAgentCatalog } from './harnessAgents';+import { agentDisplayName, loadHarnessAgentCatalog } from './harnessAgents';import { Badge } from '../ui/badge';import { Button } from '../ui/button';import { Switch } from '../ui/switch';+import { errorMessage } from '@/lib/errorMessage';// Detail-panel schedule, in words. The literal it was derived from is printed// beside it by the caller — humanizing must never be the only copy of a value@@ -102,8 +104,6 @@ function formatSchedule(task: HarnessTask, t: (k: string, opts?: any) => string)return task.schedule_type || t('harness.unknownSchedule');}-type TabKey = 'tasks' | 'watches' | 'runs';-// Status segments per tab. Definitions filter by what they are doing; runs by// execution outcome. One control renders whichever set the tab needs.const RUN_STATUS_FILTERS = ['all', 'queued', 'running', 'succeeded', 'failed', 'canceled'] as const;@@ -116,27 +116,6 @@ const RUN_STATUS_FILTERS = ['all', 'queued', 'running', 'succeeded', 'failed', '// built-in name for, and those are just as selectable.type RunTypeFilter = string;-const TAB_ORDER: TabKey[] = ['tasks', 'watches', 'runs'];-const DEFAULT_TAB: TabKey = 'tasks';--// Which tab a ``?tab=`` param opens. Anything that is not a tab opens the-// default rather than selecting nothing — ``?tab=webhooks`` still arrives from-// links and bookmarks made before the Webhooks tab was removed, and must land-// on Tasks, not on an empty page with no tab lit.-//-// One function rather than a guard here and a ``useState`` initializer three-// hundred lines away, so removing a tab later cannot strand its old links.-export function harnessTabFromParam(param: string | null | undefined): TabKey {- return (TAB_ORDER as string[]).includes(param ?? '') ? (param as TabKey) : DEFAULT_TAB;-}--export function harnessEmptyStateKey(kind: TabKey, hasStoredRows: boolean): string {- if (!hasStoredRows) {- return kind === 'tasks' ? 'harness.emptyTasks' : kind === 'watches' ? 'harness.emptyWatches' : 'harness.emptyRuns';- }- return kind === 'tasks' ? 'harness.noTaskMatches' : kind === 'watches' ? 'harness.noWatchMatches' : 'harness.noRunMatches';-}-const PAGE_LIMIT = 30;const EMPTY_DEFINITION_COUNTS: HarnessDefinitionCounts = {total: 0,@@ -365,9 +344,9 @@ export const HarnessPage: React.FC = () => {setRunsHasMore(page.has_more);if (page.run_types) setPresentRunTypes(page.run_types);}- } catch (err: any) {+ } catch (err) {if (!isCurrent()) return;- setError(err?.message ?? String(err));+ setError(errorMessage(err) ?? String(err));} finally {if (isCurrent()) setLoading(false);}@@ -436,8 +415,8 @@ export const HarnessPage: React.FC = () => {setSelection((prev) => (prev?.kind === 'task' && prev.id === task.id ? null : prev));}await refresh();- } catch (err: any) {- setError(err?.message ?? String(err));+ } catch (err) {+ setError(errorMessage(err) ?? String(err));setTasks((prev) => prev.map((t) => (t.id === task.id ? { ...t, enabled: task.enabled } : t)));} finally {markPending(task.id, false);@@ -458,8 +437,8 @@ export const HarnessPage: React.FC = () => {setSelection((prev) => (prev?.kind === 'task' && prev.id === task.id ? null : prev));if (tasks.length === 1 && tasksPage > 1) setTasksPage((page) => Math.max(1, page - 1));else await refresh();- } catch (err: any) {- setError(err?.message ?? String(err));+ } catch (err) {+ setError(errorMessage(err) ?? String(err));} finally {markPending(task.id, false);}@@ -478,8 +457,8 @@ export const HarnessPage: React.FC = () => {setSelection((prev) => (prev?.kind === 'watch' && prev.id === watch.id ? null : prev));}await refresh();- } catch (err: any) {- setError(err?.message ?? String(err));+ } catch (err) {+ setError(errorMessage(err) ?? String(err));setWatches((prev) => prev.map((w) => (w.id === watch.id ? { ...w, enabled: watch.enabled } : w)));} finally {markPending(watch.id, false);@@ -500,8 +479,8 @@ export const HarnessPage: React.FC = () => {setSelection((prev) => (prev?.kind === 'watch' && prev.id === watch.id ? null : prev));if (watches.length === 1 && watchesPage > 1) setWatchesPage((page) => Math.max(1, page - 1));else await refresh();- } catch (err: any) {- setError(err?.message ?? String(err));+ } catch (err) {+ setError(errorMessage(err) ?? String(err));} finally {markPending(watch.id, false);}@@ -1569,13 +1548,6 @@ interface RunDetailProps {agent?: VibeAgentBrief;}-export function agentDisplayName(- agentName: string | null | undefined,- agent?: Pick<VibeAgentBrief, 'display_name'>,-): string {- return agent?.display_name || agentName || '—';-}-export const RunDetail: React.FC<RunDetailProps> = ({ run, agent }) => {const { t } = useTranslation();const typeLabel = runTypeLabel(run.run_type || run.request_type, t);diff --git a/ui/src/components/workbench/MentionEditor.tsx b/ui/src/components/workbench/MentionEditor.tsxindex 82f357095..fba65053a 100644--- a/ui/src/components/workbench/MentionEditor.tsx+++ b/ui/src/components/workbench/MentionEditor.tsx@@ -4,6 +4,7 @@ import {useEffect,useImperativeHandle,useRef,+ useState,type Ref,} from 'react';import { LexicalComposer } from '@lexical/react/LexicalComposer';@@ -51,6 +52,7 @@ import {voiceInsertionText,type VoiceInsertionSnapshot,} from '../../lib/voiceCleanup';+import { useLatestRef } from '@/lib/useLatestRef';export type AgentSearchResult = {name: string;@@ -398,8 +400,7 @@ function EditablePlugin({ disabled }: { disabled: boolean }) {// command registers once per editor and never churns on the composer's renders.function PasteFilesPlugin({ onPasteFiles }: { onPasteFiles?: (files: File[]) => void }) {const [editor] = useLexicalComposerContext();- const handlerRef = useRef(onPasteFiles);- handlerRef.current = onPasteFiles;+ const handlerRef = useLatestRef(onPasteFiles);useEffect(() =>editor.registerCommand(@@ -725,7 +726,12 @@ export const MentionEditor = forwardRef<MentionEditorHandle, MentionEditorProps>[onSearchAgents, onSearchSessions],);- const initialConfig = useRef({+ // Lexical reads `initialConfig` once, at mount; a fresh object on later+ // renders would be ignored anyway. A lazy `useState` initializer is the+ // render-safe way to spell "compute once per instance" — `useRef({…}).current`+ // rebuilt the object on every render only to throw it away, and reading+ // `.current` during render is what `react-hooks/refs` warns about.+ const [initialConfig] = useState(() => ({namespace: 'avibe-mention-composer',theme: { beautifulMentions: MENTION_THEME },nodes: [BeautifulMentionNode],@@ -734,7 +740,7 @@ export const MentionEditor = forwardRef<MentionEditorHandle, MentionEditorProps>// Surface in dev; never throw out of the editor and wipe the box.console.error('[MentionEditor]', error);},- }).current;+ }));return (<div className={cn('relative', className)}>diff --git a/ui/src/components/workbench/NewAgentDialog.tsx b/ui/src/components/workbench/NewAgentDialog.tsxindex b79a48d07..2231339a8 100644--- a/ui/src/components/workbench/NewAgentDialog.tsx+++ b/ui/src/components/workbench/NewAgentDialog.tsx@@ -14,6 +14,7 @@ import { Input } from '../ui/input';import { Textarea } from '../ui/textarea';import { EditorDialog } from '../ui/editor-dialog';import { Button } from '../ui/button';+import { errorMessage } from '@/lib/errorMessage';type BackendKey = 'claude' | 'opencode' | 'codex';@@ -137,8 +138,8 @@ export const NewAgentDialog: React.FC<NewAgentDialogProps> = ({ open, onClose, oonCreated(result.agent);onClose();}- } catch (err: any) {- setError(err?.message ?? String(err));+ } catch (err) {+ setError(errorMessage(err) ?? String(err));} finally {setSubmitting(false);}diff --git a/ui/src/components/workbench/NewProjectDialog.tsx b/ui/src/components/workbench/NewProjectDialog.tsxindex a250b3485..f8a8adaa7 100644--- a/ui/src/components/workbench/NewProjectDialog.tsx+++ b/ui/src/components/workbench/NewProjectDialog.tsx@@ -7,6 +7,7 @@ import type { WorkbenchProject } from '../../context/ApiContext';import { DirectoryBrowser } from '../ui/directory-browser';import { Button } from '../ui/button';import { Input } from '../ui/input';+import { errorMessage } from '@/lib/errorMessage';interface NewProjectDialogProps {onClose: () => void;@@ -50,8 +51,8 @@ export const NewProjectDialog: React.FC<NewProjectDialogProps> = ({ onClose, onCdisplay_name: displayName.trim() || undefined,});onCreated(project);- } catch (err: any) {- setError(err?.message ?? String(err));+ } catch (err) {+ setError(errorMessage(err) ?? String(err));setSubmitting(false);}};diff --git a/ui/src/components/workbench/RunAgentDialog.tsx b/ui/src/components/workbench/RunAgentDialog.tsxindex 7ff321dd7..5f3c11204 100644--- a/ui/src/components/workbench/RunAgentDialog.tsx+++ b/ui/src/components/workbench/RunAgentDialog.tsx@@ -7,6 +7,7 @@ import { useApi } from '../../context/ApiContext';import type { VibeAgentFull, WorkbenchProject } from '../../context/ApiContext';import { Button } from '../ui/button';import { Select } from '../ui/select';+import { errorMessage } from '@/lib/errorMessage';interface RunAgentDialogProps {agent: VibeAgentFull;@@ -65,8 +66,8 @@ export const RunAgentDialog: React.FC<RunAgentDialogProps> = ({ agent, onClose }reasoning_effort: agent.reasoning_effort || undefined,});navigate(`/chat/${encodeURIComponent(session.id)}`);- } catch (err: any) {- setError(err?.message ?? String(err));+ } catch (err) {+ setError(errorMessage(err) ?? String(err));setSubmitting(false);}};diff --git a/ui/src/components/workbench/ShowPageLaunchControl.tsx b/ui/src/components/workbench/ShowPageLaunchControl.tsxindex 4f7cf8cd1..935e49c5b 100644--- a/ui/src/components/workbench/ShowPageLaunchControl.tsx+++ b/ui/src/components/workbench/ShowPageLaunchControl.tsx@@ -9,7 +9,8 @@ import {import { useTranslation } from 'react-i18next';import { showPagePrivatePath } from '../../apps/showPageAvatar';-import { showDockId, useDock } from '../../context/DockContext';+import { useDock } from '../../context/DockContext';+import { showDockId } from '../../context/dockDoc';import { useShowPageDrag } from '../../context/showPageDrag';import { useWindowManager } from '../../context/WindowManagerContext';import {diff --git a/ui/src/components/workbench/ShowPageShareControl.tsx b/ui/src/components/workbench/ShowPageShareControl.tsxindex 9af9f24e0..a0a55c613 100644--- a/ui/src/components/workbench/ShowPageShareControl.tsx+++ b/ui/src/components/workbench/ShowPageShareControl.tsx@@ -8,7 +8,8 @@ import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover';import { Select } from '../ui/select';import { Switch } from '../ui/switch';import { useApi } from '../../context/ApiContext';-import { showDockId, useDock } from '../../context/DockContext';+import { useDock } from '../../context/DockContext';+import { showDockId } from '../../context/dockDoc';import { copyTextToClipboard } from '../../lib/utils';import { isIosDevice, isRealMobileSafari, isStandalonePwa } from '../../lib/platform';import { copyHref, type ShowPageLinkInfo } from '../../lib/showPageLinks';diff --git a/ui/src/components/workbench/SkillsPage.tsx b/ui/src/components/workbench/SkillsPage.tsxindex dc20dd20d..0891ad1cd 100644--- a/ui/src/components/workbench/SkillsPage.tsx+++ b/ui/src/components/workbench/SkillsPage.tsx@@ -17,6 +17,7 @@ import { SkillDetailPanel } from './skills/SkillDetailPanel';import { ProjectPicker } from './skills/ProjectPicker';import { AddSkillDialog } from './skills/AddSkillDialog';import { BrowseRegistryDialog } from './skills/BrowseRegistryDialog';+import { errorMessage } from '@/lib/errorMessage';const skillKey = (s: SkillBrief) => `${s.scope}:${s.name}`;@@ -92,8 +93,8 @@ export const SkillsPage: React.FC = () => {setError(res.error?.message ?? 'Failed to list skills');setSkills([]);}- } catch (err: any) {- if (reqId === listReq.current) setError(err?.message ?? String(err));+ } catch (err) {+ if (reqId === listReq.current) setError(errorMessage(err) ?? String(err));} finally {if (reqId === listReq.current) setLoading(false);}@@ -167,8 +168,8 @@ export const SkillsPage: React.FC = () => {: await api.removeSkill(selected.name, { scope: selected.scope, projectId: projectArg, backends: [backend] });if (!res.ok) showToast(res.error?.message ?? BACKEND_LABEL[backend], 'error');await refresh();- } catch (err: any) {- showToast(err?.message ?? String(err), 'error');+ } catch (err) {+ showToast(errorMessage(err) ?? String(err), 'error');} finally {setBusyBackend(null);}@@ -187,8 +188,8 @@ export const SkillsPage: React.FC = () => {} else {showToast(res.error?.message ?? selected.name, 'error');}- } catch (err: any) {- showToast(err?.message ?? String(err), 'error');+ } catch (err) {+ showToast(errorMessage(err) ?? String(err), 'error');}};@@ -204,8 +205,8 @@ export const SkillsPage: React.FC = () => {} else {showToast(res.error?.message ?? selected.name, 'error');}- } catch (err: any) {- showToast(err?.message ?? String(err), 'error');+ } catch (err) {+ showToast(errorMessage(err) ?? String(err), 'error');} finally {setUpdating(false);}@@ -321,8 +322,8 @@ export const SkillsPage: React.FC = () => {} else {showToast(res.message || t('skills.installFailed'), 'error');}- } catch (err: any) {- showToast(err?.message || t('skills.installFailed'), 'error');+ } catch (err) {+ showToast(errorMessage(err) || t('skills.installFailed'), 'error');} finally {setInstallingAskill(false);}diff --git a/ui/src/components/workbench/TerminalTabs.tsx b/ui/src/components/workbench/TerminalTabs.tsxindex b5a7376ed..6bdb12d44 100644--- a/ui/src/components/workbench/TerminalTabs.tsx+++ b/ui/src/components/workbench/TerminalTabs.tsx@@ -9,6 +9,7 @@ import { apiFetch } from '../../lib/apiFetch';import { acquireTerminalSlot, releaseTerminalSlot } from '../../lib/terminalSlots';import { MAX_RESTORED_TERMINAL_TABS, WINDOW_RESTORE_PARAM } from '../../lib/workbenchPersistence';import type { TerminalStatus } from './TerminalView';+import { useLatestRef } from '@/lib/useLatestRef';// Lazy so xterm.js stays out of the main bundle until a terminal opens.const TerminalView = lazy(() => import('./TerminalView').then((m) => ({ default: m.TerminalView })));@@ -70,16 +71,19 @@ export const TerminalTabs: React.FC<{const { t } = useTranslation();const { getAuthSession } = useApi();const [identity, setIdentity] = useState<string | null | undefined>(undefined); // undefined = resolving- const tabSeq = useRef(0);// Restore the tab layout (count + custom titles) on reload for a windowed terminal, over fresh// slots/shells — the ephemeral session ids are never persisted (a deliberate security property).+ // The initializer numbers its tabs 1..n from a local counter rather than from `tabSeq`, so it+ // touches no ref during render; `tabSeq` picks up at n below and every later tab counts on from+ // there, which is what keeps the keys unique.const [tabs, setTabs] = useState<Tab[]>(() => {+ let seq = 0;const restore = windowed ? (params?.[WINDOW_RESTORE_PARAM] as TerminalRestore | undefined) : undefined;if (restore && Array.isArray(restore.tabs) && restore.tabs.length > 0) {// Cap at the backend session capacity before acquiring slots, so a corrupt/oversized array// can't open a flood of shells the terminal service can't admit.return restore.tabs.slice(0, MAX_RESTORED_TERMINAL_TABS).map((rt) => ({- key: ++tabSeq.current,+ key: ++seq,slot: acquireTerminalSlot(),title: typeof rt?.title === 'string' ? rt.title : undefined,}));@@ -88,8 +92,11 @@ export const TerminalTabs: React.FC<{// directory. The route terminal's first tab stays the persistent reattach (slot null); its cwd// tab is appended by the launch effect below instead.const firstCwd = windowed && typeof params?.cwd === 'string' ? (params.cwd as string) : undefined;- return [{ key: ++tabSeq.current, slot: windowed ? acquireTerminalSlot() : null, cwd: firstCwd }];+ return [{ key: ++seq, slot: windowed ? acquireTerminalSlot() : null, cwd: firstCwd }];});+ // Highest key handed out so far. Seeded from the initial tabs (keyed 1..n above); `useRef` keeps+ // that first value, so later renders never reset it.+ const tabSeq = useRef(tabs.length);const [active, setActive] = useState<number>(() => tabs[0]?.key ?? 0);// Whether sessions actually persist (tmux available) — reported by TerminalView's ready frame.// Drives the tab-bar badge so it never falsely promises persistence for a plain-shell fallback.@@ -176,8 +183,7 @@ export const TerminalTabs: React.FC<{// Dispose every ephemeral session on unmount (window close) + on tab/page unload, reading// the live tabs from a ref so the listeners don't churn as tabs change.- const liveRef = useRef<{ tabs: Tab[]; resolve: (t: Tab) => string | null }>({ tabs, resolve: sessionIdFor });- liveRef.current = { tabs, resolve: sessionIdFor };+ const liveRef = useLatestRef({ tabs, resolve: sessionIdFor });useEffect(() => {const onHide = () => {for (const tab of liveRef.current.tabs) {diff --git a/ui/src/components/workbench/TerminalView.tsx b/ui/src/components/workbench/TerminalView.tsxindex b7125e8fc..9ca06124b 100644--- a/ui/src/components/workbench/TerminalView.tsx+++ b/ui/src/components/workbench/TerminalView.tsx@@ -15,6 +15,7 @@ import {resetTerminalFontSize,subscribeTerminalFontSize,} from '../../lib/terminalFontSize';+import { useLatestRef } from '@/lib/useLatestRef';// xterm.js wired to the /api/terminal/{id} WebSocket. Protocol (locked with the// backend): client sends raw stdin as BINARY frames and JSON control as TEXT@@ -148,8 +149,7 @@ export const TerminalView: React.FC<{// Report actual session persistence (from the backend 'ready' frame) up to the tab bar, so its// badge reflects reality — tmux-backed = persistent, plain-shell fallback = not. Held in a ref so// the WS effect (which doesn't depend on the prop) always calls the latest callback.- const onPersistentRef = useRef(onPersistent);- onPersistentRef.current = onPersistent;+ const onPersistentRef = useLatestRef(onPersistent);const [status, setStatus] = useState<TerminalStatus>('connecting');const [exitCode, setExitCode] = useState<number | null>(null);const [reconnectKey, setReconnectKey] = useState(0);@@ -164,8 +164,7 @@ export const TerminalView: React.FC<{// Surface connection status to the parent (tab bar). The standalone status row inside the// body was removed — only the terminating states render an in-body overlay (below).- const onStatusRef = useRef(onStatus);- onStatusRef.current = onStatus;+ const onStatusRef = useLatestRef(onStatus);useEffect(() => {onStatusRef.current?.(status, exitCode);}, [status, exitCode]);diff --git a/ui/src/components/workbench/VaultsPage.tsx b/ui/src/components/workbench/VaultsPage.tsxindex 4fa537991..2f4e0fbf5 100644--- a/ui/src/components/workbench/VaultsPage.tsx+++ b/ui/src/components/workbench/VaultsPage.tsx@@ -17,7 +17,8 @@ import { useToast } from '../../context/ToastContext';import type { ApprovalOutcome } from '../ui/vault-approval-card';import { SigningAddressList } from '../ui/signing-address-list';import { VaultApprovalDialog } from '../ui/vault-approval-dialog';-import { VaultRequestSessionLink, vaultRequestSessionDisplay } from '../ui/vault-request-session-link';+import { vaultRequestSessionDisplay } from '../ui/vault-request-session';+import { VaultRequestSessionLink } from '../ui/vault-request-session-link';import { VaultSecretDialog } from '../ui/vault-secret-dialog';import { VaultSettingsDialog } from '../ui/vault-settings-dialog';import { useProtectedVault } from '../../lib/useProtectedVault';diff --git a/ui/src/components/workbench/harnessAgents.ts b/ui/src/components/workbench/harnessAgents.tsindex 90bab92af..e43f5a88b 100644--- a/ui/src/components/workbench/harnessAgents.ts+++ b/ui/src/components/workbench/harnessAgents.ts@@ -10,3 +10,13 @@ export async function loadHarnessAgentCatalog(});return Object.fromEntries(result.agents.map((agent) => [agent.name, agent]));}++/** How a run names its Agent: the Agent's own display name, else the raw name it+ * was dispatched under, else an em dash. An Agent renamed or archived after the+ * run still reads back under the name the run actually used. */+export function agentDisplayName(+ agentName: string | null | undefined,+ agent?: Pick<VibeAgentBrief, 'display_name'>,+): string {+ return agent?.display_name || agentName || '—';+}diff --git a/ui/src/components/workbench/harnessTabs.ts b/ui/src/components/workbench/harnessTabs.tsnew file mode 100644index 000000000..83b94d355--- /dev/null+++ b/ui/src/components/workbench/harnessTabs.ts@@ -0,0 +1,27 @@+// Which Harness tab is on screen, and what an empty one says. The tab set and+// the ``?tab=`` mapping live together so removing a tab later cannot strand its+// old links, and the copy keys are asserted without rendering the page+// (see HarnessPage.test.tsx).++export type TabKey = 'tasks' | 'watches' | 'runs';++export const TAB_ORDER: TabKey[] = ['tasks', 'watches', 'runs'];+export const DEFAULT_TAB: TabKey = 'tasks';++// Which tab a ``?tab=`` param opens. Anything that is not a tab opens the+// default rather than selecting nothing — ``?tab=webhooks`` still arrives from+// links and bookmarks made before the Webhooks tab was removed, and must land+// on Tasks, not on an empty page with no tab lit.+//+// One function rather than a guard here and a ``useState`` initializer three+// hundred lines away, so removing a tab later cannot strand its old links.+export function harnessTabFromParam(param: string | null | undefined): TabKey {+ return (TAB_ORDER as string[]).includes(param ?? '') ? (param as TabKey) : DEFAULT_TAB;+}++export function harnessEmptyStateKey(kind: TabKey, hasStoredRows: boolean): string {+ if (!hasStoredRows) {+ return kind === 'tasks' ? 'harness.emptyTasks' : kind === 'watches' ? 'harness.emptyWatches' : 'harness.emptyRuns';+ }+ return kind === 'tasks' ? 'harness.noTaskMatches' : kind === 'watches' ? 'harness.noWatchMatches' : 'harness.noRunMatches';+}diff --git a/ui/src/components/workbench/sessionAgentName.ts b/ui/src/components/workbench/sessionAgentName.tsnew file mode 100644index 000000000..a7f65ed4d--- /dev/null+++ b/ui/src/components/workbench/sessionAgentName.ts@@ -0,0 +1,18 @@+// How a chat session names its Agent. The Agent row is matched by id first and by+// name only as a fallback, so a session whose Agent was renamed still reads back+// under the current display name while a stale catalog entry cannot claim it.+// Pure so the precedence is asserted without mounting the page+// (see ChatArchivedReadOnly.test.tsx).+import type { VibeAgentBrief, WorkbenchSession } from '../../context/ApiContext';++export function sessionAgentDisplayName(+ session: Pick<WorkbenchSession, 'agent_id' | 'agent_name'>,+ agents: VibeAgentBrief[],+): string | null {+ const agentName = session.agent_name?.trim() || null;+ if (!agentName) return null;+ const agent =+ (session.agent_id ? agents.find((candidate) => candidate.id === session.agent_id) : undefined) ??+ agents.find((candidate) => candidate.name === agentName);+ return agent?.display_name?.trim() || agentName;+}diff --git a/ui/src/components/workbench/skills/AddSkillDialog.tsx b/ui/src/components/workbench/skills/AddSkillDialog.tsxindex b306df679..f78710868 100644--- a/ui/src/components/workbench/skills/AddSkillDialog.tsx+++ b/ui/src/components/workbench/skills/AddSkillDialog.tsx@@ -9,6 +9,7 @@ import { SegmentedRadio } from '../../ui/segmented';import { Checkbox } from '../../ui/checkbox';import { BACKEND_CHIP, BACKEND_LABEL, BACKEND_ORDER, type Backend } from '../../../lib/backendAccent';import { FileDropzone } from './FileDropzone';+import { errorMessage } from '@/lib/errorMessage';const AGENT_OF: Record<Backend, string> = { claude: 'claude-code', opencode: 'opencode', codex: 'codex' };@@ -66,8 +67,8 @@ export function AddSkillDialog({ defaultScope, projectId, projectName, onClose,if (reqId !== previewReq.current) return; // a newer source superseded thisif (res.ok && res.skills) onDiscovered(res.skills);else setError(res.error?.message ?? t('skills.addDialog.fetchFirst'));- } catch (err: any) {- if (reqId === previewReq.current) setError(err?.message ?? String(err));+ } catch (err) {+ if (reqId === previewReq.current) setError(errorMessage(err) ?? String(err));} finally {if (reqId === previewReq.current) setBusy(null);}@@ -89,8 +90,8 @@ export function AddSkillDialog({ defaultScope, projectId, projectName, onClose,} else {setError(res.error?.message ?? t('skills.addDialog.fetchFirst'));}- } catch (err: any) {- if (reqId === previewReq.current) setError(err?.message ?? String(err));+ } catch (err) {+ if (reqId === previewReq.current) setError(errorMessage(err) ?? String(err));} finally {if (reqId === previewReq.current) setBusy(null);}@@ -162,8 +163,8 @@ export function AddSkillDialog({ defaultScope, projectId, projectName, onClose,}showToast(t('skills.addSuccess', { count: selected.size }), 'success');onInstalled();- } catch (err: any) {- setError(err?.message ?? String(err));+ } catch (err) {+ setError(errorMessage(err) ?? String(err));} finally {setBusy(null);}diff --git a/ui/src/components/workbench/skills/BrowseRegistryDialog.tsx b/ui/src/components/workbench/skills/BrowseRegistryDialog.tsxindex 8ca390738..ac98afc95 100644--- a/ui/src/components/workbench/skills/BrowseRegistryDialog.tsx+++ b/ui/src/components/workbench/skills/BrowseRegistryDialog.tsx@@ -6,6 +6,7 @@ import { useApi } from '../../../context/ApiContext';import type { SkillScope, SkillSearchItem } from '../../../context/ApiContext';import { useToast } from '../../../context/ToastContext';import { AiScoreBadge } from './QualityMeter';+import { errorMessage } from '@/lib/errorMessage';export interface BrowseRegistryDialogProps {scope: SkillScope;@@ -64,8 +65,8 @@ export function BrowseRegistryDialog({ scope, projectId, installedNames, onClose} else {showToast(res.error?.message ?? t('skills.addSkill'), 'error');}- } catch (err: any) {- showToast(err?.message ?? String(err), 'error');+ } catch (err) {+ showToast(errorMessage(err) ?? String(err), 'error');} finally {setInstalling(null);}diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsxindex f09ddabeb..d037cac9a 100644--- a/ui/src/context/ApiContext.tsx+++ b/ui/src/context/ApiContext.tsx@@ -10,7 +10,8 @@ import {WorkbenchEventReconnectLoop,type WorkbenchEventConnectionState,} from '../lib/workbenchEventConnection';-import type { DockDoc } from './DockContext';+import type { DockDoc } from './dockDoc';+import { archivedConflictSessionId, selectApiErrorFields } from './apiErrorParse';// The workbench Dock API response shape ({ ok, dock }); the Dock document type// itself lives with the DockProvider that owns reconciliation.@@ -1933,59 +1934,6 @@ export class ApiError extends Error {}}-/** Pick the machine code + human fallback out of an error response body.- *- * Accepts the legacy ``error`` shape (a bare string, or ``{ code, message }``) AND the- * top-level ``{ code, message }`` shape newer routes use (e.g. /api/vault/*), so callers- * always get a real ``ApiError.code`` to branch on instead of a generic status string.- *- * Note the precedence, which is a CONTRACT for route authors: ``error`` is consulted- * first, and a STRING ``error`` is taken as the code — so a route that pairs a human- * sentence in ``error`` with the real code alongside it in a top-level ``code`` loses that- * code here, and its message is rendered verbatim in every locale. Routes with a machine- * code must nest it: ``{"error": {"code", "message"}}`` (see ``_show_page_error_response``- * in ``vibe/ui_server.py``). Extracted from ``handleApiError`` unchanged so that contract- * is directly testable — see ApiErrorParse.test.ts. */-export const selectApiErrorFields = (- data: any,- defaultMessage: string,-): { code: string | null; fallback: string } | null => {- // Not ``data?.error``: a non-object JSON body (``null``) must keep THROWING here so- // handleApiError's catch falls back to the status text, exactly as before.- const rawErr = data.error ?? (data.code ? { code: data.code, message: data.message } : undefined);- if (!rawErr) return null;- const code = typeof rawErr === 'string' ? rawErr : rawErr?.code;- const fallback = typeof rawErr === 'string' ? rawErr : rawErr?.message ?? rawErr?.code ?? defaultMessage;- return { code: typeof code === 'string' ? code : null, fallback };-};--/** Which session an error response says is archived, or ``null`` if it says no such- * thing. The WHOLE decision — the code guard and the id lookup — so it is testable- * without a DOM (this repo has no DOM test environment; same reason- * ``selectApiErrorFields`` was extracted). ``handleApiError`` only fans the answer- * out to subscribers.- *- * Every route that can answer ``409 session_archived`` puts the session id in the- * first segment after its collection: ``/api/sessions/<id>`` (PATCH), plus- * ``/messages`` and ``/fork`` under it, and ``/api/show-pages/<session_id>/…``- * (ensure / visibility / share-id / rotate-share / icon). One pattern therefore- * covers all of them, and a future session-scoped route inherits it.- *- * Deliberately UNANCHORED: some callers pass a human LABEL rather than a bare- * path (``updateSession`` sends ``"PATCH /api/sessions/<id>"``), and that label- * belongs to the very route this convergence was added for. */-export const archivedConflictSessionId = (code: string | null, path: string): string | null => {- if (code !== 'session_archived') return null;- const match = /\/api\/(?:sessions|show-pages)\/([^/?#\s]+)/.exec(path);- if (!match) return null;- try {- return decodeURIComponent(match[1]) || null;- } catch {- // A malformed escape must not throw inside an error handler.- return match[1] || null;- }-};-const ApiContext = createContext<ApiContextType | undefined>(undefined);const CONFIG_CACHE_TTL_MS = 30_000;diff --git a/ui/src/context/ApiErrorParse.test.ts b/ui/src/context/ApiErrorParse.test.tsindex 644b06a7a..9cc26bbe8 100644--- a/ui/src/context/ApiErrorParse.test.ts+++ b/ui/src/context/ApiErrorParse.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest';-import { archivedConflictSessionId, selectApiErrorFields } from './ApiContext';+import { archivedConflictSessionId, selectApiErrorFields } from './apiErrorParse';// ── Codex review #4 (ui_server.py:6611) ───────────────────────────────────────// PATCH /api/sessions/<id> on an archived session answereddiff --git a/ui/src/context/ComposerBridgeContext.tsx b/ui/src/context/ComposerBridgeContext.tssimilarity index 72%rename from ui/src/context/ComposerBridgeContext.tsxrename to ui/src/context/ComposerBridgeContext.tsindex 208d3fdfa..fdd2859ce 100644--- a/ui/src/context/ComposerBridgeContext.tsx+++ b/ui/src/context/ComposerBridgeContext.ts@@ -1,4 +1,4 @@-import { createContext, useContext, useEffect, useMemo, useState, type ReactNode } from 'react';+import { createContext, useContext, useEffect } from 'react';/*** Bridges the chat composer (mounted only inside ChatPage) to components that@@ -21,15 +21,7 @@ type ComposerBridge = {setTarget: (target: ComposerInsertTarget | null) => void;};-const ComposerBridgeContext = createContext<ComposerBridge | null>(null);--export const ComposerBridgeProvider = ({ children }: { children: ReactNode }) => {- const [target, setTarget] = useState<ComposerInsertTarget | null>(null);- // Stable value identity (setTarget is a stable setState fn) so the value only- // changes when the active composer target does — not on unrelated re-renders.- const value = useMemo(() => ({ target, setTarget }), [target]);- return <ComposerBridgeContext.Provider value={value}>{children}</ComposerBridgeContext.Provider>;-};+export const ComposerBridgeContext = createContext<ComposerBridge | null>(null);/** Consumer side (sidebar session menu): the active composer target, or null. */export const useComposerInsertTarget = (): ComposerInsertTarget | null =>diff --git a/ui/src/context/ComposerBridgeProvider.tsx b/ui/src/context/ComposerBridgeProvider.tsxnew file mode 100644index 000000000..f38f1a510--- /dev/null+++ b/ui/src/context/ComposerBridgeProvider.tsx@@ -0,0 +1,11 @@+import { useMemo, useState, type ReactNode } from 'react';++import { ComposerBridgeContext, type ComposerInsertTarget } from './ComposerBridgeContext';++export const ComposerBridgeProvider = ({ children }: { children: ReactNode }) => {+ const [target, setTarget] = useState<ComposerInsertTarget | null>(null);+ // Stable value identity (setTarget is a stable setState fn) so the value only+ // changes when the active composer target does — not on unrelated re-renders.+ const value = useMemo(() => ({ target, setTarget }), [target]);+ return <ComposerBridgeContext.Provider value={value}>{children}</ComposerBridgeContext.Provider>;+};diff --git a/ui/src/context/DockContext.ts b/ui/src/context/DockContext.tsnew file mode 100644index 000000000..c89fe43b4--- /dev/null+++ b/ui/src/context/DockContext.ts@@ -0,0 +1,38 @@+import { createContext, useContext } from 'react';++import type { DockPin } from './dockDoc';++// The Dock value contract and the context handle every consumer reads.+// `DockProvider.tsx` owns the fetch/optimistic-write side; keeping the handle in+// its own component-free module lets the provider hot-reload on its own.+export interface DockValue {+ /** Reconciled docked subset (built-in ids + `show:<id>` pins), in user order. */+ order: string[];+ /** Installed AI pages (built-ins are implicitly installed, not listed here). */+ pins: DockPin[];+ /** Whether a session's Show Page is installed (pinned). */+ isPinned: (sessionId: string) => boolean;+ /** Whether a Dock id (built-in or `show:<id>`) is currently in the Dock. */+ isDocked: (dockId: string) => boolean;+ /** The pin record for a session, or null. */+ pinFor: (sessionId: string) => DockPin | null;+ /** Install a session's Show Page — also docks it (optimistic; idempotent). */+ pin: (sessionId: string) => Promise<void>;+ /** Uninstall a session's Show Page — removes it from install + Dock (optimistic; idempotent). */+ unpin: (sessionId: string) => Promise<void>;+ /** Add a known tile (built-in or installed page) to the Dock (optimistic; idempotent). */+ dock: (dockId: string) => Promise<void>;+ /** Remove a tile from the Dock, keeping it installed (optimistic; idempotent). */+ undock: (dockId: string) => Promise<void>;+ /** Persist a new resident-tile order (optimistic; rolls back if rejected). */+ setOrder: (order: string[]) => Promise<void>;+}+++export const DockContext = createContext<DockValue | null>(null);++export function useDock(): DockValue {+ const ctx = useContext(DockContext);+ if (!ctx) throw new Error('useDock must be used within a DockProvider');+ return ctx;+}diff --git a/ui/src/context/DockContext.tsx b/ui/src/context/DockProvider.tsxsimilarity index 51%rename from ui/src/context/DockContext.tsxrename to ui/src/context/DockProvider.tsxindex 166b0f077..db90813be 100644--- a/ui/src/context/DockContext.tsx+++ b/ui/src/context/DockProvider.tsx@@ -1,136 +1,20 @@-import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';-import { APP_LIST } from '../apps/registry';import { useApi } from './ApiContext';--// The workbench Dock is durable, cross-device *product* state (see-// core/dock_store.py). Two layers (§7.1c): `pins` is the INSTALLED set of AI-// Show Pages (built-ins are implicitly installed); `order` is the DOCKED subset —-// the resident tiles, in user order, a SUBSET of the known ids. This provider-// fetches the document once, keeps it reconciled against the apps the client-// knows, and exposes optimistic install (pin) / uninstall (unpin) /-// dock / undock / reorder actions that roll back if the server rejects the write.-//-// A Dock item id is either a built-in app id verbatim (`files` / `terminal` /-// `editor` / `library`) or a pinned Show Page as `show:<session_id>`. The-// built-in id set and its canonical order are a contract shared with the-// backend's BUILTIN_DOCK_IDS — both derive from APP_LIST, so keep them in sync.-// Any tile, built-ins included, can be undocked (absent from `order`); the empty-// Dock is a valid state.--export type DockPin = {- session_id: string;- title_snapshot: string;- pinned_at: string;-};--export type DockDoc = {- order: string[];- pins: DockPin[];-};--export const SHOW_DOCK_PREFIX = 'show:';--// Fixed defensive cap on PINNED Show Pages, mirroring core/dock_store.py's-// MAX_PINNED_PAGES. reconcile clamps pins to this FIXED budget (independent of-// the built-in count) so a corrupt/oversized doc stays bounded AND adding a-// built-in never shrinks the budget or drops an existing valid pin on reconcile.-export const MAX_PINNED_PAGES = 197;--/** The Dock id for a pinned Show Page session. */-export function showDockId(sessionId: string): string {- return `${SHOW_DOCK_PREFIX}${sessionId}`;-}--/** The session id inside a `show:<id>` Dock id, or null for a non-Show item. */-export function dockIdToSession(dockId: string): string | null {- return dockId.startsWith(SHOW_DOCK_PREFIX) ? dockId.slice(SHOW_DOCK_PREFIX.length) : null;-}--// The resident built-in tiles, in canonical order. Mirrors the backend-// BUILTIN_DOCK_IDS; `preview` is intentionally absent (opened on demand, never-// resident), exactly like `showpage`.-const BUILTIN_DOCK_IDS: string[] = APP_LIST.map((app) => app.id);--/**- * Canonicalize a Dock document against the known built-in ids — the same rule- * the server applies (core/dock_store._reconcile), so a stale or partial doc- * from either side converges to one shape:- * - dedupe pins by session id (first wins);- * - clamp pins to the fixed install budget;- * - drop unknown / duplicate ids from `order`.- * The order is left as the stored SUBSET — built-ins and pins are NOT- * force-appended (§7.1c), so an undocked tile stays undocked and the empty Dock- * round-trips. Pure: no I/O, safe to unit-test and to run on every read.- */-export function reconcileDock(doc: DockDoc | null | undefined, builtinIds: string[] = BUILTIN_DOCK_IDS): DockDoc {- const pins: DockPin[] = [];- const seenPins = new Set<string>();- for (const pin of doc?.pins ?? []) {- if (!pin || typeof pin.session_id !== 'string' || !pin.session_id || seenPins.has(pin.session_id)) continue;- seenPins.add(pin.session_id);- pins.push({- session_id: pin.session_id,- title_snapshot: typeof pin.title_snapshot === 'string' ? pin.title_snapshot : '',- pinned_at: typeof pin.pinned_at === 'string' ? pin.pinned_at : '',- });- }-- // Clamp on read (mirrors the backend): built-ins are always kept; excess pins- // beyond the FIXED pin budget are dropped so a corrupt/oversized doc stays- // bounded (the budget doesn't shrink when a built-in is added).- const maxPins = MAX_PINNED_PAGES;- const clampedPins = pins.length > maxPins ? pins.slice(0, maxPins) : pins;-- const pinIds = clampedPins.map((pin) => showDockId(pin.session_id));- const known = new Set<string>([...builtinIds, ...pinIds]);-- const order: string[] = [];- const seen = new Set<string>();- for (const id of doc?.order ?? []) {- if (known.has(id) && !seen.has(id)) {- order.push(id);- seen.add(id);- }- }- return { order, pins: clampedPins };-}--/**- * The pre-load default Dock: every built-in docked, nothing installed — matching- * the server's seed for a fresh instance. Used only as the initial state before- * the server document loads (avoids a flash of an empty Dock); once the GET- * resolves, reconcileDock takes over and an undocked built-in stays undocked.- */-export function seedDefaultDock(builtinIds: string[] = BUILTIN_DOCK_IDS): DockDoc {- return { order: [...builtinIds], pins: [] };-}--export interface DockValue {- /** Reconciled docked subset (built-in ids + `show:<id>` pins), in user order. */- order: string[];- /** Installed AI pages (built-ins are implicitly installed, not listed here). */- pins: DockPin[];- /** Whether a session's Show Page is installed (pinned). */- isPinned: (sessionId: string) => boolean;- /** Whether a Dock id (built-in or `show:<id>`) is currently in the Dock. */- isDocked: (dockId: string) => boolean;- /** The pin record for a session, or null. */- pinFor: (sessionId: string) => DockPin | null;- /** Install a session's Show Page — also docks it (optimistic; idempotent). */- pin: (sessionId: string) => Promise<void>;- /** Uninstall a session's Show Page — removes it from install + Dock (optimistic; idempotent). */- unpin: (sessionId: string) => Promise<void>;- /** Add a known tile (built-in or installed page) to the Dock (optimistic; idempotent). */- dock: (dockId: string) => Promise<void>;- /** Remove a tile from the Dock, keeping it installed (optimistic; idempotent). */- undock: (dockId: string) => Promise<void>;- /** Persist a new resident-tile order (optimistic; rolls back if rejected). */- setOrder: (order: string[]) => Promise<void>;-}--const DockContext = createContext<DockValue | null>(null);-+import { DockContext, type DockValue } from './DockContext';+import {+ BUILTIN_DOCK_IDS,+ reconcileDock,+ seedDefaultDock,+ showDockId,+ type DockDoc,+} from './dockDoc';+import { useLatestRef } from '@/lib/useLatestRef';++// Fetches the Dock document once, keeps it reconciled against the apps this client+// knows (see dockDoc.ts for the shape and the reconcile rules), and exposes optimistic+// install (pin) / uninstall (unpin) / dock / undock / reorder actions that roll back if+// the server rejects the write.// Every-built-in-docked default so the Dock renders its resident tiles// immediately (no flicker) before the server document loads. Matches the// server's fresh-instance seed; reconcileDock takes over once the GET resolves.@@ -140,8 +24,7 @@ export const DockProvider: React.FC<{ children: React.ReactNode }> = ({ childrenconst api = useApi();const [doc, setDoc] = useState<DockDoc>(DEFAULT_DOC);// Latest committed doc for the async actions' rollback (avoids stale closures).- const docRef = useRef(doc);- docRef.current = doc;+ const docRef = useLatestRef(doc);// Dock writes are serialized. Each mutation shows its optimistic doc at once// (responsiveness), then queues the server request so requests run in action// order — never overlapping. A monotonic counter marks the latest mutation and@@ -292,9 +175,3 @@ export const DockProvider: React.FC<{ children: React.ReactNode }> = ({ childrenreturn <DockContext.Provider value={value}>{children}</DockContext.Provider>;};--export function useDock(): DockValue {- const ctx = useContext(DockContext);- if (!ctx) throw new Error('useDock must be used within a DockProvider');- return ctx;-}diff --git a/ui/src/context/StatusContext.ts b/ui/src/context/StatusContext.tsnew file mode 100644index 000000000..f9da43649--- /dev/null+++ b/ui/src/context/StatusContext.ts@@ -0,0 +1,24 @@+import { createContext, useContext } from 'react';++export interface RuntimeStatus {+ state?: string;+ last_action?: string;+ [key: string]: any;+}++interface StatusContextType {+ status: RuntimeStatus;+ health: boolean;+ refreshStatus: () => Promise<RuntimeStatus | null>;+ control: (action: string, payload?: any) => Promise<any>;+}++export const StatusContext = createContext<StatusContextType | undefined>(undefined);++export const useStatus = () => {+ const context = useContext(StatusContext);+ if (!context) {+ throw new Error('useStatus must be used within a StatusProvider');+ }+ return context;+};diff --git a/ui/src/context/StatusContext.tsx b/ui/src/context/StatusProvider.tsxsimilarity index 92%rename from ui/src/context/StatusContext.tsxrename to ui/src/context/StatusProvider.tsxindex 9f7527f64..bfe1c19bd 100644--- a/ui/src/context/StatusContext.tsx+++ b/ui/src/context/StatusProvider.tsx@@ -1,18 +1,6 @@-import React, { createContext, useCallback, useContext, useEffect, useRef, useState } from 'react';+import React, { useCallback, useEffect, useRef, useState } from 'react';import { apiFetch } from '../lib/apiFetch';--interface RuntimeStatus {- state?: string;- last_action?: string;- [key: string]: any;-}--interface StatusContextType {- status: RuntimeStatus;- health: boolean;- refreshStatus: () => Promise<RuntimeStatus | null>;- control: (action: string, payload?: any) => Promise<any>;-}+import { StatusContext, type RuntimeStatus } from './StatusContext';// Polling cadence for GET /status. The probe is cheap server-side (it reads a// small state file plus a process-liveness check), so the steady-state interval@@ -33,16 +21,6 @@ const RESTARTING_POLL_MS = 2_000;// slow-but-successful restart before we fall back to the idle cadence.const RESTARTING_FAST_WINDOW_MS = 45_000;-const StatusContext = createContext<StatusContextType | undefined>(undefined);--export const useStatus = () => {- const context = useContext(StatusContext);- if (!context) {- throw new Error('useStatus must be used within a StatusProvider');- }- return context;-};-export const StatusProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {const [status, setStatus] = useState<RuntimeStatus>({});const [health, setHealth] = useState(false);diff --git a/ui/src/context/ThemeContext.ts b/ui/src/context/ThemeContext.tsnew file mode 100644index 000000000..2260ce944--- /dev/null+++ b/ui/src/context/ThemeContext.ts@@ -0,0 +1,21 @@+import { createContext, useContext } from 'react';++export type ThemeMode = 'system' | 'light' | 'dark';+type ResolvedTheme = 'light' | 'dark';++type ThemeContextValue = {+ mode: ThemeMode;+ resolvedTheme: ResolvedTheme;+ setMode: (mode: ThemeMode) => void;+ cycleMode: () => void;+};++export const ThemeContext = createContext<ThemeContextValue | undefined>(undefined);++export function useTheme() {+ const context = useContext(ThemeContext);+ if (!context) {+ throw new Error('useTheme must be used within ThemeProvider');+ }+ return context;+}diff --git a/ui/src/context/ThemeContext.tsx b/ui/src/context/ThemeProvider.tsxsimilarity index 86%rename from ui/src/context/ThemeContext.tsxrename to ui/src/context/ThemeProvider.tsxindex 223029724..5475a7a84 100644--- a/ui/src/context/ThemeContext.tsx+++ b/ui/src/context/ThemeProvider.tsx@@ -1,21 +1,13 @@-import React, { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react';+import React, { useCallback, useEffect, useMemo, useState } from 'react';-export type ThemeMode = 'system' | 'light' | 'dark';-type ResolvedTheme = 'light' | 'dark';+import { ThemeContext, type ThemeMode } from './ThemeContext';-type ThemeContextValue = {- mode: ThemeMode;- resolvedTheme: ResolvedTheme;- setMode: (mode: ThemeMode) => void;- cycleMode: () => void;-};+type ResolvedTheme = 'light' | 'dark';const STORAGE_KEY = 'vibe-remote-theme';const VALID_MODES: ThemeMode[] = ['system', 'light', 'dark'];const DEFAULT_MODE: ThemeMode = 'system';-const ThemeContext = createContext<ThemeContextValue | undefined>(undefined);-function getSystemTheme(): ResolvedTheme {if (typeof window !== 'undefined' &&@@ -128,11 +120,3 @@ export const ThemeProvider: React.FC<{ children: React.ReactNode }> = ({ childrereturn <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>;};--export function useTheme() {- const context = useContext(ThemeContext);- if (!context) {- throw new Error('useTheme must be used within ThemeProvider');- }- return context;-}diff --git a/ui/src/context/ToastContext.ts b/ui/src/context/ToastContext.tsnew file mode 100644index 000000000..e09c0f230--- /dev/null+++ b/ui/src/context/ToastContext.ts@@ -0,0 +1,19 @@+import { createContext, useContext } from 'react';++import type { ToastAction } from './toastCoalesce';++export type ToastType = 'success' | 'error' | 'warning';++interface ToastContextType {+ showToast: (message: string, type?: ToastType, action?: ToastAction) => void;+}++export const ToastContext = createContext<ToastContextType | null>(null);++export const useToast = () => {+ const context = useContext(ToastContext);+ if (!context) {+ throw new Error('useToast must be used within a ToastProvider');+ }+ return context;+};diff --git a/ui/src/context/ToastContext.tsx b/ui/src/context/ToastProvider.tsxsimilarity index 90%rename from ui/src/context/ToastContext.tsxrename to ui/src/context/ToastProvider.tsxindex 61e52ced8..a41c18929 100644--- a/ui/src/context/ToastContext.tsx+++ b/ui/src/context/ToastProvider.tsx@@ -1,10 +1,9 @@-import React, { createContext, useContext, useState, useCallback, useMemo, useRef } from 'react';+import React, { useState, useCallback, useMemo, useRef } from 'react';import { AlertTriangle, CheckCircle, XCircle, X } from 'lucide-react';+import { ToastContext, type ToastType } from './ToastContext';import { shouldCoalesceToast, type ToastAction } from './toastCoalesce';-type ToastType = 'success' | 'error' | 'warning';-interface Toast {id: number;message: string;@@ -17,12 +16,6 @@ interface Toast {action?: ToastAction;}-interface ToastContextType {- showToast: (message: string, type?: ToastType, action?: ToastAction) => void;-}--const ToastContext = createContext<ToastContextType | null>(null);-let toastId = 0;// Dedupe window — within this many ms, an identical message replaces the@@ -131,11 +124,3 @@ export const ToastProvider: React.FC<{ children: React.ReactNode }> = ({ childre</ToastContext.Provider>);};--export const useToast = () => {- const context = useContext(ToastContext);- if (!context) {- throw new Error('useToast must be used within a ToastProvider');- }- return context;-};diff --git a/ui/src/context/WindowManagerContext.ts b/ui/src/context/WindowManagerContext.tsnew file mode 100644index 000000000..3b56ddc76--- /dev/null+++ b/ui/src/context/WindowManagerContext.ts@@ -0,0 +1,117 @@+import { createContext, useContext, useEffect } from 'react';++import type { AppId } from '../apps/registry';+import { useLatestRef } from '@/lib/useLatestRef';++// One open app window. Bounds are in CSS px relative to the window LAYER (the+// workbench main area, right of the sidebar). z drives stacking + focus order.+export interface WindowBounds {+ x: number;+ y: number;+ width: number;+ height: number;+}++export interface WindowInstance {+ id: string;+ appId: AppId;+ /** Optional per-instance title override (e.g. an open file path); falls back to the app's titleKey. */+ title?: string;+ /** Per-instance launch params surfaced to the app body (e.g. the file an Editor window opens). */+ params?: Record<string, unknown>;+ bounds: WindowBounds;+ z: number;+ minimized: boolean;+ maximized: boolean;+ // Bounds captured before a maximize, restored on un-maximize.+ restoreBounds?: WindowBounds;+}++export interface OpenAppOptions {+ title?: string;+ bounds?: Partial<WindowBounds>;+ params?: Record<string, unknown>;+}++export interface WindowManagerValue {+ windows: WindowInstance[];+ /** The current top window id (highest z, not minimized), or null. */+ focusedId: string | null;+ openApp: (appId: AppId, opts?: OpenAppOptions) => string;+ close: (id: string) => void;+ focus: (id: string) => void;+ minimize: (id: string) => void;+ /** Un-minimize and bring to front. */+ restore: (id: string) => void;+ toggleMaximize: (id: string) => void;+ /** Patch a window's bounds (used by drag + resize). */+ setBounds: (id: string, bounds: Partial<WindowBounds>) => void;+ /** Set (or clear) a window's title — e.g. the Editor reflecting its active file so several open+ * windows are distinguishable in the Dock + titlebar. No-op when the title is unchanged. */+ setTitle: (id: string, title: string | undefined) => void;+ /** Merge a patch into a window's launch params — lets an external navigation+ * (e.g. the /admin/show-pages redirect) hand an already-open app a request. */+ setParams: (id: string, params: Record<string, unknown>) => void;+ /**+ * Register (or clear, by passing null) a guard a window body uses to veto closing.+ * The getter returns a confirm message when closing would lose work, else null.+ */+ setCloseGuard: (id: string, getMessage: (() => string | null) | null) => void;+ /**+ * Register (or clear, by passing null) a provider a window body uses to contribute its own+ * JSON-able state to the persisted layout (e.g. the Editor's open tabs, the Terminal's tab+ * titles). Read on save; the value comes back through the window's params on the next restore.+ */+ setStateProvider: (id: string, getState: (() => unknown) | null) => void;+ /**+ * Mark a window as closing (its exit animation has started but it's still mounted until+ * animationEnd calls close()). Excludes it from the persisted snapshot so a reload during the+ * ~300ms close animation doesn't write back — and resurrect — a window the user just closed.+ */+ markClosing: (id: string) => void;+ /** Run a window's close guard (confirm if it has a message); true = may close. */+ confirmClose: (id: string) => boolean;+ /**+ * True while ANY window is mid drag/resize gesture. Windows shield their body+ * (iframe) with a transparent overlay while it's set, so a gesture whose pointer+ * crosses an iframe can't have its events stolen by the iframe document (§7.1i).+ * Set true at gesture start, false on gesture end (unconditional cleanup).+ */+ gestureActive: boolean;+ setGestureActive: (active: boolean) => void;+}++export const WindowManagerContext = createContext<WindowManagerValue | null>(null);++export function useWindowManager(): WindowManagerValue {+ const ctx = useContext(WindowManagerContext);+ if (!ctx) throw new Error('useWindowManager must be used within a WindowManagerProvider');+ return ctx;+}++// A window body calls this to veto its own close while there's unsaved work: pass+// the owning window id and a confirm message (or null when clean). No-ops for a+// non-windowed (full-page) mount, where windowId is undefined.+export function useWindowCloseGuard(windowId: string | undefined, message: string | null): void {+ const { setCloseGuard } = useWindowManager();+ const messageRef = useLatestRef(message);+ useEffect(() => {+ if (!windowId) return;+ setCloseGuard(windowId, () => messageRef.current);+ return () => setCloseGuard(windowId, null);+ }, [windowId, setCloseGuard]);+}++// A window body calls this to contribute its own JSON-able state to the persisted layout, so a+// reload can restore it (Editor open tabs, Terminal tab titles). `getState` may be a fresh closure+// each render — it's held in a ref and read lazily at save time, so it always sees current state+// without re-registering. No-ops for a non-windowed (full-page) mount, where windowId is undefined.+export function useWindowState(windowId: string | undefined, getState: () => unknown): void {+ const { setStateProvider } = useWindowManager();+ const getStateRef = useLatestRef(getState);+ useEffect(() => {+ if (!windowId) return;+ setStateProvider(windowId, () => getStateRef.current());+ return () => setStateProvider(windowId, null);+ }, [windowId, setStateProvider]);+}diff --git a/ui/src/context/WindowManagerContext.tsx b/ui/src/context/WindowManagerProvider.tsxsimilarity index 68%rename from ui/src/context/WindowManagerContext.tsxrename to ui/src/context/WindowManagerProvider.tsxindex 1febb9370..24f47778e 100644--- a/ui/src/context/WindowManagerContext.tsx+++ b/ui/src/context/WindowManagerProvider.tsx@@ -1,6 +1,6 @@-import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';-import { APP_REGISTRY, type AppId } from '../apps/registry';+import { APP_REGISTRY } from '../apps/registry';import {WINDOW_RESTORE_PARAM,loadWorkbenchWindows,@@ -8,86 +8,13 @@ import {stripRestoreParam,type PersistedWindow,} from '../lib/workbenchPersistence';--// One open app window. Bounds are in CSS px relative to the window LAYER (the-// workbench main area, right of the sidebar). z drives stacking + focus order.-export interface WindowBounds {- x: number;- y: number;- width: number;- height: number;-}--export interface WindowInstance {- id: string;- appId: AppId;- /** Optional per-instance title override (e.g. an open file path); falls back to the app's titleKey. */- title?: string;- /** Per-instance launch params surfaced to the app body (e.g. the file an Editor window opens). */- params?: Record<string, unknown>;- bounds: WindowBounds;- z: number;- minimized: boolean;- maximized: boolean;- // Bounds captured before a maximize, restored on un-maximize.- restoreBounds?: WindowBounds;-}--export interface OpenAppOptions {- title?: string;- bounds?: Partial<WindowBounds>;- params?: Record<string, unknown>;-}--export interface WindowManagerValue {- windows: WindowInstance[];- /** The current top window id (highest z, not minimized), or null. */- focusedId: string | null;- openApp: (appId: AppId, opts?: OpenAppOptions) => string;- close: (id: string) => void;- focus: (id: string) => void;- minimize: (id: string) => void;- /** Un-minimize and bring to front. */- restore: (id: string) => void;- toggleMaximize: (id: string) => void;- /** Patch a window's bounds (used by drag + resize). */- setBounds: (id: string, bounds: Partial<WindowBounds>) => void;- /** Set (or clear) a window's title — e.g. the Editor reflecting its active file so several open- * windows are distinguishable in the Dock + titlebar. No-op when the title is unchanged. */- setTitle: (id: string, title: string | undefined) => void;- /** Merge a patch into a window's launch params — lets an external navigation- * (e.g. the /admin/show-pages redirect) hand an already-open app a request. */- setParams: (id: string, params: Record<string, unknown>) => void;- /**- * Register (or clear, by passing null) a guard a window body uses to veto closing.- * The getter returns a confirm message when closing would lose work, else null.- */- setCloseGuard: (id: string, getMessage: (() => string | null) | null) => void;- /**- * Register (or clear, by passing null) a provider a window body uses to contribute its own- * JSON-able state to the persisted layout (e.g. the Editor's open tabs, the Terminal's tab- * titles). Read on save; the value comes back through the window's params on the next restore.- */- setStateProvider: (id: string, getState: (() => unknown) | null) => void;- /**- * Mark a window as closing (its exit animation has started but it's still mounted until- * animationEnd calls close()). Excludes it from the persisted snapshot so a reload during the- * ~300ms close animation doesn't write back — and resurrect — a window the user just closed.- */- markClosing: (id: string) => void;- /** Run a window's close guard (confirm if it has a message); true = may close. */- confirmClose: (id: string) => boolean;- /**- * True while ANY window is mid drag/resize gesture. Windows shield their body- * (iframe) with a transparent overlay while it's set, so a gesture whose pointer- * crosses an iframe can't have its events stolen by the iframe document (§7.1i).- * Set true at gesture start, false on gesture end (unconditional cleanup).- */- gestureActive: boolean;- setGestureActive: (active: boolean) => void;-}--const WindowManagerContext = createContext<WindowManagerValue | null>(null);+import { useLatestRef } from '@/lib/useLatestRef';+import {+ WindowManagerContext,+ type WindowBounds,+ type WindowInstance,+ type WindowManagerValue,+} from './WindowManagerContext';const DEFAULT_SIZE = { width: 760, height: 520 };// Cascade each new window down-right from the last so stacks stay reachable.@@ -128,6 +55,12 @@ export const WindowManagerProvider: React.FC<{ children: React.ReactNode }> = ({// Restore in the lazy initializer when the shell mounts at desktop width, so `windows` never// starts empty there (which would let the first debounced save wipe the stored layout). A shell// that mounts narrow restores later, on crossing the breakpoint (see the effect below).+ //+ // The initializer marks `restoredRef` and seeds the id/z/open sequences, which is a ref write+ // during render. It runs exactly once, before anything is mounted, and is the same bootstrap the+ // after-widen path performs from an effect; moving it out would put the first debounced save back+ // in a position to wipe the stored layout.+ // eslint-disable-next-line react-hooks/refs -- Mount-time bootstrap; see above.const [windows, setWindows] = useState<WindowInstance[]>(() => {if (!isDesktopViewport()) return [];restoredRef.current = true;@@ -135,8 +68,7 @@ export const WindowManagerProvider: React.FC<{ children: React.ReactNode }> = ({});// Latest windows for the debounced/pagehide save closures (which fire after render).- const windowsRef = useRef(windows);- windowsRef.current = windows;+ const windowsRef = useLatestRef(windows);// Per-window close guards: a body (e.g. a dirty editor) registers a getter that// returns a confirm message when closing would lose work. Held in a ref so it@@ -316,7 +248,6 @@ export const WindowManagerProvider: React.FC<{ children: React.ReactNode }> = ({restoreOnce(); // may have crossed to desktop between the initial render and this effectmql.addEventListener('change', restoreOnce);return () => mql.removeEventListener('change', restoreOnce);- // eslint-disable-next-line react-hooks/exhaustive-deps}, []);// Persist on any window-list change (open/close, geometry, z, min/max, title). Body-only state@@ -373,38 +304,3 @@ export const WindowManagerProvider: React.FC<{ children: React.ReactNode }> = ({return <WindowManagerContext.Provider value={value}>{children}</WindowManagerContext.Provider>;};--export function useWindowManager(): WindowManagerValue {- const ctx = useContext(WindowManagerContext);- if (!ctx) throw new Error('useWindowManager must be used within a WindowManagerProvider');- return ctx;-}--// A window body calls this to veto its own close while there's unsaved work: pass-// the owning window id and a confirm message (or null when clean). No-ops for a-// non-windowed (full-page) mount, where windowId is undefined.-export function useWindowCloseGuard(windowId: string | undefined, message: string | null): void {- const { setCloseGuard } = useWindowManager();- const messageRef = useRef(message);- messageRef.current = message;- useEffect(() => {- if (!windowId) return;- setCloseGuard(windowId, () => messageRef.current);- return () => setCloseGuard(windowId, null);- }, [windowId, setCloseGuard]);-}--// A window body calls this to contribute its own JSON-able state to the persisted layout, so a-// reload can restore it (Editor open tabs, Terminal tab titles). `getState` may be a fresh closure-// each render — it's held in a ref and read lazily at save time, so it always sees current state-// without re-registering. No-ops for a non-windowed (full-page) mount, where windowId is undefined.-export function useWindowState(windowId: string | undefined, getState: () => unknown): void {- const { setStateProvider } = useWindowManager();- const getStateRef = useRef(getState);- getStateRef.current = getState;- useEffect(() => {- if (!windowId) return;- setStateProvider(windowId, () => getStateRef.current());- return () => setStateProvider(windowId, null);- }, [windowId, setStateProvider]);-}diff --git a/ui/src/context/WorkbenchInboxContext.ts b/ui/src/context/WorkbenchInboxContext.tsnew file mode 100644index 000000000..2d9b4d088--- /dev/null+++ b/ui/src/context/WorkbenchInboxContext.ts@@ -0,0 +1,38 @@+import { createContext, useContext } from 'react';++import type { InboxSession } from './ApiContext';++// The Inbox state contract and the context handle every consumer reads.+// `WorkbenchInboxProvider.tsx` owns the feed, the SSE subscription and the+// writes; keeping the handle in its own component-free module lets the provider+// hot-reload on its own.+export interface InboxState {+ /** Per-session ("Slack-like") feed: one card per conversation, newest+ * activity first. Driven by realtime ``inbox.session.updated`` upserts. */+ inboxSessions: InboxSession[];+ /** Pagination-independent per-session unread counts — the sidebar badges+ * each session row from this (a session with unread may sit past the first+ * inbox page, so the feed array alone isn't a complete source). */+ unreadBySession: Record<string, number>;+ /** Sum of ``unreadBySession`` — the Inbox nav badge. */+ totalUnread: number;+ /** Number of sessions with ≥1 unread reply — the header "N unread" count. */+ unreadSessions: number;+ /** Keyset cursor for "load more"; null when the feed is fully loaded. */+ nextCursor: string | null;+ loading: boolean;+ loadingMore: boolean;+ refresh: () => Promise<void>;+ loadMore: () => Promise<void>;+ markRead: (sessionId: string, untilMessageId?: string) => Promise<void>;+}++export const WorkbenchInboxContext = createContext<InboxState | undefined>(undefined);++export const useWorkbenchInbox = (): InboxState => {+ const ctx = useContext(WorkbenchInboxContext);+ if (ctx === undefined) {+ throw new Error('useWorkbenchInbox must be used inside <WorkbenchInboxProvider>');+ }+ return ctx;+};diff --git a/ui/src/context/WorkbenchInboxContext.tsx b/ui/src/context/WorkbenchInboxProvider.tsxsimilarity index 91%rename from ui/src/context/WorkbenchInboxContext.tsxrename to ui/src/context/WorkbenchInboxProvider.tsxindex a2dcb42f3..dc8401ebf 100644--- a/ui/src/context/WorkbenchInboxContext.tsx+++ b/ui/src/context/WorkbenchInboxProvider.tsx@@ -1,35 +1,13 @@-import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import type { ReactNode } from 'react';import { useApi } from './ApiContext';import type { InboxSession } from './ApiContext';+import { WorkbenchInboxContext, type InboxState } from './WorkbenchInboxContext';import { sessionActivityInboxAction } from '../lib/inboxActivity';const PAGE_SIZE = 30;-interface InboxState {- /** Per-session ("Slack-like") feed: one card per conversation, newest- * activity first. Driven by realtime ``inbox.session.updated`` upserts. */- inboxSessions: InboxSession[];- /** Pagination-independent per-session unread counts — the sidebar badges- * each session row from this (a session with unread may sit past the first- * inbox page, so the feed array alone isn't a complete source). */- unreadBySession: Record<string, number>;- /** Sum of ``unreadBySession`` — the Inbox nav badge. */- totalUnread: number;- /** Number of sessions with ≥1 unread reply — the header "N unread" count. */- unreadSessions: number;- /** Keyset cursor for "load more"; null when the feed is fully loaded. */- nextCursor: string | null;- loading: boolean;- loadingMore: boolean;- refresh: () => Promise<void>;- loadMore: () => Promise<void>;- markRead: (sessionId: string, untilMessageId?: string) => Promise<void>;-}--const WorkbenchInboxContext = createContext<InboxState | undefined>(undefined);-// Sort matches the backend keyset order: last activity (any author) desc, then// session_id desc as the stable tie-break, so client upserts stay consistent// with server-paginated pages.@@ -352,11 +330,3 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>return <WorkbenchInboxContext.Provider value={value}>{children}</WorkbenchInboxContext.Provider>;};--export const useWorkbenchInbox = (): InboxState => {- const ctx = useContext(WorkbenchInboxContext);- if (ctx === undefined) {- throw new Error('useWorkbenchInbox must be used inside <WorkbenchInboxProvider>');- }- return ctx;-};diff --git a/ui/src/context/WorkbenchProjectsContext.ts b/ui/src/context/WorkbenchProjectsContext.tsnew file mode 100644index 000000000..41f102228--- /dev/null+++ b/ui/src/context/WorkbenchProjectsContext.ts@@ -0,0 +1,70 @@+import { createContext, useContext } from 'react';++import type { ProjectDefaultAgent, WorkbenchProject, WorkbenchSession, WorkbenchSessionCreate } from './ApiContext';++// The projects/sessions tree contract and the context handle every consumer+// reads. `WorkbenchProjectsProvider.tsx` owns the cache, the SSE subscription+// and the writes; keeping the handle in its own component-free module lets the+// provider hot-reload on its own.+export interface ProjectSessionsState {+ /** null = not loaded yet. [] = loaded-but-empty (or a first-page failure, with `error`). */+ sessions: WorkbenchSession[] | null;+ /** First-page (or retry) fetch in flight. */+ loading: boolean;+ /** Load-more (append) fetch in flight. */+ loadingMore: boolean;+ /** next_before_id: a string means more pages exist, null means fully loaded. */+ cursor: string | null;+ /** The last first-page fetch failed — any rows are kept so the user can retry. */+ error: boolean;+}++export interface WorkbenchProjectsTree {+ projects: WorkbenchProject[] | null;+ projectsError: string | null;+ refreshProjects: () => Promise<void>;++ sessionsOf: (projectId: string) => ProjectSessionsState;+ expanded: ReadonlySet<string>;+ isExpanded: (projectId: string) => boolean;+ toggleExpanded: (projectId: string) => void;+ loadMore: (projectId: string) => void;+ /** Re-fetch the first page (mobile retry button / programmatic reload). */+ reloadSessions: (projectId: string) => void;++ creatingSession: (projectId: string) => boolean;+ /** Creates a session under a project (optimistic prepend + expand) and RETURNS it;+ * the caller navigates (this provider is mounted outside the router). null on failure.+ * `overrides` lets the create surfaces pin an agent/backend; omit for the server default. */+ createSessionForProject: (projectId: string, overrides?: Partial<WorkbenchSessionCreate>) => Promise<WorkbenchSession | null>;+ /** Fork an existing session, prepend the new row to the source project, and return it for navigation. */+ forkSession: (projectId: string, sessionId: string) => Promise<WorkbenchSession | null>;+ renameProject: (projectId: string, name: string) => Promise<void>;+ /** Persist the project's default Agent route (Project Settings) and patch the+ * shared cache so the sidebar + Projects page reflect it. Pass an all-null+ * route to clear the default back to the global default. Throws on failure+ * (the apiFetch layer already surfaced a toast) so the dialog can react. */+ setProjectDefaultAgent: (+ projectId: string,+ route: ProjectDefaultAgent,+ expectedAgentId: string | null,+ ) => Promise<void>;+ archiveProject: (projectId: string) => Promise<void>;+ /** Throws on failure so the row's inline editor can fall back; patches title on success. */+ renameSession: (projectId: string, sessionId: string, title: string) => Promise<void>;+ /** Persist pin state and keep the session in the project's pinned-first order. */+ setSessionPinned: (projectId: string, sessionId: string, pinned: boolean) => Promise<void>;+ /** Permanently archive a session: calls the API (which reclaims its bound+ * tasks/watches/runs) then drops the row from the tree. Throws on failure. */+ archiveSession: (projectId: string, sessionId: string) => Promise<void>;+ /** After NewProjectDialog: dedup-by-id, hoist to top, expand, fetch sessions if not loaded. */+ upsertProjectToTop: (project: WorkbenchProject) => void;+}++export const WorkbenchProjectsContext = createContext<WorkbenchProjectsTree | null>(null);++export function useWorkbenchProjectsTree(): WorkbenchProjectsTree {+ const ctx = useContext(WorkbenchProjectsContext);+ if (!ctx) throw new Error('useWorkbenchProjectsTree must be used within a WorkbenchProjectsProvider');+ return ctx;+}diff --git a/ui/src/context/WorkbenchProjectsContext.tsx b/ui/src/context/WorkbenchProjectsProvider.tsxsimilarity index 88%rename from ui/src/context/WorkbenchProjectsContext.tsxrename to ui/src/context/WorkbenchProjectsProvider.tsxindex f40f116d6..001eafa2d 100644--- a/ui/src/context/WorkbenchProjectsContext.tsx+++ b/ui/src/context/WorkbenchProjectsProvider.tsx@@ -1,10 +1,16 @@-import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import type { ReactNode } from 'react';import { useApi } from './ApiContext';import type { ProjectDefaultAgent, WorkbenchProject, WorkbenchSession, WorkbenchSessionCreate } from './ApiContext';+import {+ WorkbenchProjectsContext,+ type ProjectSessionsState,+ type WorkbenchProjectsTree,+} from './WorkbenchProjectsContext';import { createdReconcileMinCount } from '../lib/sessionVisibilityEvents';import { orderProjectSessions } from '../lib/sessionPinning';+import { errorMessage } from '@/lib/errorMessage';// How many sessions to load per page under a project. The server clamps the// /api/sessions limit (to 200) and returns a cursor (next_before_id); both the@@ -16,19 +22,6 @@ import { orderProjectSessions } from '../lib/sessionPinning';const SESSIONS_PAGE_SIZE = 8;const RECONNECT_SESSIONS_PAGE_SIZE = 200;-export interface ProjectSessionsState {- /** null = not loaded yet. [] = loaded-but-empty (or a first-page failure, with `error`). */- sessions: WorkbenchSession[] | null;- /** First-page (or retry) fetch in flight. */- loading: boolean;- /** Load-more (append) fetch in flight. */- loadingMore: boolean;- /** next_before_id: a string means more pages exist, null means fully loaded. */- cursor: string | null;- /** The last first-page fetch failed — any rows are kept so the user can retry. */- error: boolean;-}-const EMPTY_SESSIONS: ProjectSessionsState = {sessions: null,loading: false,@@ -37,48 +30,6 @@ const EMPTY_SESSIONS: ProjectSessionsState = {error: false,};-export interface WorkbenchProjectsTree {- projects: WorkbenchProject[] | null;- projectsError: string | null;- refreshProjects: () => Promise<void>;-- sessionsOf: (projectId: string) => ProjectSessionsState;- expanded: ReadonlySet<string>;- isExpanded: (projectId: string) => boolean;- toggleExpanded: (projectId: string) => void;- loadMore: (projectId: string) => void;- /** Re-fetch the first page (mobile retry button / programmatic reload). */- reloadSessions: (projectId: string) => void;-- creatingSession: (projectId: string) => boolean;- /** Creates a session under a project (optimistic prepend + expand) and RETURNS it;- * the caller navigates (this provider is mounted outside the router). null on failure.- * `overrides` lets the create surfaces pin an agent/backend; omit for the server default. */- createSessionForProject: (projectId: string, overrides?: Partial<WorkbenchSessionCreate>) => Promise<WorkbenchSession | null>;- /** Fork an existing session, prepend the new row to the source project, and return it for navigation. */- forkSession: (projectId: string, sessionId: string) => Promise<WorkbenchSession | null>;- renameProject: (projectId: string, name: string) => Promise<void>;- /** Persist the project's default Agent route (Project Settings) and patch the- * shared cache so the sidebar + Projects page reflect it. Pass an all-null- * route to clear the default back to the global default. Throws on failure- * (the apiFetch layer already surfaced a toast) so the dialog can react. */- setProjectDefaultAgent: (- projectId: string,- route: ProjectDefaultAgent,- expectedAgentId: string | null,- ) => Promise<void>;- archiveProject: (projectId: string) => Promise<void>;- /** Throws on failure so the row's inline editor can fall back; patches title on success. */- renameSession: (projectId: string, sessionId: string, title: string) => Promise<void>;- /** Persist pin state and keep the session in the project's pinned-first order. */- setSessionPinned: (projectId: string, sessionId: string, pinned: boolean) => Promise<void>;- /** Permanently archive a session: calls the API (which reclaims its bound- * tasks/watches/runs) then drops the row from the tree. Throws on failure. */- archiveSession: (projectId: string, sessionId: string) => Promise<void>;- /** After NewProjectDialog: dedup-by-id, hoist to top, expand, fetch sessions if not loaded. */- upsertProjectToTop: (project: WorkbenchProject) => void;-}-// Scan every project's loaded rows for a session id and apply `patch`; returns a// new state only when something actually changed (so unrelated consumers don't// re-render). Used for both the status-dot and title SSE patches — keyed on@@ -138,8 +89,6 @@ function removeSessionRow(const REORDER_ACTIVITY_EVENTS = new Set(['created', 'user_message', 'show_event']);-const WorkbenchProjectsContext = createContext<WorkbenchProjectsTree | null>(null);-// Single source of truth for the workbench projects/sessions tree. The desktop// WorkbenchSidebar (always mounted) and the mobile ProjectsPage (route) both// consume it, so it's a PROVIDER (one EventSource + one cache) rather than a@@ -207,10 +156,10 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ csetProjects(result.projects);applyBootstrapSessions(result.sessions ?? {});setProjectsError(null);- } catch (err: any) {+ } catch (err) {// Don't strand consumers on an empty-state for a transient failure — keep// any list we had and surface the error (mobile shows a retry).- setProjectsError(err?.message ?? String(err));+ setProjectsError(errorMessage(err) ?? String(err));}}, [api, applyBootstrapSessions]);@@ -324,8 +273,8 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ cfor (const projectId of largeProjectIds) {void reconcileSessions(projectId);}- } catch (err: any) {- setProjectsError(err?.message ?? String(err));+ } catch (err) {+ setProjectsError(errorMessage(err) ?? String(err));const projectIds = [...bootstrapGroups.values()].flat();for (const projectId of [...projectIds, ...largeProjectIds]) {void reconcileSessions(projectId);@@ -742,9 +691,3 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ creturn <WorkbenchProjectsContext.Provider value={value}>{children}</WorkbenchProjectsContext.Provider>;};--export function useWorkbenchProjectsTree(): WorkbenchProjectsTree {- const ctx = useContext(WorkbenchProjectsContext);- if (!ctx) throw new Error('useWorkbenchProjectsTree must be used within a WorkbenchProjectsProvider');- return ctx;-}diff --git a/ui/src/context/apiErrorParse.ts b/ui/src/context/apiErrorParse.tsnew file mode 100644index 000000000..42406a85c--- /dev/null+++ b/ui/src/context/apiErrorParse.ts@@ -0,0 +1,56 @@+// Pure parsing of an API error body. Lives outside ApiContext so the response+// contract stays unit-testable without mounting a provider (see ApiErrorParse.test.ts);+// ``handleApiError`` is the only place that turns these answers into side effects.++/** Pick the machine code + human fallback out of an error response body.+ *+ * Accepts the legacy ``error`` shape (a bare string, or ``{ code, message }``) AND the+ * top-level ``{ code, message }`` shape newer routes use (e.g. /api/vault/*), so callers+ * always get a real ``ApiError.code`` to branch on instead of a generic status string.+ *+ * Note the precedence, which is a CONTRACT for route authors: ``error`` is consulted+ * first, and a STRING ``error`` is taken as the code — so a route that pairs a human+ * sentence in ``error`` with the real code alongside it in a top-level ``code`` loses that+ * code here, and its message is rendered verbatim in every locale. Routes with a machine+ * code must nest it: ``{"error": {"code", "message"}}`` (see ``_show_page_error_response``+ * in ``vibe/ui_server.py``). Extracted from ``handleApiError`` unchanged so that contract+ * is directly testable — see ApiErrorParse.test.ts. */+export const selectApiErrorFields = (+ data: any,+ defaultMessage: string,+): { code: string | null; fallback: string } | null => {+ // Not ``data?.error``: a non-object JSON body (``null``) must keep THROWING here so+ // handleApiError's catch falls back to the status text, exactly as before.+ const rawErr = data.error ?? (data.code ? { code: data.code, message: data.message } : undefined);+ if (!rawErr) return null;+ const code = typeof rawErr === 'string' ? rawErr : rawErr?.code;+ const fallback = typeof rawErr === 'string' ? rawErr : rawErr?.message ?? rawErr?.code ?? defaultMessage;+ return { code: typeof code === 'string' ? code : null, fallback };+};++/** Which session an error response says is archived, or ``null`` if it says no such+ * thing. The WHOLE decision — the code guard and the id lookup — so it is testable+ * without a DOM (this repo has no DOM test environment; same reason+ * ``selectApiErrorFields`` was extracted). ``handleApiError`` only fans the answer+ * out to subscribers.+ *+ * Every route that can answer ``409 session_archived`` puts the session id in the+ * first segment after its collection: ``/api/sessions/<id>`` (PATCH), plus+ * ``/messages`` and ``/fork`` under it, and ``/api/show-pages/<session_id>/…``+ * (ensure / visibility / share-id / rotate-share / icon). One pattern therefore+ * covers all of them, and a future session-scoped route inherits it.+ *+ * Deliberately UNANCHORED: some callers pass a human LABEL rather than a bare+ * path (``updateSession`` sends ``"PATCH /api/sessions/<id>"``), and that label+ * belongs to the very route this convergence was added for. */+export const archivedConflictSessionId = (code: string | null, path: string): string | null => {+ if (code !== 'session_archived') return null;+ const match = /\/api\/(?:sessions|show-pages)\/([^/?#\s]+)/.exec(path);+ if (!match) return null;+ try {+ return decodeURIComponent(match[1]) || null;+ } catch {+ // A malformed escape must not throw inside an error handler.+ return match[1] || null;+ }+};diff --git a/ui/src/context/DockContext.test.ts b/ui/src/context/dockDoc.test.tssimilarity index 99%rename from ui/src/context/DockContext.test.tsrename to ui/src/context/dockDoc.test.tsindex 7d14b06e5..53a7ec81a 100644--- a/ui/src/context/DockContext.test.ts+++ b/ui/src/context/dockDoc.test.ts@@ -7,7 +7,7 @@ import {seedDefaultDock,showDockId,type DockDoc,-} from './DockContext';+} from './dockDoc';const BUILTINS = ['files', 'terminal', 'editor'];diff --git a/ui/src/context/dockDoc.ts b/ui/src/context/dockDoc.tsnew file mode 100644index 000000000..f4d40e986--- /dev/null+++ b/ui/src/context/dockDoc.ts@@ -0,0 +1,105 @@+import { APP_LIST } from '../apps/registry';++// The shape of the workbench Dock document and the pure rules that canonicalize+// it. `DockContext.tsx` owns the fetch/optimistic-write side; everything here is+// I/O-free so the shared contract stays unit-testable (see dockDoc.test.ts).+//+// The Dock is durable, cross-device *product* state (see core/dock_store.py).+// Two layers (§7.1c): `pins` is the INSTALLED set of AI Show Pages (built-ins are+// implicitly installed); `order` is the DOCKED subset — the resident tiles, in+// user order, a SUBSET of the known ids.+//+// A Dock item id is either a built-in app id verbatim (`files` / `terminal` /+// `editor` / `library`) or a pinned Show Page as `show:<session_id>`. The+// built-in id set and its canonical order are a contract shared with the+// backend's BUILTIN_DOCK_IDS — both derive from APP_LIST, so keep them in sync.+// Any tile, built-ins included, can be undocked (absent from `order`); the empty+// Dock is a valid state.++export type DockPin = {+ session_id: string;+ title_snapshot: string;+ pinned_at: string;+};++export type DockDoc = {+ order: string[];+ pins: DockPin[];+};++export const SHOW_DOCK_PREFIX = 'show:';++// Fixed defensive cap on PINNED Show Pages, mirroring core/dock_store.py's+// MAX_PINNED_PAGES. reconcile clamps pins to this FIXED budget (independent of+// the built-in count) so a corrupt/oversized doc stays bounded AND adding a+// built-in never shrinks the budget or drops an existing valid pin on reconcile.+export const MAX_PINNED_PAGES = 197;++/** The Dock id for a pinned Show Page session. */+export function showDockId(sessionId: string): string {+ return `${SHOW_DOCK_PREFIX}${sessionId}`;+}++/** The session id inside a `show:<id>` Dock id, or null for a non-Show item. */+export function dockIdToSession(dockId: string): string | null {+ return dockId.startsWith(SHOW_DOCK_PREFIX) ? dockId.slice(SHOW_DOCK_PREFIX.length) : null;+}++// The resident built-in tiles, in canonical order. Mirrors the backend+// BUILTIN_DOCK_IDS; `preview` is intentionally absent (opened on demand, never+// resident), exactly like `showpage`.+export const BUILTIN_DOCK_IDS: string[] = APP_LIST.map((app) => app.id);++/**+ * Canonicalize a Dock document against the known built-in ids — the same rule+ * the server applies (core/dock_store._reconcile), so a stale or partial doc+ * from either side converges to one shape:+ * - dedupe pins by session id (first wins);+ * - clamp pins to the fixed install budget;+ * - drop unknown / duplicate ids from `order`.+ * The order is left as the stored SUBSET — built-ins and pins are NOT+ * force-appended (§7.1c), so an undocked tile stays undocked and the empty Dock+ * round-trips. Pure: no I/O, safe to unit-test and to run on every read.+ */+export function reconcileDock(doc: DockDoc | null | undefined, builtinIds: string[] = BUILTIN_DOCK_IDS): DockDoc {+ const pins: DockPin[] = [];+ const seenPins = new Set<string>();+ for (const pin of doc?.pins ?? []) {+ if (!pin || typeof pin.session_id !== 'string' || !pin.session_id || seenPins.has(pin.session_id)) continue;+ seenPins.add(pin.session_id);+ pins.push({+ session_id: pin.session_id,+ title_snapshot: typeof pin.title_snapshot === 'string' ? pin.title_snapshot : '',+ pinned_at: typeof pin.pinned_at === 'string' ? pin.pinned_at : '',+ });+ }++ // Clamp on read (mirrors the backend): built-ins are always kept; excess pins+ // beyond the FIXED pin budget are dropped so a corrupt/oversized doc stays+ // bounded (the budget doesn't shrink when a built-in is added).+ const maxPins = MAX_PINNED_PAGES;+ const clampedPins = pins.length > maxPins ? pins.slice(0, maxPins) : pins;++ const pinIds = clampedPins.map((pin) => showDockId(pin.session_id));+ const known = new Set<string>([...builtinIds, ...pinIds]);++ const order: string[] = [];+ const seen = new Set<string>();+ for (const id of doc?.order ?? []) {+ if (known.has(id) && !seen.has(id)) {+ order.push(id);+ seen.add(id);+ }+ }+ return { order, pins: clampedPins };+}++/**+ * The pre-load default Dock: every built-in docked, nothing installed — matching+ * the server's seed for a fresh instance. Used only as the initial state before+ * the server document loads (avoids a flash of an empty Dock); once the GET+ * resolves, reconcileDock takes over and an undocked built-in stays undocked.+ */+export function seedDefaultDock(builtinIds: string[] = BUILTIN_DOCK_IDS): DockDoc {+ return { order: [...builtinIds], pins: [] };+}diff --git a/ui/src/lib/errorMessage.test.ts b/ui/src/lib/errorMessage.test.tsnew file mode 100644index 000000000..29bffd75c--- /dev/null+++ b/ui/src/lib/errorMessage.test.ts@@ -0,0 +1,36 @@+import { describe, expect, it } from 'vitest';+import { errorMessage } from './errorMessage';++describe('errorMessage', () => {+ it('reads the message off an Error', () => {+ expect(errorMessage(new Error('boom'))).toBe('boom');+ });++ it('reads the message off any object that carries one', () => {+ expect(errorMessage({ message: 'rejected by server' })).toBe('rejected by server');+ });++ it('keeps an empty message so callers can choose between ?? and ||', () => {+ // `?? fallback` must keep '' and `|| fallback` must replace it — that choice+ // belongs to the call site, so the helper must not collapse the two.+ expect(errorMessage(new Error(''))).toBe('');+ });++ it('returns undefined for a thrown value with no message', () => {+ expect(errorMessage({ code: 'E_NOPE' })).toBeUndefined();+ expect(errorMessage('boom')).toBeUndefined();+ expect(errorMessage(42)).toBeUndefined();+ });++ it('returns undefined for nullish throws instead of dereferencing them', () => {+ expect(errorMessage(null)).toBeUndefined();+ expect(errorMessage(undefined)).toBeUndefined();+ });++ it('returns undefined when message is present but not a string', () => {+ // The old `catch (err: any)` sites would have assigned a number straight+ // into string state; falling back to the caller's message is safer.+ expect(errorMessage({ message: 42 })).toBeUndefined();+ expect(errorMessage({ message: { nested: true } })).toBeUndefined();+ });+});diff --git a/ui/src/lib/errorMessage.ts b/ui/src/lib/errorMessage.tsnew file mode 100644index 000000000..9002c2d59--- /dev/null+++ b/ui/src/lib/errorMessage.ts@@ -0,0 +1,19 @@+/**+ * Read the `message` of an unknown thrown value.+ *+ * A `catch` binding is `unknown`, so reaching `.message` needs a guard. The+ * codebase used to spell that guard as `catch (err: any)`, which typed away the+ * problem instead of solving it and let a non-string `message` land in string+ * state.+ *+ * The helper deliberately stops at *reading* the message and returns+ * `undefined` when there is none. Choosing what to show instead stays at the+ * call site, because the two fallbacks are not interchangeable:+ *+ * - `errorMessage(err) ?? fallback` keeps an empty message as an empty string+ * - `errorMessage(err) || fallback` replaces an empty message with the fallback+ */+export function errorMessage(err: unknown): string | undefined {+ const message = (err as { message?: unknown } | null | undefined)?.message;+ return typeof message === 'string' ? message : undefined;+}diff --git a/ui/src/lib/mentions.ts b/ui/src/lib/mentions.tsindex 9cceeef5f..5deac2ccb 100644--- a/ui/src/lib/mentions.ts+++ b/ui/src/lib/mentions.ts@@ -57,7 +57,7 @@ export function dedupeReferences(refs: MentionReference[]): MentionReference[] {}function escapeMarkdownLabel(value: string): string {- return value.replace(/[\\\[\]]/g, (m) => `\\${m}`).replace(/\s*\n\s*/g, ' ');+ return value.replace(/[\\[\]]/g, (m) => `\\${m}`).replace(/\s*\n\s*/g, ' ');}/**diff --git a/ui/src/lib/useLatestRef.test.tsx b/ui/src/lib/useLatestRef.test.tsxnew file mode 100644index 000000000..1e2ad6b13--- /dev/null+++ b/ui/src/lib/useLatestRef.test.tsx@@ -0,0 +1,48 @@+import { useState } from 'react';+import { renderToStaticMarkup } from 'react-dom/server';+import { describe, expect, it } from 'vitest';++import { useLatestRef } from './useLatestRef';++describe('useLatestRef', () => {+ it('exposes the value of the current render, not of the previous one', () => {+ // A render-phase state update makes React re-render this component+ // immediately, before anything commits. The second pass is where the two+ // possible implementations diverge: writing during render reports 1,+ // deferring the write to an effect would still report the initial 0,+ // because no effect has run yet. Every caller reads the ref from a+ // listener or effect that fires after this point, so "already current in+ // the render that produced the new value" is the property they rely on.+ function Probe() {+ const [n, setN] = useState(0);+ const latest = useLatestRef(n);+ if (n === 0) setN(1);+ return <span>{`n=${n} ref=${latest.current}`}</span>;+ }++ expect(renderToStaticMarkup(<Probe />)).toBe('<span>n=1 ref=1</span>');+ });++ it('starts at the first value handed to it', () => {+ function Probe({ label }: { label: string }) {+ const latest = useLatestRef(label);+ return <span>{latest.current}</span>;+ }++ expect(renderToStaticMarkup(<Probe label="initial" />)).toBe('<span>initial</span>');+ });++ it('tracks a value that is not a string, by identity', () => {+ const first = { id: 1 };+ const second = { id: 2 };++ function Probe() {+ const [current, setCurrent] = useState(first);+ const latest = useLatestRef(current);+ if (current === first) setCurrent(second);+ return <span>{latest.current === second ? 'second' : 'stale'}</span>;+ }++ expect(renderToStaticMarkup(<Probe />)).toBe('<span>second</span>');+ });+});diff --git a/ui/src/lib/useLatestRef.ts b/ui/src/lib/useLatestRef.tsnew file mode 100644index 000000000..0d8a2827c--- /dev/null+++ b/ui/src/lib/useLatestRef.ts@@ -0,0 +1,44 @@+import { useRef, type RefObject } from 'react';++/**+ * A ref that always holds the latest `value`, for readers that run *outside*+ * render: effects, subscriptions, timers, event listeners, async callbacks.+ *+ * Twelve call sites had spelled this out by hand as+ *+ * ```ts+ * const handlerRef = useRef(onPaste);+ * handlerRef.current = onPaste;+ * ```+ *+ * so that a long-lived listener can call the newest callback without the+ * effect re-subscribing on every prop change. The write happens during render,+ * which `react-hooks/refs` flags — correctly in general, because a component+ * that *renders* from a ref will not re-render when it changes.+ *+ * This helper keeps that write during render on purpose, and is the only place+ * in the UI where the rule is exempted:+ *+ * - The write is idempotent and invisible to the render output, so a double+ * invocation under StrictMode or a discarded concurrent render is harmless.+ * - Deferring it to an effect would be a behaviour change, not a cleanup: the+ * ref would still hold the previous value while children's effects run, and+ * during the render itself.+ *+ * The contract is therefore "current *now*, in this render", and+ * `useLatestRef.test.tsx` pins it.+ *+ * One thing the linter cannot do for you: it does not see through this hook, so+ * reading the returned `.current` *during render* at a call site is not flagged+ * the way reading a plain `useRef` is. That read is still wrong — the component+ * will not re-render when the value changes. Read it from effects, listeners,+ * timers and async callbacks only. `scripts/eslintConventions.test.mjs` pins+ * that the rule itself is still on for the ordinary case, so the exemption above+ * stays one line rather than becoming a config-wide relaxation.+ */+export function useLatestRef<T>(value: T): RefObject<T> {+ const ref = useRef(value);+ // eslint-disable-next-line react-hooks/refs -- The point of the helper; see above.+ ref.current = value;+ return ref;+}diff --git a/ui/src/lib/usePendingVaultRequests.ts b/ui/src/lib/usePendingVaultRequests.tsindex fd365fa14..296c75b92 100644--- a/ui/src/lib/usePendingVaultRequests.ts+++ b/ui/src/lib/usePendingVaultRequests.ts@@ -2,6 +2,7 @@ import { useCallback, useEffect, useRef, useState } from 'react';import { useApi, type VaultRequest } from '@/context/ApiContext';import { useVaultRequestRefresh } from '@/lib/useVaultRequestRefresh';+import { useLatestRef } from './useLatestRef';/*** Pending vault requests (access/sign/provision) for one chat session. Fed by@@ -18,8 +19,7 @@ export function usePendingVaultRequests(sessionId: string): { requests: VaultReqconst loadSeq = useRef(0);// Latest requested session, updated synchronously during render so an async load resolving after// a switch (its effect hasn't bumped the token yet) is still rejected.- const currentSessionRef = useRef(sessionId);- currentSessionRef.current = sessionId;+ const currentSessionRef = useLatestRef(sessionId);// Reset stale rows *during render* (not a post-commit effect) so switching from session A to B// never paints A's cards/float for a frame — the hook state now outlives the switch. This is