A local-first multi-agent app development platform, built on PenguinHarness
test(web): behaviour-first sessions and sidebar suite, shared storage and fetch fakes (#918)
Yaowei Zhengaace20976e39
diff --git a/.gitignore b/.gitignoreindex 028a558f..e2f3fd78 100644--- a/.gitignore+++ b/.gitignore@@ -29,6 +29,9 @@ cache/.agents/settings.local.json.agents/**/*.local.*+# vitest --coverage reports+coverage/+# playwright e2e artifactspackages/web/test-results/# component gallery screenshots (scripts/shots.mjs); never committeddiff --git a/.prettierignore b/.prettierignoreindex 928b82bc..e17f6912 100644--- a/.prettierignore+++ b/.prettierignore@@ -19,6 +19,9 @@ packages/ui/src/fonts/misans/specs/*.md+# vitest --coverage reports+coverage/+# Playwright e2e artifactstest-results/playwright-report/diff --git a/packages/web/package.json b/packages/web/package.jsonindex 1e10e3f8..ee65d01d 100644--- a/packages/web/package.json+++ b/packages/web/package.json@@ -35,6 +35,7 @@"@types/react": "^19.1.0","@types/react-dom": "^19.1.0","@vitejs/plugin-react": "^4.5.0",+ "@vitest/coverage-v8": "3.2.7","tailwindcss": "^4.1.0","typescript": "^5.6.0","vite": "^7.0.0",diff --git a/packages/web/test/account-menu.test.ts b/packages/web/test/account-menu.test.tsindex 1a0e0394..e19663dc 100644--- a/packages/web/test/account-menu.test.ts+++ b/packages/web/test/account-menu.test.ts@@ -1,20 +1,14 @@/**- * account-menu.ts unit tests: which sessions the account menu offers a- * change-password entry to.+ * Which account controls a session is offered (lib/account-menu.ts), decided by the pair of+ * the server's desktop mode and how the session signed in — never by either alone.*- * The rule is pinned by value in all four combinations rather than by shape, because the- * tempting simplification — keying on `desktopMode` alone, like the sibling sign-out and- * Users entries do — is wrong in a way nothing else would catch: it also strips the- * control from a browser signed in against a desktop-mode server over loopback, whose- * password session can still change its password (server/test/desktop.test.ts, "keeps- * requiring oldPassword for password-established sessions in desktop mode").- *- * vitest runs node-only here (`environment: "node"`, no jsdom), so this asserts against the- * exported predicate rather than a rendered menu (title-reveal.test.ts convention).+ * - Only the desktop shell's own window counts as the shell's window.+ * - Change password is hidden in exactly one state, the shell's own window; a browser signed+ * into a desktop-mode server and a desktop cookie replayed against a plain server keep it.+ * - The initial-password nag stays quiet in any window the shell signed in.+ * - The current-password field is omitted for the shell's own window and first-login+ * sessions, and kept for a desktop session against a server no shell spawned.*/-import { readFileSync } from "node:fs";-import { dirname, resolve } from "node:path";-import { fileURLToPath } from "node:url";import { describe, expect, it } from "vitest";import {isDesktopShellWindow,@@ -38,25 +32,21 @@ describe("isDesktopShellWindow", () => {});describe("offersChangePassword", () => {- it("hides it in the desktop shell's own window — no login form, seed password never shown", () => {- expect(offersChangePassword({ desktopMode: true, sessionVia: "desktop" })).toBe(false);- });-- it("offers it on an ordinary multi-user server reached from a browser", () => {- expect(offersChangePassword({ desktopMode: false, sessionVia: "password" })).toBe(true);- });-- it("offers it to a browser signed into a desktop-mode server over loopback", () => {- // That session typed a real password at the login form; the server still lets it- // change one, so hiding the entry would strand it.- expect(offersChangePassword({ desktopMode: true, sessionVia: "password" })).toBe(true);- });-- it("offers it to a desktop cookie replayed against a plain server on the same data root", () => {- // The shared data root makes this reachable, and there the server requires the old- // password like any other session — so the control is live and must stay visible.- expect(offersChangePassword({ desktopMode: false, sessionVia: "desktop" })).toBe(true);- });+ // The shell's own window has no login form and never shows the seed password. A browser+ // that typed a real password into a desktop-mode server over loopback can still change it,+ // and so can a desktop cookie replayed against a plain server on the same data root, where+ // the server requires the old password like any other session.+ it.each([+ [true, "desktop", false],+ [false, "password", true],+ [true, "password", true],+ [false, "desktop", true],+ ] as const)(+ "desktopMode %s, signed in via %s: offered %s",+ (desktopMode, sessionVia, offered) => {+ expect(offersChangePassword({ desktopMode, sessionVia })).toBe(offered);+ },+ );});describe("nagsAboutInitialPassword", () => {@@ -91,105 +81,4 @@ describe("omitsOldPassword", () => {// reset-admin-password`, not from this form.expect(omitsOldPassword({ desktopMode: false, sessionVia: "desktop" })).toBe(false);});-- it("is hidden in exactly one of the four states", () => {- const states = [true, false].flatMap((desktopMode) =>- (["password", "desktop"] as const).map((sessionVia) => ({ desktopMode, sessionVia })),- );- expect(states.filter((s) => !offersChangePassword(s))).toEqual([- { desktopMode: true, sessionVia: "desktop" },- ]);- });-});--describe("the settings section registry", () => {- const source = readFileSync(- resolve(dirname(fileURLToPath(import.meta.url)), "../src/lib/settings-sections.ts"),- "utf8",- );-- it("gates the account page on the predicate rather than listing it always", () => {- // The change-password row moved from the sidebar menu into the settings dialog; the- // predicate now decides whether that page exists at all. Without this the predicate- // could pass every test above while the registry ignored it.- expect(source).toContain("offersChangePassword(v)");- });-});--describe("the account menu", () => {- // One menu, two anchors: the pinned sidebar's user row and the collapsed rail's avatar- // both render this component, so the rows below are asserted once, where they live.- const source = readFileSync(- resolve(dirname(fileURLToPath(import.meta.url)), "../src/components/layout/user-menu.tsx"),- "utf8",- );-- it("keeps sign-out on its own desktopMode gate", () => {- // Sign out is hidden for the whole desktop-mode server, not just the shell's window.- // Anchored to sign-out's own block: the server update row above it carries the same- // gate, so a bare `toContain("{!desktopMode && (")` would keep passing once this one- // was deleted.- const signOut = source.indexOf("S.auth.logout");- expect(signOut).toBeGreaterThan(-1);- const gate = source.lastIndexOf("{!desktopMode && (", signOut);- expect(gate).toBeGreaterThan(-1);- // Only sign-out's own <MenuItem> stands between that gate and the label it renders.- expect(source.slice(gate, signOut).match(/<\w+/g)).toEqual(["<MenuItem"]);- });-- it("confirms before signing out, from a dialog the closing menu cannot take with it", () => {- // The row opens the confirmation; only the dialog's Confirm ends the session. A direct- // logout() back on the row is the regression worth naming: sign-out sits in a menu of- // otherwise harmless entries, where one slip used to land on the login page.- const signOut = source.indexOf("S.auth.logout");- const row = source.slice(source.lastIndexOf("{!desktopMode && (", signOut), signOut);- expect(row).toContain("setConfirmingLogout(true)");- expect(row).not.toContain("logout()");- // And the dialog is mounted OUTSIDE the dropdown, the property the comment beside it- // claims: the panel's children unmount the moment the menu closes, and the row closes- // the menu as it opens the dialog — moved inside, the confirmation would never appear.- const menuEnd = source.indexOf("</Dropdown>");- expect(menuEnd).toBeGreaterThan(-1);- expect(source.indexOf("<ConfirmModal")).toBeGreaterThan(menuEnd);- });-- it("reaches the settings it no longer holds through one ungated Settings entry", () => {- // The preference rows, change password and user management all moved into the settings- // dialog, whose own section registry decides which pages this viewer sees — so the row- // itself carries no isAdmin test, or a non-admin would lose the personal pages along- // with the admin ones.- expect(source).toContain("setSettingsOpen(true)");- expect(source).not.toContain("offersChangePassword");- expect(source).not.toContain("S.settings.language");- expect(source).not.toContain("S.settings.theme");- expect(source).not.toContain('go("/settings")');- expect(source).not.toContain('go("/admin/users")');- });-- it("mounts no dialog for a surface the settings dialog owns", () => {- // A stale mount would be a build failure rather than a silent one, but the menu- // keeping an opener for a surface reachable elsewhere is the regression worth naming.- expect(source).not.toContain("ProxySettingsDialog");- expect(source).not.toContain("UploadLimitsDialog");- expect(source).not.toContain("ChangePasswordDialog");- });-- it("keeps the one update row outside the settings dialog, opening the modal the layout mounts", () => {- // Updating is deliberately not a settings page: the menu carries the entry itself. One- // row serves both backends (the server release, the shell's own updater in the desktop- // window) and hides itself where the session can update nothing; every click opens the- // update modal, which is mounted by the app layout — not here, where the menu closing on- // that same click would unmount it, and not on the draft page whose badge opens it too.- expect(source).toContain("<UpdateRow");- expect(source).toContain("openUpdateModal()");- expect(source).not.toContain("<UpdateModal");- expect(source).not.toContain("ServerUpdateRow");- expect(source).not.toContain("DesktopUpdateRow");- });-- it("leaves the font credit to the Settings dialog's credits page", () => {- // The MiSans credit moved to Settings → Credits, which every account can open; the menu- // keeps no second copy of it.- expect(source).not.toContain("fontCredit");- });});diff --git a/packages/web/test/agent-handoff.test.ts b/packages/web/test/agent-handoff.test.tsindex 07962910..9f8edfd3 100644--- a/packages/web/test/agent-handoff.test.ts+++ b/packages/web/test/agent-handoff.test.ts@@ -1,21 +1,17 @@/**- * agent-handoff.ts unit tests: the `/agent` picker's candidate filtering, the staged-switch- * send decision (`/agent` and `/model` only act on Enter — this is where "act on what, and- * when" is pinned down), and the re-export wiring for the origin marker blocks (their own- * semantics — both forms, anchoring, legacy compat — are covered by- * packages/core/test/markers.test.ts).+ * The `/agent` and `/model` chips (features/chat/agent-handoff.ts). The origin marker blocks+ * it re-exports are core's, tested in packages/core/test/markers.test.ts.+ *+ * - The `/agent` picker's search matches any part of an Agent's id or name, case-insensitively;+ * an empty query lists every candidate and a query matching nothing lists none.+ * - A staged chip acts only on send: with nothing staged the message is an ordinary post; a+ * staged handoff opens the new chat whatever this session is doing; a staged model fork goes+ * out only while the session is idle and is blocked (never degraded into a post) otherwise;+ * where no fork is possible the chip cannot block a send; with both chips, the handoff wins.*/import { describe, expect, it } from "vitest";import type { AgentSummary } from "@prismshadow/penguin-server/api";-import {- filterAgents,- handoffMessage,- modelSwitchMessage,- parseHandoffMessage,- parseModelSwitchMessage,- parseScheduledMessage,- stagedSendRoute,-} from "../src/features/chat/agent-handoff";+import { filterAgents, stagedSendRoute } from "../src/features/chat/agent-handoff";const agent = (agentId: string, name?: string): AgentSummary => ({agentId,@@ -116,28 +112,3 @@ describe("stagedSendRoute (what a staged /agent or /model chip does on send)", (expect(route({ handoffTarget: true, pendingModel: true, sessionBusy: true })).toBe("handoff");});});--describe("origin marker blocks are re-exported from core", () => {- it("handoff / model-switch producers emit the square form and round-trip through the feature module", () => {- const handoff = handoffMessage({ agentId: "default_agent", workspace: "/data/ws" });- expect(handoff.startsWith("[handoff_from]\n")).toBe(true);- expect(parseHandoffMessage(handoff)).toEqual({- agentId: "default_agent",- workspace: "/data/ws",- });- const switched = modelSwitchMessage({ sessionId: "session-01", tracePath: "/t.jsonl" });- expect(switched.startsWith("[model_switch_from]\n")).toBe(true);- expect(parseModelSwitchMessage(switched)).toEqual({- sessionId: "session-01",- tracePath: "/t.jsonl",- });- });-- it("the scheduled-task parser (server-produced block) is reachable here for the banner", () => {- expect(- parseScheduledMessage(- "[scheduled_task]\nschedule: daily\nfired_at: 2026-01-01T00:00:00Z\n[/scheduled_task]\n\nbody",- ),- ).toEqual({ origin: { name: "daily", firedAt: "2026-01-01T00:00:00Z" }, rest: "body" });- });-});diff --git a/packages/web/test/agent-settings-options.test.ts b/packages/web/test/agent-settings-options.test.tsdeleted file mode 100644index 4f5727cc..00000000--- a/packages/web/test/agent-settings-options.test.ts+++ /dev/null@@ -1,35 +0,0 @@-/**- * agent-settings-page.ts optionRows unit tests: the runtime dropdowns build from the- * dictionary's [value, description] pairs with the "" (inherit) row dropped and dictionary- * order kept — pinned so a future reconciliation (e.g. with the no-none branch's option- * assembly) cannot silently regress the filter.- */-import { describe, expect, it } from "vitest";-import { optionRows } from "../src/features/agents/agent-settings-page";--const ENTRIES: ReadonlyArray<readonly [string, string]> = [- ["", "Send no override."],- ["low", "Low tier."],- ["medium", "Medium tier."],- ["high", "High tier."],- ["xhigh", "Extra-high tier."],- ["max", "Max tier."],-];--describe("optionRows", () => {- it("drops the '' inherit row and keeps dictionary order", () => {- const rows = optionRows(ENTRIES);- expect(rows.map((r) => r.value)).toEqual(["low", "medium", "high", "xhigh", "max"]);- expect(rows.some((r) => r.value === "")).toBe(false);- });-- it("maps value into both labels and carries the description through", () => {- const rows = optionRows([["summarize", "Summarize old context."]]);- expect(rows[0]).toEqual({- value: "summarize",- triggerLabel: "summarize",- label: "summarize",- description: "Summarize old context.",- });- });-});diff --git a/packages/web/test/agent-settings-page.test.ts b/packages/web/test/agent-settings-page.test.tsnew file mode 100644index 00000000..d8f1734e--- /dev/null+++ b/packages/web/test/agent-settings-page.test.ts@@ -0,0 +1,62 @@+/**+ * The Agent settings page's pure helpers (features/agents/agent-settings-page.tsx). One file,+ * so the page module is imported once.+ *+ * - A runtime dropdown is built from the dictionary's [value, description] pairs in dictionary+ * order, the "" inherit row dropped, each value labelling both the trigger and the row and+ * the description carried through.+ * - The `?tab=` deep link passes a known tab key through and falls back to the default for an+ * absent, empty, unknown or wrong-cased value, judged against the live tab list rather than a+ * hard-coded one.+ */+import { describe, expect, it } from "vitest";+import { optionRows, resolveTabKey } from "../src/features/agents/agent-settings-page";++const ENTRIES: ReadonlyArray<readonly [string, string]> = [+ ["", "Send no override."],+ ["low", "Low tier."],+ ["medium", "Medium tier."],+ ["high", "High tier."],+ ["xhigh", "Extra-high tier."],+ ["max", "Max tier."],+];++describe("optionRows", () => {+ it("drops the '' inherit row and keeps dictionary order", () => {+ const rows = optionRows(ENTRIES);+ expect(rows.map((r) => r.value)).toEqual(["low", "medium", "high", "xhigh", "max"]);+ expect(rows.some((r) => r.value === "")).toBe(false);+ });++ it("maps value into both labels and carries the description through", () => {+ const rows = optionRows([["summarize", "Summarize old context."]]);+ expect(rows[0]).toEqual({+ value: "summarize",+ triggerLabel: "summarize",+ label: "summarize",+ description: "Summarize old context.",+ });+ });+});++const TABS = [{ key: "overview" }, { key: "tools" }, { key: "vault" }] as const;++describe("resolveTabKey", () => {+ it("passes a known tab key through", () => {+ expect(resolveTabKey("tools", TABS, "overview")).toBe("tools");+ expect(resolveTabKey("vault", TABS, "overview")).toBe("vault");+ });++ it("falls back for absent, empty, unknown, or wrong-cased values", () => {+ expect(resolveTabKey(null, TABS, "overview")).toBe("overview");+ expect(resolveTabKey("", TABS, "overview")).toBe("overview");+ expect(resolveTabKey("bogus", TABS, "overview")).toBe("overview");+ expect(resolveTabKey("Tools", TABS, "overview")).toBe("overview");+ });++ it("validates against the supplied keys, not a hardcoded list", () => {+ expect(resolveTabKey("skills", [...TABS, { key: "skills" }], "overview")).toBe("skills");+ expect(resolveTabKey("hooks", TABS, "overview")).toBe("overview");+ expect(resolveTabKey("hooks", [...TABS, { key: "hooks" }], "overview")).toBe("hooks");+ });+});diff --git a/packages/web/test/agent-settings-tab.test.ts b/packages/web/test/agent-settings-tab.test.tsdeleted file mode 100644index 1d492baf..00000000--- a/packages/web/test/agent-settings-tab.test.ts+++ /dev/null@@ -1,30 +0,0 @@-/**- * agent-settings-page.tsx resolveTabKey unit tests: the settings page's `?tab=` deep link- * narrows an untrusted query value against the live TABS keys — a known key passes through,- * anything else (absent, empty, unknown, wrong casing) falls back to the default — pinned so- * the validation stays dynamic and newly added tabs deep-link without a hardcoded key list.- */-import { describe, expect, it } from "vitest";-import { resolveTabKey } from "../src/features/agents/agent-settings-page";--const TABS = [{ key: "overview" }, { key: "tools" }, { key: "vault" }] as const;--describe("resolveTabKey", () => {- it("passes a known tab key through", () => {- expect(resolveTabKey("tools", TABS, "overview")).toBe("tools");- expect(resolveTabKey("vault", TABS, "overview")).toBe("vault");- });-- it("falls back for absent, empty, unknown, or wrong-cased values", () => {- expect(resolveTabKey(null, TABS, "overview")).toBe("overview");- expect(resolveTabKey("", TABS, "overview")).toBe("overview");- expect(resolveTabKey("bogus", TABS, "overview")).toBe("overview");- expect(resolveTabKey("Tools", TABS, "overview")).toBe("overview");- });-- it("validates against the supplied keys, not a hardcoded list", () => {- expect(resolveTabKey("skills", [...TABS, { key: "skills" }], "overview")).toBe("skills");- expect(resolveTabKey("hooks", TABS, "overview")).toBe("overview");- expect(resolveTabKey("hooks", [...TABS, { key: "hooks" }], "overview")).toBe("hooks");- });-});diff --git a/packages/web/test/api-error-text.test.ts b/packages/web/test/api-error-text.test.tsindex 7c0f556e..c27abbbc 100644--- a/packages/web/test/api-error-text.test.ts+++ b/packages/web/test/api-error-text.test.ts@@ -1,17 +1,20 @@/**- * Server error → localized display text (`apiErrorText`).+ * Server error → display text (`apiErrorText`), and the error the api client builds. The+ * server's messages are English-only by design, so the UI derives its text from the error code;+ * a code missing from the table falls through to the raw English message.*- * The server's error messages are English-only by design, so the UI derives its text from the- * error **code**. Any code missing from the table falls through to the raw English message —- * which is how English prose ends up in a Chinese UI. These tests pin the codes a user actually- * meets, and pin that the three "cannot compact" reasons stay three distinct explanations- * rather than collapsing into one.+ * - The three "cannot compact" refusals stay three distinct explanations, in both languages.+ * - The Chinese UI shows Chinese text for the errors an ordinary session can surface.+ * - A code nobody mapped still falls back to the server's message; a non-ApiError reads as the+ * generic failure.+ * - A numeric Retry-After header survives onto the ApiError.*/-import { afterEach, describe, expect, it, vi } from "vitest";+import { afterEach, describe, expect, it } from "vitest";import { ApiError, apiFetch } from "../src/api/client";import { apiErrorText } from "../src/lib/api-error";import { S, setActiveStrings, zh as ZH } from "../src/lib/strings";import { en as EN } from "../src/lib/strings-en";+import { apiError, stubFetch } from "./helpers/fetch";/** The English message the server actually sends, so an unmapped code is visibly distinguishable. */const serverError = (code: string): ApiError =>@@ -19,7 +22,6 @@ const serverError = (code: string): ApiError =>afterEach(() => {setActiveStrings(ZH);- vi.unstubAllGlobals();});describe("apiErrorText", () => {@@ -72,35 +74,13 @@ describe("apiErrorText", () => {);});- it("keeps the zh and en code tables in step", () => {- // A code localized in one language and not the other is the same bug in the other- // direction; the Strings type pins the key set, this pins that neither side is empty.- expect(Object.keys(EN.errors.byCode)).toEqual(Object.keys(ZH.errors.byCode));- for (const [code, text] of Object.entries(EN.errors.byCode)) {- expect(text, `${code} has no English text`).not.toBe("");- expect(ZH.errors.byCode[code as keyof typeof ZH.errors.byCode]).not.toBe("");- }- });-it("reports a non-ApiError as the generic failure, not a stray object", () => {setActiveStrings(ZH);expect(apiErrorText(new Error("boom"))).toBe(S.common.unknownError);});it("keeps a numeric Retry-After header on the ApiError", async () => {- vi.stubGlobal(- "fetch",- vi.fn(- async () =>- new Response(- JSON.stringify({ error: { code: "platform_rate_limited", message: "slow down" } }),- {- status: 429,- headers: { "content-type": "application/json", "retry-after": "7" },- },- ),- ),- );+ stubFetch(() => apiError(429, "platform_rate_limited", "slow down", { "retry-after": "7" }));await expect(apiFetch("/api/platform-rate-limit-test")).rejects.toMatchObject({status: 429,diff --git a/packages/web/test/approval-mode.test.ts b/packages/web/test/approval-mode.test.tsindex 5164a49e..58b08a46 100644--- a/packages/web/test/approval-mode.test.ts+++ b/packages/web/test/approval-mode.test.ts@@ -1,17 +1,17 @@/**- * approval-mode.ts: which approval modes the composer's picker lists. An organization's- * Session (`client: "org"`) runs with nobody watching — the server denies on the spot any call- * its mode would hand to a person — so `always-ask` is left out there, as in the organization- * settings. The one exception is a row that already stores it: the entry stays listed while it- * is the current value, rather than the menu showing nothing selected. Every other Session- * gets all four.+ * Which approval modes the composer's picker lists (features/chat/approval-mode.ts).+ *+ * - Every Session the organization runtime did not open (web, cli, or a row from before the+ * column existed) gets every mode.+ * - An organization's Session runs with nobody watching, so always-ask is left out there...+ * - ...except while the row already stores it: it stays listed in its usual place rather than+ * the menu showing nothing selected, and goes once another mode is picked.*/import { describe, expect, it } from "vitest";import { APPROVAL_MODES, approvalModeChoices } from "../src/features/chat/approval-mode";describe("approvalModeChoices", () => {it("lists every mode for a Session the organization runtime did not open", () => {- expect(APPROVAL_MODES).toEqual(["always-ask", "read-only", "allow-all", "deny-all"]);// `undefined`: a row from before the column existed, which reads as a web Session.for (const client of ["web", "cli", undefined] as const) {expect(approvalModeChoices(client, "allow-all")).toEqual(APPROVAL_MODES);diff --git a/packages/web/test/autofill.test.ts b/packages/web/test/autofill.test.tsdeleted file mode 100644index e351cbf3..00000000--- a/packages/web/test/autofill.test.ts+++ /dev/null@@ -1,47 +0,0 @@-/**- * Autofill policy of the shared form controls (autofillProps in the UI package's forms/input):- * fields opt out by default, a declared credential role passes through, and an opted-out- * password box goes out as "new-password" — plain "off" is ignored by Chrome/Safari there,- * which is how the account's saved login used to land in an API-key field.- */-import { describe, it, expect } from "vitest";-import { autofillProps } from "@prismshadow/penguin-ui";-import { expectEveryRootScanned, expectSingleHome, scanSources } from "./helpers/roots";--const IGNORES = {- "data-1p-ignore": "",- "data-lpignore": "true",- "data-bwignore": "",- "data-form-type": "other",-};--describe("autofill sources", () => {- it("scan every source root, and find the policy in one place", () => {- const scan = scanSources();- expectEveryRootScanned(scan);- expectSingleHome(scan, "packages/ui/src/components/forms/input/input.tsx");- });-});--describe("autofillProps", () => {- it("opts an undeclared field out, extension attributes included", () => {- expect(autofillProps(undefined, false)).toEqual({ autoComplete: "off", ...IGNORES });- });-- it("emits new-password for a secret field, never a bare off", () => {- // Chrome and Safari ignore autocomplete="off" on a password box and offer the saved- // login anyway; "new-password" is the only value they read as "not the account password".- expect(autofillProps(undefined, true)).toEqual({ autoComplete: "new-password", ...IGNORES });- expect(autofillProps("off", true)).toEqual({ autoComplete: "new-password", ...IGNORES });- });-- it("treats an explicit off as the same opt-out as no value at all", () => {- expect(autofillProps("off", false)).toEqual(autofillProps(undefined, false));- });-- it("passes a declared credential role through untouched (login, password dialogs)", () => {- for (const role of ["username", "current-password", "new-password"]) {- expect(autofillProps(role, role.endsWith("password"))).toEqual({ autoComplete: role });- }- });-});diff --git a/packages/web/test/avatar-image.test.ts b/packages/web/test/avatar-image.test.tsindex d5537adb..30839711 100644--- a/packages/web/test/avatar-image.test.ts+++ b/packages/web/test/avatar-image.test.ts@@ -1,10 +1,15 @@/**- * avatar-image.ts: the crop rectangle and the format decision behind a picked avatar.+ * The crop rectangle and the format decision behind a picked avatar (lib/avatar-image.ts). The+ * encoder is a parameter rather than a canvas call, so the PNG-or-JPEG-or-refuse rule runs here+ * against a fake encoder.*- * vitest runs node-only here (`environment: "node"`, no jsdom), which is why the encoder is a- * parameter rather than a canvas call: the rule that decides PNG-or-JPEG-or-refuse is the part- * a user hits, and it is exercised here with a fake encoder instead of being unreachable.+ * - The crop is the image's centred square.+ * - A PNG that fits its budget is kept; otherwise a JPEG that fits the cap; otherwise the pick is+ * refused.+ * - The cap is the one the server enforces, in the same unit (characters of data URL), read from+ * the server's route.*/+import { readFileSync } from "node:fs";import { describe, expect, it } from "vitest";import {AVATAR_JPEG_QUALITY,@@ -83,11 +88,17 @@ describe("fitAvatarDataUrl", () => {});describe("the cap", () => {- it("is the same number the server enforces, in the same unit", () => {- // server/src/http/routes/me.ts rejects an avatar over 131072 CHARACTERS of data URL. Both- // sides measuring the string rather than the decoded bytes is what keeps a picture this- // module just accepted from being refused by the request that carries it.- expect(AVATAR_MAX_CHARS).toBe(131072);+ it("is the number the server enforces, in the same unit", () => {+ // The server's route rejects an avatar over its cap in CHARACTERS of data URL. Both sides+ // measuring the string rather than the decoded bytes is what keeps a picture this module+ // just accepted from being refused by the request that carries it. The server is a+ // type-only dependency of the Web App, so its route is read as text.+ const route = readFileSync(+ new URL("../../server/src/http/routes/me.ts", import.meta.url),+ "utf8",+ );+ const serverCap = Number(/const AVATAR_MAX_CHARS = (\d+);/.exec(route)?.[1]);+ expect(AVATAR_MAX_CHARS).toBe(serverCap);expect(AVATAR_PNG_BUDGET).toBeLessThan(AVATAR_MAX_CHARS);});});diff --git a/packages/web/test/benchmark-prompts.test.ts b/packages/web/test/benchmark-prompts.test.tsindex ba608d6a..8ff75fef 100644--- a/packages/web/test/benchmark-prompts.test.ts+++ b/packages/web/test/benchmark-prompts.test.ts@@ -1,11 +1,19 @@/**- * The Evaluation Center's prompts and id helpers (src/features/benchmark/benchmark-prompts.ts):- * the Create-with-AI tail hands the benchmark-design Skill its tested Agent and the Project-level- * layout, the Evaluate and Optimize tails carry every input the agent-evaluation and- * agent-optimization Skills require, the two Ask AI tails carry the facts on screen and the- * files they were read from, and the manual form's directory names follow the id alphabet.+ * The Evaluation Center's prompts and id helpers (src/features/benchmark/benchmark-prompts.ts).* Assertions on a tail's wording are language-agnostic: the ids, paths and Session ids it must* name, never the sentences around them, which differ per dictionary.+ *+ * - The Create-with-AI tail hands the benchmark-design Skill its tested Agent and the+ * Project-level layout, and every evaluation records its tested Agent.+ * - The Evaluate tail carries every input the agent-evaluation Skill requires and asks for the+ * full matrix without offering an optimization; the Optimize tail carries every input the+ * agent-optimization Skill requires; a note or focus text goes before the tail, a blank one+ * is left out.+ * - The evaluation dialog's Ask AI question carries the facts on screen, every case and the+ * Session of every run, and names no Skill to run; the case dialog's names both material+ * paths and the latest runs; each box opens on the default question, which leads its examples.+ * - Case ids pad the position to three digits, a Benchmark lives at the Project level, and a+ * runs count is 1..MAX_RUNS.*/import { describe, expect, it } from "vitest";import { S } from "../src/lib/strings";@@ -15,7 +23,6 @@ import {askCaseTail,askEvaluationExamples,askEvaluationTail,- benchmarkCreateExamples,benchmarkCreateTail,benchmarkPath,buildEvaluatePrompt,@@ -45,16 +52,6 @@ describe("benchmarkCreateTail", () => {expect(tail).not.toContain("agents/report-writer");expect(tail).toContain("`agent_id`");});-- it("offers examples with unique keys and non-empty prompts", () => {- const examples = benchmarkCreateExamples();- expect(examples.length).toBeGreaterThanOrEqual(4);- expect(new Set(examples.map((e) => e.key)).size).toBe(examples.length);- for (const e of examples) {- expect(e.label).not.toBe("");- expect(e.prompt.trim()).not.toBe("");- }- });});describe("evaluateTail / buildEvaluatePrompt", () => {@@ -206,17 +203,10 @@ describe("askEvaluationTail (the evaluation dialog's Ask AI question)", () => {expect(tail).not.toContain("run_subagent");});- it("offers examples with unique keys and non-empty prompts, the default question first", () => {- const examples = askEvaluationExamples();- expect(examples).toHaveLength(4);- expect(new Set(examples.map((e) => e.key)).size).toBe(examples.length);- for (const e of examples) {- expect(e.label).not.toBe("");- expect(e.prompt.trim()).not.toBe("");- }- // The box opens on the default question; the leading example IS that question, so a- // reader who tried another example can bring it back with one click.- expect(examples[0]?.prompt).toBe(S.benchmark.askEvaluationDefault);+ it("leads the examples with the default question the box opens on", () => {+ // The leading example IS that question, so a reader who tried another example can bring+ // it back with one click.+ expect(askEvaluationExamples()[0]?.prompt).toBe(S.benchmark.askEvaluationDefault);});});@@ -254,15 +244,8 @@ describe("askCaseTail (the case dialog's Ask AI question)", () => {expect(tail).not.toContain("64.7");});- it("offers examples with unique keys and non-empty prompts, the default question first", () => {- const examples = askCaseExamples();- expect(examples).toHaveLength(4);- expect(examples[0]?.prompt).toBe(S.benchmark.askCaseDefault);- expect(new Set(examples.map((e) => e.key)).size).toBe(examples.length);- for (const e of examples) {- expect(e.label).not.toBe("");- expect(e.prompt.trim()).not.toBe("");- }+ it("leads the examples with the default question the box opens on", () => {+ expect(askCaseExamples()[0]?.prompt).toBe(S.benchmark.askCaseDefault);});});diff --git a/packages/web/test/budget-input.test.ts b/packages/web/test/budget-input.test.tsindex 1bc3e13c..49d7d33f 100644--- a/packages/web/test/budget-input.test.ts+++ b/packages/web/test/budget-input.test.ts@@ -1,7 +1,14 @@/**- * budget-input.ts unit tests: a budget is a monthly cap stored in USD, and the box that sets- * it speaks whichever currency the reader picked — so what was typed has to reach the server- * as USD, and what the server holds has to come back into the box as the reader's currency.+ * The budget box (features/company/budget-input.ts): a monthly cap stored in USD, typed and+ * shown in whichever currency the reader picked.+ *+ * - A USD box is stored as typed; a CNY box is divided by the fixed rate and rounded to cents.+ * - An empty box is unbounded, zero is a real budget, and a negative or non-number is refused.+ * - The box fills with the stored amount converted to the reader's currency (empty when there+ * is no budget); a USD box round-trips exactly, and a CNY box shows what the cent-rounded+ * amount really converts back to.+ * - The box accepts an empty value or a non-negative number, nothing else.+ * - The unit names the reader's currency, per month in the reader's language.*/import { describe, expect, it } from "vitest";import {@@ -81,10 +88,9 @@ describe("isBudgetText", () => {});describe("unitLabel", () => {- it("names the reader's currency and the period the cap covers", () => {- expect(unitLabel("USD", zh)).toBe("$ / 月");- expect(unitLabel("CNY", zh)).toBe("¥ / 月");- expect(unitLabel("USD", en)).toBe("$ / month");- expect(unitLabel("CNY", en)).toBe("¥ / month");+ it("names the reader's currency, per month in the reader's language", () => {+ expect(unitLabel("USD", en)).toMatch(/^\$/);+ expect(unitLabel("CNY", en)).toMatch(/^¥/);+ expect(unitLabel("USD", zh)).not.toBe(unitLabel("USD", en));});});diff --git a/packages/web/test/builtin-browser-geometry.test.ts b/packages/web/test/builtin-browser-geometry.test.tsindex 3595fb7d..0f04018b 100644--- a/packages/web/test/builtin-browser-geometry.test.ts+++ b/packages/web/test/builtin-browser-geometry.test.ts@@ -1,7 +1,13 @@/**- * Where the built-in browser's pages sit (features/builtin-browser/geometry.ts): the page on- * screen covers the visible part of the dock's slot at the slot's full size, every other page- * parks off-screen at a real size, and a frame that computes the same boxes writes nothing.+ * Where the built-in browser's pages sit (features/builtin-browser/geometry.ts).+ *+ * - The page on screen covers a fully visible slot exactly; a clipped slot clips the frame to+ * the dock's window while the page keeps the slot's size, offset by what the clip cuts off.+ * - With no slot, an empty one, or nothing of it visible, the page parks far off-screen at a+ * real size; the size a page was last shown at is remembered, a parked page's is not.+ * - Edges snap to whole pixels (edges rounded, not sizes), so a slot and its frame never open+ * a seam; rectangles intersect, reporting no overlap as null.+ * - A frame that computes the same boxes writes nothing.*/import { describe, expect, it } from "vitest";import {@@ -75,8 +81,7 @@ describe("parking", () => {expect(placement.view).toEqual({ left: 0, top: 0, ...DEFAULT_PARK_SIZE });});- it("defaults to a desktop viewport, and remembers the size a page was shown at", () => {- expect(DEFAULT_PARK_SIZE).toEqual({ width: 1280, height: 800 });+ it("remembers the size a page was shown at, and none for a parked page", () => {expect(shownSize(slotPlacement(slot, [], DEFAULT_PARK_SIZE))).toEqual({width: 480,height: 700,diff --git a/packages/web/test/builtin-browser-on-screen.test.ts b/packages/web/test/builtin-browser-on-screen.test.tsindex 7fc0acd3..60de2b9b 100644--- a/packages/web/test/builtin-browser-on-screen.test.ts+++ b/packages/web/test/builtin-browser-on-screen.test.ts@@ -1,64 +1,77 @@/**- * The tab on screen, told to the server (features/builtin-browser/on-screen-report.ts): once the- * choice has settled, once per change however many frames repeat it, and again after a resync.+ * The tab on screen, told to the server (features/builtin-browser/on-screen-report.ts), as the+ * `POST …/tabs/on-screen` requests the fetch fake records. The layer reports on every frame it+ * lays out (every 16 ms here, on fake timers).+ *+ * - The tab on screen is said once it has stayed put for the settle time, and not again while it+ * stays.+ * - A quick run of switches says only where it ends; a switch that comes back before it settled+ * says nothing new.+ * - After a resync the tab on screen is said again.*/import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";--vi.mock("../src/api/endpoints", () => ({- setBuiltinBrowserOnScreen: vi.fn(() => Promise.resolve()),-}));--import * as api from "../src/api/endpoints";import {ON_SCREEN_SETTLE_MS,forgetOnScreenReport,reportOnScreenTab,} from "../src/features/builtin-browser/on-screen-report";+import { json, stubFetch } from "./helpers/fetch";+import type { FakeFetch } from "./helpers/fetch";-const sent = vi.mocked(api.setBuiltinBrowserOnScreen);+let fetch: FakeFetch;beforeEach(() => {vi.useFakeTimers();forgetOnScreenReport();- sent.mockClear();+ fetch = stubFetch(() => json({}));});afterEach(() => vi.useRealTimers());-/** The layer lays out a frame every 16 ms. */+const FRAME_MS = 16;+/** Enough frames for a choice to settle; a handful, well short of it. */+const SETTLED = Math.ceil(ON_SCREEN_SETTLE_MS / FRAME_MS) + 1;+const QUICK = 3;++/** The layer laying out `count` frames with `tabId` on screen. */function frames(tabId: number | null, count: number): void {for (let i = 0; i < count; i++) {reportOnScreenTab(tabId);- vi.advanceTimersByTime(16);+ vi.advanceTimersByTime(FRAME_MS);}}+/** The tab each on-screen report named, in order. */+const said = () =>+ fetch.requests+ .filter((r) => r.path.endsWith("/tabs/on-screen"))+ .map((r) => (r.body as { tabId: number | null }).tabId);+describe("reportOnScreenTab", () => {it("says the tab on screen once it has stayed a moment, and not again while it stays", () => {- frames(4, 5);- expect(sent).not.toHaveBeenCalled();- frames(4, 60);- expect(sent.mock.calls).toEqual([[4]]);+ frames(4, QUICK);+ expect(said()).toEqual([]);+ frames(4, SETTLED * 2);+ expect(said()).toEqual([4]);});it("says only where a quick run of switches ends", () => {- frames(4, 3);- frames(7, 3);- frames(null, 40);- expect(sent.mock.calls).toEqual([[null]]);+ frames(4, QUICK);+ frames(7, QUICK);+ frames(null, SETTLED);+ expect(said()).toEqual([null]);});it("says nothing when the switch comes back before it settled", () => {- frames(4, 40);- frames(7, 3);- frames(4, 40);- expect(sent.mock.calls).toEqual([[4]]);+ frames(4, SETTLED);+ frames(7, QUICK);+ frames(4, SETTLED);+ expect(said()).toEqual([4]);});it("says it again after a resync", () => {- frames(4, 40);+ frames(4, SETTLED);forgetOnScreenReport();- frames(4, 40);- expect(sent.mock.calls).toEqual([[4], [4]]);- expect(ON_SCREEN_SETTLE_MS).toBeLessThan(40 * 16);+ frames(4, SETTLED);+ expect(said()).toEqual([4, 4]);});});diff --git a/packages/web/test/channel-list.test.ts b/packages/web/test/channel-list.test.tsindex 533cd51c..23a0ec16 100644--- a/packages/web/test/channel-list.test.ts+++ b/packages/web/test/channel-list.test.ts@@ -1,7 +1,16 @@/**- * channel-list.ts unit tests: the all-hands channel's reserved id and its localized label,- * the four runs of the sidebar's list and the order inside them, the id a new channel may- * take, the two numbers the sidebar and rail badges sum, and who is left to invite.+ * A company's channel list (features/company/channel-list.ts).+ *+ * - The all-hands channel renders under its localized label; every other channel under its+ * stored name.+ * - A new channel id follows the server's semantic-id grammar; a blank, malformed, reserved or+ * taken id is refused with its reason before the request goes out.+ * - The list pins the all-hands channel, then splits the rest into mine and others, with+ * archived channels folded away whatever the membership; each run is ordered by name, then+ * id, and a missing all-hands channel is survived.+ * - The badges sum unread messages and mentions over the joined, unarchived channels only.+ * - Invite candidates are the employees then the Project members not already in the channel,+ * with an employee's title as detail, a prefix match ranked above a substring match.*/import { describe, expect, it } from "vitest";import type { OrgChannelItem } from "@prismshadow/penguin-server/api";@@ -32,8 +41,7 @@ const channel = (over: Partial<OrgChannelItem> & { channelId: string }): OrgChan});describe("the all-hands channel", () => {- it("is `default_channel`, and renders under its localized label rather than its stored name", () => {- expect(DEFAULT_CHANNEL_ID).toBe("default_channel");+ it("renders under its localized label rather than its stored name", () => {expect(isAllHands(DEFAULT_CHANNEL_ID)).toBe(true);expect(isAllHands("site")).toBe(false);expect(channelLabel({ channelId: DEFAULT_CHANNEL_ID, name: "General" }, "全员频道")).toBe(diff --git a/packages/web/test/channel-notices.test.ts b/packages/web/test/channel-notices.test.tsindex 5343e71d..0174db69 100644--- a/packages/web/test/channel-notices.test.ts+++ b/packages/web/test/channel-notices.test.ts@@ -1,8 +1,13 @@/**- * channel-notices.ts unit tests: every kind the contract declares has a sentence in both- * dictionaries, the sentence names employees instead of spelling them `agent:<id>`, a member- * reads as its user id, an unknown employee falls back to its id, and a kind this build does- * not know renders nothing so the view can fall back to the server's English text.+ * A channel's system lines in the reader's language (features/company/channel-notices.ts).+ *+ * - Every kind the contract declares has wording in both languages, even for a notice that is+ * missing its parameters.+ * - A hire names its employees and keeps the job title verbatim.+ * - A member reads as its user id and an unknown employee as its id, never as a principal.+ * - A budget event carries its period, share and amounts; a ticket event its id and title.+ * - A kind this build does not know renders nothing, so the view falls back to the server's+ * English text.*/import { describe, expect, it } from "vitest";import type { OrgChannelNotice } from "@prismshadow/penguin-server/api";@@ -19,14 +24,6 @@ const notice = (kind: string, params: Record<string, string>): OrgChannelNotice({ kind, params }) as OrgChannelNotice;describe("the notice dictionaries", () => {- for (const [locale, dict] of Object.entries({ zh, en })) {- it(`${locale} carries one sentence per kind, and no key the contract does not declare`, () => {- const notices: Record<string, unknown> = dict.company.channels.notices;- expect(Object.keys(notices).sort()).toEqual([...NOTICE_KINDS].sort());- for (const kind of NOTICE_KINDS) expect(typeof notices[kind], kind).toBe("function");- });- }-it("has wording for every kind, even for a notice missing its parameters", () => {for (const kind of NOTICE_KINDS) {expect(noticeText(notice(kind, {}), names, zh.company.channels.notices), kind).toBeTruthy();@@ -45,13 +42,20 @@ describe("noticeText", () => {title: "研究",reportsTo: "agent:ceo",});- expect(enText(hire)).toBe("Dana Dev joined as 研究, reporting to Ada CEO.");- expect(zhText(hire)).toBe("Dana Dev 以「研究」身份加入,汇报给 Ada CEO。");+ for (const text of [enText(hire), zhText(hire)]) {+ expect(text).toContain("Dana Dev");+ expect(text).toContain("研究");+ expect(text).toContain("Ada CEO");+ expect(text).not.toContain("agent:");+ }});it("renders a member as its user id and an unknown employee as its id", () => {const invited = notice("channel_invited", { by: "user:alice", principal: "agent:ghost" });- expect(enText(invited)).toBe("alice invited ghost to the channel.");+ const text = enText(invited)!;+ expect(text).toContain("alice");+ expect(text).toContain("ghost");+ expect(text).not.toMatch(/user:|agent:/);});it("carries a budget event's period, share and amounts", () => {@@ -62,16 +66,19 @@ describe("noticeText", () => {cost: "41.00",budget: "50.00",});- expect(enText(warned)).toBe(- "Budget warning: Ada CEO has used 82% of its 2026-09 budget (41.00 / 50.00 USD).",- );- expect(zhText(warned)).toContain("2026-09 预算的 82%");+ for (const text of [enText(warned), zhText(warned)]) {+ for (const part of ["Ada CEO", "2026-09", "82%", "41.00", "50.00"]) {+ expect(text).toContain(part);+ }+ }});it("carries a ticket's id and title", () => {const done = notice("ticket_done", { ticket: "T-3", title: "Build the site" });- expect(enText(done)).toBe("Ticket T-3 (Build the site) is done.");- expect(zhText(done)).toBe("工单 T-3(Build the site)已完成。");+ for (const text of [enText(done), zhText(done)]) {+ expect(text).toContain("T-3");+ expect(text).toContain("Build the site");+ }});it("renders nothing for a kind this build does not know", () => {diff --git a/packages/web/test/clipboard.test.ts b/packages/web/test/clipboard.test.tsindex 64b54c7e..f6938f34 100644--- a/packages/web/test/clipboard.test.ts+++ b/packages/web/test/clipboard.test.ts@@ -1,75 +1,36 @@/**- * writeClipboard unit tests: the copy path that has to work on the origins this app is- * actually served from.+ * The app's one clipboard write (lib/clipboard.ts `writeClipboard`), which has to work on the+ * origins the app is served from: `navigator.clipboard` exists only in a secure context, so it+ * is absent on every plain-HTTP origin but localhost. The entry hands the write to the real+ * `copy-to-clipboard` here, with only `window`, `navigator` and `document` replaced, so an+ * upgrade that changes one of the properties the app chose it for fails here.*- * `navigator.clipboard` is secure-context-only, so it is absent on every plain-HTTP origin- * that is not localhost — a LAN bind, a remote install opened at `http://<host>:7364`. The- * entry hands the write to `copy-to-clipboard`, and the three groups below pin three- * different things:- *- * - the entry's contract, against a module double: the text goes to the library as is,- * its boolean comes back as is, and its `window.prompt` last resort stays off;- * - the library's behaviour, against the REAL library with only `window`, `navigator`- * and `document` replaced: these are the properties this app chose it for, so an- * upgrade that changes one of them fails here rather than in a browser;- * - the seam itself, against the source text: a copy affordance that reaches for- * `navigator.clipboard.writeText` on its own would reintroduce exactly the silent no-op- * this module exists to prevent, and nothing in a node-only suite would notice- * (context-menu.test.ts convention).+ * - On a non-secure origin the copy command runs without suspending, copies exactly the text+ * from an element kept out of layout, removes that element whatever the copy did, and hands+ * the page's selection and focus back.+ * - A copy command that reports failure or throws resolves false, never a rejection, and never+ * falls back to a prompt.+ * - In a secure context the Clipboard API is used and no copy command runs; when it refuses the+ * write, the copy command takes over.+ * - Guard: no other module writes to `navigator.clipboard` or imports `copy-to-clipboard`.*/import { readFileSync, readdirSync } from "node:fs";import { dirname, join, relative, resolve } from "node:path";import { fileURLToPath } from "node:url";-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { afterEach, describe, expect, it, vi } from "vitest";type WriteClipboard = (text: string) => Promise<boolean>;-/** A fresh import of the entry, so a module double (or its removal) takes effect. */+/** A fresh import of the entry and its library, reading the globals the test just stubbed. */async function loadEntry(): Promise<WriteClipboard> {vi.resetModules();return (await import("../src/lib/clipboard")).writeClipboard;}afterEach(() => {- vi.unstubAllGlobals();- vi.doUnmock("copy-to-clipboard");vi.resetModules();});-describe("writeClipboard: the entry's contract", () => {- const copy =- vi.fn<(text: string, options?: { fallbackToPrompt?: boolean }) => Promise<boolean>>();-- beforeEach(() => {- copy.mockReset();- vi.doMock("copy-to-clipboard", () => ({ default: copy }));- });-- it("hands the text to the library unchanged and returns its true", async () => {- copy.mockResolvedValue(true);- const writeClipboard = await loadEntry();-- await expect(writeClipboard(" reply\ttext\n")).resolves.toBe(true);- expect(copy).toHaveBeenCalledTimes(1);- expect(copy.mock.calls[0]?.[0]).toBe(" reply\ttext\n");- });-- it("returns the library's false as is", async () => {- copy.mockResolvedValue(false);- const writeClipboard = await loadEntry();-- await expect(writeClipboard("x")).resolves.toBe(false);- });-- it("leaves the library's prompt fallback off", async () => {- copy.mockResolvedValue(false);- const writeClipboard = await loadEntry();-- await writeClipboard("x");- expect(copy.mock.calls[0]?.[1]?.fallbackToPrompt).toBeFalsy();- });-});-interface FakeElement {tagName: string;textContent: string;@@ -317,19 +278,4 @@ describe("clipboard writes go through one entry", () => {expect(LIBRARY_IMPORT.test(readFileSync(ENTRY, "utf8"))).toBe(true);expect(offenders(LIBRARY_IMPORT)).toEqual([]);});-- it("hands the entry to the shared UI package's copy controls, at the app root", () => {- const app = readFileSync(join(SRC, "app.tsx"), "utf8");- expect(app).toContain('import { writeClipboard } from "./lib/clipboard";');- expect(app).toContain("<ClipboardWriterProvider write={writeClipboard}>");- });-- it("leaves reads alone: the terminal's mouse paste still reads the Clipboard API", () => {- const reads = sourceFiles(SRC).filter((file) =>- /navigator\s*\.\s*clipboard[\s\S]{0,40}?\.\s*readText\s*\(/.test(readFileSync(file, "utf8")),- );- expect(reads.map((file) => relative(SRC, file))).toContain(- join("features", "terminal", "terminal-view.tsx"),- );- });});diff --git a/packages/web/test/command-policy-add-rule.test.ts b/packages/web/test/command-policy-add-rule.test.tsindex d967816c..b4b2c0b3 100644--- a/packages/web/test/command-policy-add-rule.test.ts+++ b/packages/web/test/command-policy-add-rule.test.ts@@ -1,63 +1,15 @@/**- * Adding a rule on the Project settings security page.+ * Adding a rule on the Project settings security page (components/layout/project-dialogs.tsx).*- * The Add button lives in the rule list's header row, above the rules. The form it opens used- * to render after every rule — and with the factory set seeded the list is already taller than- * the dialog's 70vh scroll box, so the form opened below the fold and the click looked inert.- *- * Where a form opens relative to the control that opens it is a fact about JSX child order, so- * it is checked with the TypeScript parser the way test/disclosure-anchor.test.ts checks- * disclosure anchoring — a regex cannot see siblings. The focus half is checked by rendering.+ * - The rule editor puts the caret in its first field (the rule's name) and nowhere else, so+ * opening the form is never silent.*/import { describe, expect, it } from "vitest";import { createElement } from "react";import { renderToStaticMarkup } from "react-dom/server";-import { readFileSync } from "node:fs";-import { fileURLToPath } from "node:url";-import ts from "typescript";import { RuleEditor } from "../src/components/layout/project-dialogs";-const SOURCE = fileURLToPath(- new URL("../src/components/layout/project-dialogs.tsx", import.meta.url),-);--/**- * Child slots of the rule list: the `editing === "new"` add form and the `rules.map(…)` rows.- * Only the list container holds them as two DIFFERENT children — in every ancestor both markers- * fall inside one and the same child — which is what identifies it without naming it.- */-function listSlots(): { addForm: number; rows: number } | null {- const source = ts.createSourceFile(- SOURCE,- readFileSync(SOURCE, "utf8"),- ts.ScriptTarget.Latest,- /* setParentNodes */ true,- ts.ScriptKind.TSX,- );- const found: { addForm: number; rows: number }[] = [];- const visit = (node: ts.Node): void => {- if (ts.isJsxElement(node)) {- const holds = (needle: string) => (c: ts.Node) => c.getText(source).includes(needle);- const addForm = node.children.findIndex(holds('editing === "new"'));- const rows = node.children.findIndex(holds("rules.map("));- if (addForm !== -1 && rows !== -1 && addForm !== rows) found.push({ addForm, rows });- }- ts.forEachChild(node, visit);- };- visit(source);- return found.at(-1) ?? null;-}-describe("command policy: adding a rule", () => {- it("opens the add form above the rules, beside the Add button that opened it", () => {- const slots = listSlots();- if (slots === null) throw new Error("add form and rule rows are no longer siblings in a list");- expect(- slots.addForm,- "the add form renders before the rules — appended after them it opens off-screen",- ).toBeLessThan(slots.rows);- });-it("puts the caret in the first field, so the form is not silently opened", () => {const html = renderToStaticMarkup(createElement(RuleEditor, { initial: null, onApply: () => {}, onCancel: () => {} }),diff --git a/packages/web/test/compaction-summary.test.ts b/packages/web/test/compaction-summary.test.tsindex a746faf1..a8cc91f2 100644--- a/packages/web/test/compaction-summary.test.ts+++ b/packages/web/test/compaction-summary.test.ts@@ -1,16 +1,15 @@/**- * What a compaction row shows: the text inside its result section (compaction-summary.ts)- * and the titles above it (the dictionaries' mode-aware `compactionTitle`, and the state- * titles `compactionRunning` / `compactionDone` the header shows while the step runs and once- * it settles, the work-group header's own Running/Done idiom).+ * What a compaction row shows (lib/omni/compaction-summary.ts and the dictionaries' mode-aware+ * titles). The section timings are stream-model.test.ts's.*- * The row itself is a StepBanner whose body stacks a thinking section and a result section.- * The banner opens while the compaction runs and closes itself once it settles; the two- * sections stay closed throughout, showing only their labels and their wall times — the- * reader expands one to watch the request think or write, or to read the outcome afterwards.- * What the result section then contains is this pure helper's job, and it is what these tests- * pin; the section timings behind those wall times are pinned in stream-model.test.ts (the- * Web suite runs in a node environment and renders no React).+ * - The result section reads the summary as prose: tags stripped, an unclosed block shown as+ * far as it streamed, tagless output verbatim, and nothing when nothing streamed.+ * - The result section stays hidden while the request only thinks, appears with the first+ * summary text, and stays for a completed row but not for a failed one.+ * - A discard is never titled as a compaction, and an unknown mode falls back to the+ * compaction title.+ * - The running and settled titles differ, in both modes and both languages, and a discard+ * never reads as compacting in either state.*/import { describe, expect, it } from "vitest";import { en } from "../src/lib/strings-en";@@ -90,11 +89,6 @@ describe("compactionTitle (the row is titled by its mode)", () => {});describe("compactionRunning / compactionDone (the title doubles as the status, as the work group's does)", () => {- it("reads 压缩中 while a compaction runs and 压缩完毕 once it settles", () => {- expect(zh.chat.compactionRunning("summarize")).toBe("压缩中");- expect(zh.chat.compactionDone("summarize")).toBe("压缩完毕");- });-it("keeps the two states and the two modes apart in both dictionaries", () => {for (const [locale, dict] of [["zh", zh],diff --git a/packages/web/test/company-beta.test.ts b/packages/web/test/company-beta.test.tsindex bebfb127..a4ca8458 100644--- a/packages/web/test/company-beta.test.ts+++ b/packages/web/test/company-beta.test.ts@@ -1,79 +1,38 @@/**- * Company mode's two beta marks (features/company/company-beta.tsx, the tag drawn by the shared- * UI package's `BetaBadge`).+ * Company mode's once-only beta notice (features/company/company-beta.tsx): the first switch+ * into the mode in a browser raises it, later ones do not.*- * The tag, on 「公司」 in the work-mode switch: it has to be legible, it has to reach a screen- * reader through the option's name, and it must not move the switch around — which is the whole- * reason it is positioned out of flow rather than laid out beside the word.- *- * The notice, the once-only sentence behind it: the first switch into the mode in a browser- * raises it, every later one does not, and a storage that is absent or refuses to answer raises- * nothing rather than raising it forever.+ * - The notice is owed in a browser that has never shown it, and no longer once it is marked.+ * - It stays owed while the flag holds anything but the mark.+ * - A storage that throws, or no storage at all, owes nothing, so the notice cannot repeat on+ * every switch; marking it then does not throw.*/import { describe, expect, it } from "vitest";-import { createElement } from "react";-import { renderToStaticMarkup } from "react-dom/server";-import { Segmented } from "@prismshadow/penguin-ui";import {BETA_NOTICE_KEY,- CompanyBetaBadge,markBetaNoticeShown,shouldShowBetaNotice,} from "../src/features/company/company-beta";-import { zh } from "../src/lib/strings";-import { expectEveryRootScanned, expectSingleHome, scanSources } from "./helpers/roots";--/** The in-memory stand-in for localStorage (this package's vitest runs in Node, which has none). */-function memoryStorage(initial: Record<string, string> = {}) {- const map = new Map(Object.entries(initial));- return {- getItem: (key: string): string | null => map.get(key) ?? null,- setItem: (key: string, value: string): void => {- map.set(key, value);- },- read: (key: string): string | null => map.get(key) ?? null,- };-}--/** A browser with site data blocked: every access throws rather than returning null. */-const throwingStorage = {- getItem(): string | null {- throw new Error("access denied");- },- setItem(): void {- throw new Error("access denied");- },-};--/** The modules rendered below, found by scanning web and the shared UI package (see roots.ts). */-describe("the beta marks' sources", () => {- it("scan every source root, and find the badge and the switch in one place each", () => {- const scan = scanSources();- expectEveryRootScanned(scan);- expectSingleHome(scan, "packages/web/src/features/company/company-beta.tsx");- expectSingleHome(scan, "packages/ui/src/components/feedback/beta-badge/beta-badge.tsx");- expectSingleHome(scan, "packages/ui/src/components/forms/segmented/segmented.tsx");- });-});+import { blockedStorage, memoryStorage } from "./helpers/storage";describe("shouldShowBetaNotice", () => {it("is owed on a browser that has never seen it, and not after it is marked", () => {const storage = memoryStorage();expect(shouldShowBetaNotice(storage)).toBe(true);markBetaNoticeShown(storage);- expect(storage.read(BETA_NOTICE_KEY)).toBe("1");+ expect(storage.map.get(BETA_NOTICE_KEY)).toBe("1");expect(shouldShowBetaNotice(storage)).toBe(false);});it("stays owed while the flag holds anything but the mark", () => {- expect(shouldShowBetaNotice(memoryStorage({ [BETA_NOTICE_KEY]: "" }))).toBe(true);- expect(shouldShowBetaNotice(memoryStorage({ [BETA_NOTICE_KEY]: "true" }))).toBe(true);- expect(shouldShowBetaNotice(memoryStorage({ [BETA_NOTICE_KEY]: "0" }))).toBe(true);+ for (const flag of ["", "true", "0"]) {+ expect(shouldShowBetaNotice(memoryStorage({ [BETA_NOTICE_KEY]: flag }))).toBe(true);+ }});it("answers no when storage throws, so the notice cannot repeat on every switch", () => {- expect(shouldShowBetaNotice(throwingStorage)).toBe(false);- expect(() => markBetaNoticeShown(throwingStorage)).not.toThrow();+ expect(shouldShowBetaNotice(blockedStorage())).toBe(false);+ expect(() => markBetaNoticeShown(blockedStorage())).not.toThrow();});it("answers no when there is no storage at all (Node, no localStorage)", () => {@@ -81,52 +40,3 @@ describe("shouldShowBetaNotice", () => {expect(() => markBetaNoticeShown()).not.toThrow();});});--/** The work-mode switch as the sidebar builds it, with and without the tag on 「公司」. */-function workModeSwitch(withBadge: boolean): string {- return renderToStaticMarkup(- createElement(Segmented<"dev" | "company">, {- options: [- { value: "dev", label: zh.company.modeDev },- {- value: "company",- label: zh.company.modeCompany,- ...(withBadge- ? { badge: { node: createElement(CompanyBetaBadge), name: zh.company.beta } }- : {}),- },- ],- value: "dev",- onChange: () => {},- cols: 2,- }),- );-}--describe("the beta tag on the work-mode switch", () => {- it("names itself in the option's accessible name, and only that option's", () => {- const markup = workModeSwitch(true);- expect(markup).toContain(`aria-label="${zh.company.modeCompany} · ${zh.company.beta}"`);- // The other option keeps the label's own text as its name: an aria-label is only spent- // where there is something the visible text does not already say.- expect(markup).not.toContain(`aria-label="${zh.company.modeDev}"`);- });-- it("is a superscript, so the option's height and the control's size do not move", () => {- const markup = workModeSwitch(true);- expect(markup).toContain("absolute");- // Out of flow means out of the name too, so the tag's text is hidden rather than announced- // twice beside the suffix above.- expect(markup).toContain('aria-hidden="true"');- expect(markup).toContain(zh.company.beta);- // The tooltip is the one thing the tag still says on its own.- expect(markup).toContain(`data-tooltip="${zh.company.betaTitle}"`);- });-- it("costs an option without one nothing", () => {- const markup = workModeSwitch(false);- expect(markup).not.toContain("aria-label");- expect(markup).not.toContain("absolute");- expect(markup).not.toContain(zh.company.beta);- });-});diff --git a/packages/web/test/company-mode-write.test.ts b/packages/web/test/company-mode-write.test.tsindex fe87418a..771abddd 100644--- a/packages/web/test/company-mode-write.test.ts+++ b/packages/web/test/company-mode-write.test.ts@@ -1,12 +1,11 @@/**- * company-mode-write.ts unit tests: the master switch in System settings › Server applies on the- * flip, so the write is the whole save path and there is no Save button to retry with. Both- * outcomes are pinned here — the request a flip sends and the value it settles on, and the- * revert-with-a-reason that a rejected write has to produce, since a switch left showing a state- * the server does not hold is the failure mode this replaced.+ * The company-mode master switch in System settings › Server (features/settings/+ * company-mode-write.ts): it applies on the flip, so the write is the whole save path.*- * vitest runs node-only in this package (`environment: "node"`, no jsdom), which is why the- * sequence lives in its own module and the component is the thin caller.+ * - A flip either way sends that one field alone and settles on what the server answers, even+ * when the server stored something other than what was asked.+ * - A failed write reverts the switch to the stored value (on stays on, off stays off) and+ * carries the described reason.*/import { describe, expect, it } from "vitest";import type {@@ -40,19 +39,14 @@ const recorder = (answer: boolean) => {const describeError = (error: unknown) => `described: ${String(error)}`;describe("writeCompanyMode", () => {- it("sends the flipped value alone and settles on what the server answers", async () => {- const api = recorder(true);- const result = await writeCompanyMode(true, false, { put: api.put, describeError });- // Only the one field: every other server setting keeps its stored value.- expect(api.sent).toEqual([{ companyMode: true }]);- expect(result).toEqual({ status: "applied", companyMode: true });- });-- it("turning it off is the same single write", async () => {- const api = recorder(false);- const result = await writeCompanyMode(false, true, { put: api.put, describeError });- expect(api.sent).toEqual([{ companyMode: false }]);- expect(result).toEqual({ status: "applied", companyMode: false });+ it("sends the flipped value alone, either way, and settles on what the server answers", async () => {+ for (const next of [true, false]) {+ const api = recorder(next);+ const result = await writeCompanyMode(next, !next, { put: api.put, describeError });+ // Only the one field: every other server setting keeps its stored value.+ expect(api.sent).toEqual([{ companyMode: next }]);+ expect(result).toEqual({ status: "applied", companyMode: next });+ }});it("adopts the server's answer rather than the value that was asked for", async () => {@@ -73,15 +67,12 @@ describe("writeCompanyMode", () => {revertTo: false,error: "described: Error: 403",});- });-- it("reverts to on, not to off, when turning it off fails", async () => {// The revert target is the stored value, never a default: a failed turn-off on an enabled// server has to leave the switch on.- const result = await writeCompanyMode(false, true, {+ const off = await writeCompanyMode(false, true, {put: () => Promise.reject(new Error("boom")),describeError,});- expect(result).toMatchObject({ status: "failed", revertTo: true });+ expect(off).toMatchObject({ status: "failed", revertTo: true });});});diff --git a/packages/web/test/company-nav.test.ts b/packages/web/test/company-nav.test.tsindex cb25dd8a..244b9db3 100644--- a/packages/web/test/company-nav.test.ts+++ b/packages/web/test/company-nav.test.ts@@ -1,16 +1,22 @@/**- * company-nav.ts and work-mode.ts unit tests: the company-mode nav manifest (the six pages- * in rendered order, each with a zh label, an en label and a glyph — the sidebar, the rail- * and the router all derive their rows from it), the `<projectId>/<orgId>` key, the- * `/org/:projectId/:orgId/<page>` and `…/channels/:channelId` grammars, where `/org` lands- * without an organization, where a freshly created one opens and which key the shell becomes- * current at when it does, the switcher's grouping by- * Project, and the localStorage mirrors of the mode and the last organization (injectable- * storage, forgettable, degrading to the defaults on anything unexpected).+ * Company mode's navigation (features/company/company-nav.ts) and the work-mode mirrors in+ * localStorage (lib/work-mode.ts).+ *+ * - An organization key is `<projectId>/<orgId>` and parses back; anything but two non-empty+ * segments is refused.+ * - Page and channel paths live under `/org`, with the ids encoded.+ * - A new organization opens in the CEO's desk when it has one, else on its overview, and the+ * shell becomes current at its plain-id key whatever the path escapes.+ * - Organization routes are told apart from the shared chat route.+ * - `/org` lands on the organization last opened while it exists, else the current Project's+ * first, else the first anywhere, and nowhere without any.+ * - The switcher groups organizations in the Project list's order, dropping empty Projects.+ * - The mode defaults to development, only an explicit company switches it; only a+ * well-formed last organization key is kept, and it can be forgotten outright; a throwing+ * storage degrades to the defaults.*/import { describe, expect, it } from "vitest";import {- COMPANY_NAV_KEYS,groupOrganizationsByProject,isOrgRoute,orgChannelPath,@@ -22,7 +28,6 @@ import {resolveOrgLanding,} from "../src/features/company/company-nav";import { DEFAULT_CHANNEL_ID } from "../src/features/company/channel-list";-import { COMPANY_NAV_ICONS } from "../src/features/company/company-nav-icons";import {LAST_ORG_KEY,WORK_MODE_KEY,@@ -32,60 +37,7 @@ import {storeLastOrgKey,storeWorkMode,} from "../src/lib/work-mode";-import type { WorkModeStorage } from "../src/lib/work-mode";-import { zh } from "../src/lib/strings";-import { en } from "../src/lib/strings-en";--function memStorage(): WorkModeStorage & { map: Map<string, string> } {- const map = new Map<string, string>();- return {- map,- getItem: (k) => map.get(k) ?? null,- setItem: (k, v) => void map.set(k, v),- removeItem: (k) => void map.delete(k),- };-}--describe("COMPANY_NAV_KEYS", () => {- it("lists the six organization pages in the spec's order, channels not among them", () => {- expect([...COMPANY_NAV_KEYS]).toEqual([- "overview",- "chart",- "calendar",- "tickets",- "finance",- "handbook",- ]);- // Channels are the sidebar's own list, the way conversations are in development mode.- expect(COMPANY_NAV_KEYS).not.toContain("chat");- expect(COMPANY_NAV_KEYS).not.toContain("channels");- });-- it("every entry has the spec's zh and en names and a glyph", () => {- // The bilingual table of the prototype spec, verbatim.- const expected = {- overview: ["概览", "Overview"],- chart: ["组织图", "Org Chart"],- calendar: ["日历", "Calendar"],- tickets: ["工单", "Tickets"],- finance: ["财务", "Finance"],- handbook: ["手册", "Handbook"],- } as const;- for (const key of COMPANY_NAV_KEYS) {- expect(zh.nav.org[key]).toBe(expected[key][0]);- expect(en.nav.org[key]).toBe(expected[key][1]);- expect(COMPANY_NAV_ICONS[key]).toBeTruthy();- }- });-- it("the mode switch's two options exist in both languages and differ", () => {- for (const dict of [zh, en]) {- expect(dict.company.modeDev).toBeTruthy();- expect(dict.company.modeCompany).toBeTruthy();- expect(dict.company.modeDev).not.toBe(dict.company.modeCompany);- }- });-});+import { blockedStorage, memoryStorage } from "./helpers/storage";describe("org keys and paths", () => {it("round-trips a key through parseOrgKey", () => {@@ -113,14 +65,6 @@ describe("org keys and paths", () => {expect(orgChannelPath("alice-proj", "a b", "site")).toBe("/org/alice-proj/a%20b/channels/site");});- // An organization opens on its overview, not on a channel: the switcher's pick, `/org`'s- // redirect and the router's index route all land there, and a channel is reached from the- // sidebar's own list.- it("makes the overview the first page of the six, which is where an organization opens", () => {- expect(COMPANY_NAV_KEYS[0]).toBe("overview");- expect(orgPagePath("p1", "acme", "overview")).toBe("/org/p1/acme/overview");- });-it("lands a newly created organization in the CEO's desk, else on its overview", () => {expect(orgCreatedPath({ projectId: "p1", orgId: "acme", ceoDeskSessionId: "s-1" })).toBe("/chat/s-1",@@ -205,7 +149,7 @@ describe("groupOrganizationsByProject", () => {describe("work-mode storage mirrors", () => {it("defaults to development with nothing stored, and only an explicit company switches", () => {- const s = memStorage();+ const s = memoryStorage();expect(initialWorkMode(s)).toBe("dev");storeWorkMode("company", s);expect(s.map.get(WORK_MODE_KEY)).toBe("company");@@ -215,7 +159,7 @@ describe("work-mode storage mirrors", () => {});it("keeps only a well-formed last organization key", () => {- const s = memStorage();+ const s = memoryStorage();expect(initialLastOrgKey(s)).toBeNull();storeLastOrgKey("p1/acme", s);expect(s.map.get(LAST_ORG_KEY)).toBe("p1/acme");@@ -227,7 +171,7 @@ describe("work-mode storage mirrors", () => {// The organization it named was deleted: the mirror is dropped, not overwritten, so the// next reload starts with no remembered organization at all.it("forgets the last organization key outright", () => {- const s = memStorage();+ const s = memoryStorage();storeLastOrgKey("p1/acme", s);clearLastOrgKey(s);expect(s.map.has(LAST_ORG_KEY)).toBe(false);@@ -235,17 +179,7 @@ describe("work-mode storage mirrors", () => {});it("throwing storage degrades to the defaults instead of escaping", () => {- const broken: WorkModeStorage = {- getItem: () => {- throw new Error("denied");- },- setItem: () => {- throw new Error("denied");- },- removeItem: () => {- throw new Error("denied");- },- };+ const broken = blockedStorage();expect(() => storeWorkMode("company", broken)).not.toThrow();expect(() => clearLastOrgKey(broken)).not.toThrow();expect(initialWorkMode(broken)).toBe("dev");diff --git a/packages/web/test/company-work-mode.test.ts b/packages/web/test/company-work-mode.test.tsindex 3b2c77c3..bfd4fdb1 100644--- a/packages/web/test/company-work-mode.test.ts+++ b/packages/web/test/company-work-mode.test.ts@@ -1,52 +1,42 @@/*** The work mode the shell stands in across the two switches that make company mode available- * (state/company.tsx). Turning a switch on offers company mode and never enters it — not even- * when a company choice is still stored from before the switch went off, which is what used to- * swap the company sidebar in under the new-chat page. Only the user's own move enters it.+ * (state/company.tsx), driven against the store: `setServerEnabled` is what the Provider calls+ * with every read of /api/me, and `applyPrefs` what it calls when the preferences arrive. Each+ * case says where the choice ends up (the localStorage mirror and the `PUT /api/me/prefs` the+ * fetch fake records) as well as what the shell shows.*- * Driven against the store, with no React and no DOM: `setServerEnabled` is what the Provider- * calls with every read of /api/me, and `applyPrefs` what it calls when the preferences arrive.- * The localStorage mirror is an in-memory stand-in and the preference writes are recorded, so- * each case says where the choice ends up as well as what the shell shows.+ * - Company mode is available only with both switches on; the shell stands in development+ * otherwise.+ * - A switch coming on offers company mode and never enters it: not when the server's switch+ * comes on, not with a company choice left from before it went off (which is written back as+ * development), and not after the server's or the user's own switch went off and on again.+ * - Preferences that arrive with a company choice while a switch is off are settled to+ * development without passing through company; while company mode stays available, the+ * choice is kept as it was.+ * - Entering company mode is the user's own move, and only while it is available.*/-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";--vi.mock("../src/api/endpoints", async (importOriginal) => ({- ...(await importOriginal<typeof import("../src/api/endpoints")>()),- putPrefs: vi.fn(() => Promise.resolve({ prefs: {} })),-}));--import * as api from "../src/api/endpoints";+import { beforeEach, describe, expect, it, vi } from "vitest";+import type { MockInstance } from "vitest";import { BETA_NOTICE_KEY } from "../src/features/company/company-beta";import { WORK_MODE_KEY } from "../src/lib/work-mode";import { companyModeAvailable, createCompanyStore, effectiveWorkMode } from "../src/state/company";+import { json, stubFetch } from "./helpers/fetch";+import type { FakeFetch } from "./helpers/fetch";+import { memoryStorage, stubLocalStorage } from "./helpers/storage";+import type { MemoryStorage } from "./helpers/storage";-const putPrefs = vi.mocked(api.putPrefs);-let storage: Map<string, string>;-/**- * Every value written to the work-mode mirror, in order. The end state is not the whole story:- * a mode the mirror only passes through is a mode the next load finds if the tab closes in that- * window, so a settled choice must never be written unsettled first.- */-let modeWrites: string[];+let storage: MemoryStorage;+let setItem: MockInstance<Storage["setItem"]>;+let fetch: FakeFetch;beforeEach(() => {// The beta notice counts as shown, so entering company mode raises no toast here.- storage = new Map([[BETA_NOTICE_KEY, "1"]]);- modeWrites = [];- vi.stubGlobal("localStorage", {- getItem: (key: string) => storage.get(key) ?? null,- setItem: (key: string, value: string) => {- if (key === WORK_MODE_KEY) modeWrites.push(value);- storage.set(key, value);- },- removeItem: (key: string) => void storage.delete(key),+ storage = stubLocalStorage(memoryStorage({ [BETA_NOTICE_KEY]: "1" }));+ setItem = vi.spyOn(storage, "setItem");+ fetch = stubFetch((request) => {+ if (request.path === "/api/me/prefs") return json({ prefs: {} });+ throw new TypeError("fetch failed");});- putPrefs.mockClear();-});--afterEach(() => {- vi.unstubAllGlobals();});type Store = ReturnType<typeof createCompanyStore>;@@ -54,9 +44,25 @@ type Store = ReturnType<typeof createCompanyStore>;/** What the shell stands in: the mode switch's selection and the sidebar it draws. */const shown = (store: Store) => effectiveWorkMode(store.getState());+/**+ * Every value written to the work-mode mirror, in order. The end state is not the whole story:+ * a mode the mirror only passes through is a mode the next load finds if the tab closes in that+ * window, so a settled choice must never be written unsettled first.+ */+const modeWrites = () =>+ setItem.mock.calls.filter(([key]) => key === WORK_MODE_KEY).map(([, value]) => value);++/** Every preferences body sent to the server, in order. */+const sentPrefs = () =>+ fetch.requests+ .filter((r) => r.method === "PUT" && r.path === "/api/me/prefs")+ .map((r) => r.body as { workMode?: string });+/** Every work mode written to the user's preferences, in order. */const writtenModes = () =>- putPrefs.mock.calls.map(([body]) => body.workMode).filter((mode) => mode !== undefined);+ sentPrefs()+ .map((body) => body.workMode)+ .filter((mode) => mode !== undefined);describe("availability and the mode the shell stands in", () => {it("is available only with both switches on, and stands in development otherwise", () => {@@ -88,13 +94,14 @@ describe("turning company mode on offers it and does not enter it", () => {it("writes a company choice found while the server's switch is off back as development, so the switch coming on does not apply it", () => {// The mirror still holds a choice made before the switch was turned off somewhere else.- storage.set(WORK_MODE_KEY, "company");+ storage.setItem(WORK_MODE_KEY, "company");+ setItem.mockClear();const store = createCompanyStore({ serverEnabled: false });// The first render, before the Provider's effect has reached the store.expect(shown(store)).toBe("dev");store.getState().setServerEnabled(false);expect(store.getState().workMode).toBe("dev");- expect(storage.get(WORK_MODE_KEY)).toBe("dev");+ expect(storage.getItem(WORK_MODE_KEY)).toBe("dev");expect(writtenModes()).toEqual(["dev"]);store.getState().setServerEnabled(true);@@ -113,7 +120,7 @@ describe("turning company mode on offers it and does not enter it", () => {store.getState().setServerEnabled(true);expect(shown(store)).toBe("dev");- expect(storage.get(WORK_MODE_KEY)).toBe("dev");+ expect(storage.getItem(WORK_MODE_KEY)).toBe("dev");expect(writtenModes()).toEqual(["company", "dev"]);});@@ -126,8 +133,8 @@ describe("turning company mode on offers it and does not enter it", () => {store.getState().setPersonalEnabled(true);expect(shown(store)).toBe("dev");- expect(storage.get(WORK_MODE_KEY)).toBe("dev");- expect(putPrefs.mock.calls.map(([body]) => body)).toEqual([+ expect(storage.getItem(WORK_MODE_KEY)).toBe("dev");+ expect(sentPrefs()).toEqual([{ workMode: "company" },{ workMode: "dev" },{ companyMode: false },@@ -142,9 +149,9 @@ describe("the preferences as they arrive", () => {store.getState().setServerEnabled(false);store.getState().applyPrefs({ workMode: "company", lastOrgKey: "p1/acme" });expect(store.getState().workMode).toBe("dev");- expect(storage.get(WORK_MODE_KEY)).toBe("dev");+ expect(storage.getItem(WORK_MODE_KEY)).toBe("dev");// Never through "company" on the way: the mirror follows the settled mode, not the stored one.- expect(modeWrites).not.toContain("company");+ expect(modeWrites()).not.toContain("company");expect(writtenModes()).toEqual(["dev"]);expect(store.getState().lastOrgKey).toBe("p1/acme");@@ -157,8 +164,8 @@ describe("the preferences as they arrive", () => {store.getState().applyPrefs({ workMode: "company", companyMode: false });expect(store.getState().personalEnabled).toBe(false);expect(store.getState().workMode).toBe("dev");- expect(storage.get(WORK_MODE_KEY)).toBe("dev");- expect(modeWrites).not.toContain("company");+ expect(storage.getItem(WORK_MODE_KEY)).toBe("dev");+ expect(modeWrites()).not.toContain("company");expect(writtenModes()).toEqual(["dev"]);store.getState().setPersonalEnabled(true);@@ -170,9 +177,9 @@ describe("the preferences as they arrive", () => {store.getState().setServerEnabled(true);store.getState().applyPrefs({ workMode: "company" });expect(shown(store)).toBe("company");- expect(storage.get(WORK_MODE_KEY)).toBe("company");+ expect(storage.getItem(WORK_MODE_KEY)).toBe("company");// One write, and it is the choice itself: nothing was adopted and then taken back.- expect(modeWrites).toEqual(["company"]);+ expect(modeWrites()).toEqual(["company"]);expect(writtenModes()).toEqual([]);});});@@ -188,7 +195,7 @@ describe("entering company mode", () => {expect(shown(store)).toBe("dev");store.getState().setWorkMode("company");expect(shown(store)).toBe("company");- expect(storage.get(WORK_MODE_KEY)).toBe("company");+ expect(storage.getItem(WORK_MODE_KEY)).toBe("company");expect(writtenModes()).toEqual(["company"]);});});diff --git a/packages/web/test/context-menu.test.ts b/packages/web/test/context-menu.test.tsindex 7ce8e37d..67421a83 100644--- a/packages/web/test/context-menu.test.ts+++ b/packages/web/test/context-menu.test.ts@@ -1,16 +1,13 @@/**- * How the app uses the row context menu (the UI package's `useRowContextMenu` and its gesture- * rules, under components/overlays/portal-panel/, driving a `Dropdown` in `anchorRect` mode). The- * rules, the hook's own guards and the Dropdown's scroll wiring are the package's- * `context-menu.test.ts`; what is pinned here spans the app.+ * Guard: how the app uses the row context menu (the UI package's `useRowContextMenu` and its+ * gesture rules). The rules, the hook's own guards and the Dropdown's scroll wiring are the+ * package's `context-menu.test.ts`; what is held here spans the app.*- * **Suppression scope**: preventing the browser's own menu is correct on the row and wrong- * everywhere else, and nothing in a node-only suite (`environment: "node"`, no jsdom) would notice- * a `preventDefault` that had crept onto a document-level listener — so the scan asserts there is- * no global contextmenu listener in either root. And the feature must not be mouse-only: the- * sidebar's Session rows (the UI package's `SessionRow`) spread all three openers (right-click,- * Shift+F10, press-and-hold) and name the anchor's owner, which the scroll rule needs to leave a- * menu open while an unrelated container scrolls.+ * - The scan reads every source root, finds the menu modules in one place each, and reports+ * POSIX-separated paths whatever the platform's separator (the id contract every guard's+ * path comparison depends on, which only Windows CI would otherwise catch).+ * - No window-, document- or globalThis-level contextmenu listener exists, so the browser's own+ * menu survives off the row.*/import { describe, expect, it } from "vitest";import { expectEveryRootScanned, expectSingleHome, scanSources } from "./helpers/roots";@@ -34,8 +31,6 @@ const DROPDOWN = "packages/ui/src/components/overlays/dropdown/dropdown.tsx";const CONTEXT_MENU = "packages/ui/src/components/overlays/portal-panel/use-row-context-menu.ts";const RULES = "packages/ui/src/components/overlays/portal-panel/context-menu.ts";const SIDEBAR = "packages/web/src/components/layout/sidebar.tsx";-/** The sidebar's conversation row, which owns the row's menu wiring. */-const SESSION_ROW = "packages/ui/src/components/shell/session-row/session-row.tsx";describe("sourceFiles", () => {it("scans every source root, and finds the menu modules in one place each", () => {@@ -53,7 +48,6 @@ describe("sourceFiles", () => {expect(paths.filter((p) => p.includes("\\"))).toEqual([]);expect(paths).toContain(CONTEXT_MENU);expect(paths).toContain(SIDEBAR);- expect(paths).toContain(SESSION_ROW);});});@@ -69,23 +63,4 @@ describe("native-menu suppression scope", () => {);expect(global.map(([path]) => path)).toEqual([]);});-- it("gives the sidebar row all three openers, so the menu is not mouse-only", () => {- const row = sourceFiles().find(([path]) => path === SESSION_ROW);- expect(row).toBeDefined();- // The row spreads the hook's handlers (contextmenu + Shift+F10 + press-and-hold) and- // guards its own click against the one a hold replays.- expect(row![1]).toContain("{...ctx.rowProps}");- expect(row![1]).toContain("ctx.consumeLongPressClick()");- // And the sidebar draws its conversations with that row.- const sidebar = sourceFiles().find(([path]) => path === SIDEBAR);- expect(sidebar![1]).toContain("<SessionRow");- });-- it("names the anchor's owner alongside the anchor, so the scroll rule has one to test", () => {- // Without the wiring, scrollMovesAnchor is asked about a null owner on every scroll and- // answers "dismiss" — the package's rule tests would still pass while the bug was back.- const row = sourceFiles().find(([path]) => path === SESSION_ROW);- expect(row![1]).toContain("anchorOwner={ctx.anchorOwner}");- });});diff --git a/packages/web/test/context-parts.test.ts b/packages/web/test/context-parts.test.tsindex 8734e3a4..766fd184 100644--- a/packages/web/test/context-parts.test.ts+++ b/packages/web/test/context-parts.test.ts@@ -1,15 +1,17 @@/**- * Context composition rows: the estimate-to-measured rescaling behind the context ring's panel,- * and the palette it is zipped with.+ * The context ring's composition panel (features/chat/context-parts.ts).+ *+ * - The estimate is rescaled so the parts add up to the measured occupancy, both columns+ * apportioned so neither drifts off the total.+ * - Every part is drawn in a colour of its own.+ * - The tool and file rankings scale on the same basis, as shares of the whole context, each+ * file keeping its name for display.+ * - An empty estimate or a closed context has nothing to break down.+ * - A file path splits on either separator, a root keeping its own separator as the directory.*/import { describe, expect, it } from "vitest";import type { SessionContextResponse } from "@prismshadow/penguin-server/api";-import {- CONTEXT_PART_KEYS,- contextComposition,- splitFilePath,-} from "../src/features/chat/context-parts";-import { CONTEXT_PART_COLORS } from "../src/lib/category-colors";+import { contextComposition, splitFilePath } from "../src/features/chat/context-parts";function response(over: Partial<SessionContextResponse> = {}): SessionContextResponse {const base = {@@ -70,13 +72,12 @@ describe("contextComposition", () => {expect(c.parts.reduce((n, p) => n + p.tokens, 0)).toBe(350);});- it("gives the parts the palette in its documented order", () => {- const c = contextComposition(response(), 1000)!;- expect(c.parts.map((p) => p.key)).toEqual([...CONTEXT_PART_KEYS]);- expect(c.parts.map((p) => p.color)).toEqual([...CONTEXT_PART_COLORS]);- // Zipped by index: a part added on one side and not the other would silently lose its colour.- expect(CONTEXT_PART_COLORS).toHaveLength(CONTEXT_PART_KEYS.length);- expect(new Set(CONTEXT_PART_COLORS).size).toBe(CONTEXT_PART_COLORS.length);+ it("draws every part in a colour of its own", () => {+ // The palette is zipped with the parts by index: a part added on one side and not the+ // other would silently lose its colour.+ const colors = contextComposition(response(), 1000)!.parts.map((p) => p.color);+ expect(colors.every(Boolean)).toBe(true);+ expect(new Set(colors).size).toBe(colors.length);});it("scales the tool ranking on the same basis, as shares of the whole context", () => {diff --git a/packages/web/test/control-size.test.ts b/packages/web/test/control-size.test.tsindex 74635c2d..f98b6409 100644--- a/packages/web/test/control-size.test.ts+++ b/packages/web/test/control-size.test.ts@@ -1,7 +1,13 @@/**- * The form-control size scale (the UI package's `sizeTextClass`, in+ * Guard: the form-control size scale (the UI package's `sizeTextClass`, in* packages/ui/src/components/forms/input/input.tsx).*+ * - No control call site spells a font size in its own className (checked on known shapes too,+ * so the check itself cannot go blind).+ * - A Modal footer's Buttons, and the Buttons of a module that is only ever dialog content, sit+ * on the fields' sm rung.+ * - The control family spells a font size in its two records and nowhere else.+ ** A control's font size comes from its `size` prop and nowhere else. A `text-*` in a caller's* `className` does not reliably override the component's own — both are single-class font-size* utilities of equal specificity, so which one wins is decided by the order Tailwind generated@@ -58,14 +64,23 @@ const FONT_SIZE_CLASS = /\btext-(?:xs|sm|base|lg|xl|\d?xl|\[[^\]]+])(?![\w-])/;const tsxFiles = (): SourceFile[] => SCAN.files.filter((file) => file.name.endsWith(".tsx"));-const parse = (file: SourceFile) =>- ts.createSourceFile(- file.path,- file.text,- ts.ScriptTarget.Latest,- /* setParentNodes */ true,- ts.ScriptKind.TSX,- );+const parsed = new Map<string, ts.SourceFile>();++/** A file's syntax tree, parsed once however many checks walk it. */+const parse = (file: SourceFile): ts.SourceFile => {+ let tree = parsed.get(file.id);+ if (tree === undefined) {+ tree = ts.createSourceFile(+ file.path,+ file.text,+ ts.ScriptTarget.Latest,+ /* setParentNodes */ true,+ ts.ScriptKind.TSX,+ );+ parsed.set(file.id, tree);+ }+ return tree;+};const jsxTag = (node: ts.Node): string | null => {if (ts.isJsxSelfClosingElement(node)) return node.tagName.getText();diff --git a/packages/web/test/create-with-ai-surfaces.test.ts b/packages/web/test/create-with-ai-surfaces.test.tsindex 3da57bdd..abff23f8 100644--- a/packages/web/test/create-with-ai-surfaces.test.ts+++ b/packages/web/test/create-with-ai-surfaces.test.ts@@ -1,55 +1,37 @@/*** The prompt material of the three "Create with AI" surfaces — the Agents page's create dialog,- * the Models page's add dialog and the Vault tab's add dialog: in both dictionaries each offers- * examples that fill the draft and a fixed tail naming the skill the receiving agent must use;- * the tail follows the draft when composed the way the dialogs compose it; and the parameterized- * tails carry the ids they are fed, since the prompt goes to the Project's default agent rather- * than the target. Both CLI tails also name `--root`: the harness strips `PENGUIN_HOME` from a- * command's environment, so a `penguin config` call without it configures another data root.+ * the Models page's add dialog and the Vault tab's add dialog. The prompt goes to the Project's+ * default agent rather than the target, so the tails have to carry the ids they are fed.*- * The vault's cards additionally have to agree with the warning printed above them, so the- * key-names-only ask leads and no card hands the user a secret-shaped placeholder to fill.+ * - Both dictionaries offer the same example cards, and no two cards on a surface share a key+ * (React keys, and the selected-state match).+ * - The vault's cards agree with the warning printed above them: the key-names-only ask leads,+ * and no card hands the user a secret-shaped placeholder to fill.+ * - The agent tail runs agent-initialization, and the onboarding card names the agent it seeds.+ * - The models and vault tails name the Project (and the vault tail the target agent), and every+ * CLI call in them names `--root`: the harness strips `PENGUIN_HOME` from a command's+ * environment, so a `penguin config` call without it configures another data root.*/import { describe, expect, it } from "vitest";import { zh } from "../src/lib/strings";import { en } from "../src/lib/strings-en";-import { composeAiPrompt } from "../src/features/ai-create/ai-create-prompt";-import type { AiExample } from "../src/features/ai-create/ai-create-panel";-/** Every example fills the draft with something, and no two share a key (React keys, and the selected-state match). */-function expectUsableExamples(examples: AiExample[]): void {- expect(examples.length).toBeGreaterThan(0);- expect(new Set(examples.map((e) => e.key)).size).toBe(examples.length);- for (const example of examples) {- expect(example.label.trim()).not.toBe("");- expect(example.prompt.trim()).not.toBe("");- }-}--/**- * Per-dictionary assertions run twice over; this one compares the two, which the per-dictionary- * block cannot see: a card added to one language only would pass every check above.- */-it("offers the same example cards in both dictionaries", () => {- expect(en.agent.aiExamples.map((e) => e.key)).toEqual(zh.agent.aiExamples.map((e) => e.key));- expect(en.models.aiAddExamples.map((e) => e.key)).toEqual(- zh.models.aiAddExamples.map((e) => e.key),- );- expect(en.vault.aiAddExamples.map((e) => e.key)).toEqual(- zh.vault.aiAddExamples.map((e) => e.key),- );+it("offers the same example cards in both dictionaries, no two on a surface sharing a key", () => {+ const surfaces = (dict: typeof zh): { key: string }[][] => [+ dict.agent.aiExamples,+ dict.models.aiAddExamples,+ dict.vault.aiAddExamples,+ ];+ const keys = (dict: typeof zh) => surfaces(dict).map((examples) => examples.map((e) => e.key));+ // A card added to one language only would pass every per-dictionary check below.+ expect(keys(en)).toEqual(keys(zh));+ for (const surface of keys(zh)) expect(new Set(surface).size).toBe(surface.length);});describe.each([["zh", zh],["en", en],] as const)("%s dictionary", (_locale, dict) => {- it("offers examples on every surface", () => {- expectUsableExamples(dict.agent.aiExamples);- expectUsableExamples(dict.models.aiAddExamples);- expectUsableExamples(dict.vault.aiAddExamples);- });-it("leads the vault examples with the key-names-only ask, and never asks for a pasted secret", () => {// The dialog's intro recommends letting AI create the key names and filling the values in by// hand; the first card is the one a scanning eye reads as the default, so it must be that ask.@@ -59,8 +41,6 @@ describe.each([// `<paste key>` / `<新 token>`: the placeholder shape that tells the user to put a secret// into the prompt, which is exactly what the intro above the cards warns against.expect(example.prompt).not.toMatch(/<[^>]+>/);- // Two-line card, as on the sibling surfaces.- expect(example.description?.trim()).toBeTruthy();}});@@ -68,9 +48,6 @@ describe.each([const tail = dict.agent.aiCreateTail;expect(tail).toContain("agent-initialization");expect(tail).toContain("AGENTS.md");- const prompt = composeAiPrompt("Create a jotting agent", tail);- expect(prompt.startsWith("Create a jotting agent\n\n")).toBe(true);- expect(prompt.endsWith(tail)).toBe(true);const onboarding = dict.agent.aiExamples.find((e) => e.key === "report-writer");expect(onboarding?.prompt).toContain("report-writer");});@@ -86,7 +63,6 @@ describe.each([for (const line of tail.split("\n").filter((l) => l.includes("penguin config"))) {expect(line).toContain("--root");}- expect(composeAiPrompt("x", tail).endsWith(tail)).toBe(true);});it("names the target agent, the Project and the data root in the vault tail, and lists the keys at the end", () => {@@ -98,6 +74,5 @@ describe.each([for (const line of tail.split("\n").filter((l) => l.includes("penguin config"))) {expect(line).toContain("--root");}- expect(composeAiPrompt("x", tail).endsWith(tail)).toBe(true);});});diff --git a/packages/web/test/dev-proxy.test.ts b/packages/web/test/dev-proxy.test.tsdeleted file mode 100644index 44cc1361..00000000--- a/packages/web/test/dev-proxy.test.ts+++ /dev/null@@ -1,32 +0,0 @@-/**- * Dev-server `/api` proxy target resolution (vite.config.ts). The interesting case is an- * empty `PORT=`: shells export it, `.env` files carry it, and resolving it to a bare- * `http://127.0.0.1:` sends every API call to port 80 without ever failing — a wrong backend- * is far harder to notice than a broken one, so the empty case is pinned here.- */-import { describe, expect, it } from "vitest";-import { apiProxyTarget } from "../vite.config.js";--describe("apiProxyTarget", () => {- it("defaults to the development backend, not the installed server's 7364", () => {- expect(apiProxyTarget({})).toBe("http://127.0.0.1:7368");- });-- it("treats an empty PORT as unset rather than as port 80", () => {- expect(apiProxyTarget({ PORT: "" })).toBe("http://127.0.0.1:7368");- });-- it("follows PORT so moving the backend moves the proxy with it", () => {- expect(apiProxyTarget({ PORT: "9999" })).toBe("http://127.0.0.1:9999");- });-- it("PENGUIN_API_PROXY replaces the whole target, PORT and all", () => {- expect(apiProxyTarget({ PORT: "9999", PENGUIN_API_PROXY: "http://10.0.0.2:8080" })).toBe(- "http://10.0.0.2:8080",- );- });-- it("an empty PENGUIN_API_PROXY falls back instead of proxying to nowhere", () => {- expect(apiProxyTarget({ PENGUIN_API_PROXY: "" })).toBe("http://127.0.0.1:7368");- });-});diff --git a/packages/web/test/dialog-layers.test.ts b/packages/web/test/dialog-layers.test.tsnew file mode 100644index 00000000..adc75cf6--- /dev/null+++ b/packages/web/test/dialog-layers.test.ts@@ -0,0 +1,73 @@+/**+ * The two pieces every dialog, drawer, sheet and menu in the app inherits from the UI package+ * (components/overlays/esc-layers): the Tab ring inside an open dialog and the Escape stack.+ * They have no test in packages/ui yet, so they are exercised here.+ *+ * - Tab steps forward and Shift+Tab backward, wrapping at either end; from the panel itself+ * focus enters at the end the direction implies, and a single-element ring holds in place.+ * - Only the topmost Escape layer may act, and popping it restores the one below (a menu inside+ * a dialog closes first); while any layer is open the app's global shortcuts hold back.+ * - Layers may be removed out of order, and a double pop is a no-op, never a throw.+ */+import { describe, expect, it } from "vitest";+import {+ hasEscLayers,+ isTopEscLayer,+ nextFocusIndex,+ popEscLayer,+ pushEscLayer,+} from "@prismshadow/penguin-ui";++describe("nextFocusIndex", () => {+ it("steps forward and wraps past the last element", () => {+ expect(nextFocusIndex(3, 0, false)).toBe(1);+ expect(nextFocusIndex(3, 2, false)).toBe(0);+ });++ it("steps backward and wraps past the first element", () => {+ expect(nextFocusIndex(3, 2, true)).toBe(1);+ expect(nextFocusIndex(3, 0, true)).toBe(2);+ });++ it("enters the ring at the end the direction implies when focus is on the panel itself", () => {+ // -1 is focus sitting on the container: a dialog whose focusable content mounted after+ // open, or one whose only control was just disabled. Shift+Tab must reach the last+ // element, not the second-to-last — the plain modulo gets this wrong.+ expect(nextFocusIndex(4, -1, false)).toBe(0);+ expect(nextFocusIndex(4, -1, true)).toBe(3);+ });++ it("holds a single-element ring in place rather than escaping it", () => {+ expect(nextFocusIndex(1, 0, false)).toBe(0);+ expect(nextFocusIndex(1, 0, true)).toBe(0);+ });+});++describe("esc layer stack", () => {+ it("only the topmost layer may act; popping restores the one below", () => {+ const modal = pushEscLayer();+ expect(isTopEscLayer(modal)).toBe(true);+ // An open layer is what holds the app's global shortcuts back.+ expect(hasEscLayers()).toBe(true);+ // A menu opened inside the modal stacks above it: the first Escape belongs to the menu.+ const menu = pushEscLayer();+ expect(isTopEscLayer(menu)).toBe(true);+ expect(isTopEscLayer(modal)).toBe(false);+ popEscLayer(menu);+ expect(isTopEscLayer(modal)).toBe(true);+ popEscLayer(modal);+ expect(isTopEscLayer(modal)).toBe(false);+ expect(hasEscLayers()).toBe(false);+ });++ it("tolerates out-of-order removal (an outer layer unmounting first)", () => {+ const outer = pushEscLayer();+ const inner = pushEscLayer();+ popEscLayer(outer); // e.g. the host dialog unmounts while its menu is still open+ expect(isTopEscLayer(inner)).toBe(true);+ popEscLayer(inner);+ // Double-pop is a no-op, never a throw (effect cleanups can race in tests/strict mode).+ popEscLayer(inner);+ expect(isTopEscLayer(inner)).toBe(false);+ });+});diff --git a/packages/web/test/disclosure-body.test.ts b/packages/web/test/disclosure-body.test.tsdeleted file mode 100644index a88c4e62..00000000--- a/packages/web/test/disclosure-body.test.ts+++ /dev/null@@ -1,118 +0,0 @@-/**- * The expanded Markdown body the thinking block and the compaction sections share- * (the shared UI package's disclosure-row.tsx). vitest is node-only here (`environment: "node"`, no- * jsdom), so this pins the contract against the source text and the stylesheets — the- * title-reveal.test.ts convention.- *- * The fragile part is not the class list, it is **where the end-margin reset lives**. The- * `.md-body` rules (the shared UI package's prose.css) sit outside any cascade layer while- * Tailwind's utilities are emitted inside `@layer utilities`, and an unlayered declaration beats a- * layered one at any specificity — so a `[&>*:first-child]:mt-0` utility on the body is inert against- * `.md-body`'s own `margin: 0.5rem 0`, and the body carries double the inset it claims.- * Nothing about the class list looks wrong when that happens, which is why it is asserted here.- *- * The rest keeps the body in step with the output block it is derived from: the same divider- * and the same inset, minus the parts that only fit command output, and none of the tinted- * rounded box the transcript uses for a quotation.- */-import { describe, expect, it } from "vitest";-import { DISCLOSURE_BODY_MD_CLASS, DISCLOSURE_OUTPUT_PRE_CLASS } from "@prismshadow/penguin-ui";-import { expectEveryRootScanned, expectSingleHome, scanSources, sourceFile } from "./helpers/roots";--const SCAN = scanSources();--const thinking = sourceFile(- SCAN,- "packages/ui/src/components/chat/thinking-block/thinking-block.tsx",-).text;-const compaction = sourceFile(SCAN, "packages/web/src/features/chat/compaction-banner.tsx").text;--/**- * One stylesheet with every `@layer …{ }` block removed, i.e. only its unlayered rules.- * Comments go first: one of them names `@layer utilities` in prose, and the scan below- * would take that for the start of a block and swallow the rules after it.- */-const unlayeredRules = (sheet: string) => {- let css = sheet.replace(/\/\*[\s\S]*?\*\//g, "");- for (;;) {- const at = css.search(/@layer[^;{]*\{/);- if (at === -1) return css;- const open = css.indexOf("{", at);- let depth = 0;- let end = open;- for (; end < css.length; end++) {- if (css[end] === "{") depth++;- else if (css[end] === "}" && --depth === 0) break;- }- css = css.slice(0, at) + css.slice(end + 1);- }-};--/**- * The unlayered rules of every stylesheet under the scanned roots — the app's styles.css and the- * shared package's component CSS, where the Markdown body's rules live — each file stripped on its- * own.- */-const unlayered = SCAN.files- .filter((file) => file.name.endsWith(".css"))- .map((file) => unlayeredRules(file.text))- .join("\n");--describe("the disclosure body's sources", () => {- it("scan every source root, and find the shared classes in one place", () => {- expectEveryRootScanned(SCAN);- expectSingleHome(SCAN, "packages/ui/src/components/layout/disclosure-row/disclosure-row.tsx");- });-});--/** Class list as a set, so an assertion does not depend on the order Prettier settles on. */-const classes = (value: string) => new Set(value.split(" "));--describe("the disclosure body's end margins", () => {- it("are reset by an unlayered rule in a stylesheet", () => {- expect(classes(DISCLOSURE_BODY_MD_CLASS)).toContain("md-body-flush");- // Written without whitespace so reformatting the stylesheet cannot break the match.- const rules = unlayered.replace(/\s+/g, "");- expect(rules).toContain(".md-body-flush>:first-child{margin-top:0");- expect(rules).toContain(".md-body-flush>:last-child{margin-bottom:0");- });-- it("are never reset by a utility, which would lose to .md-body's own margins", () => {- expect(DISCLOSURE_BODY_MD_CLASS).not.toMatch(/\[&>\*:(first|last)-child\]/);- });-});--describe("the disclosure body's relation to the output block", () => {- it("wears the same divider, inset and ink", () => {- const body = classes(DISCLOSURE_BODY_MD_CLASS);- const output = classes(DISCLOSURE_OUTPUT_PRE_CLASS);- for (const shared of ["border-t", "border-line-muted", "px-3", "py-2", "text-fg-muted"]) {- expect(output).toContain(shared);- expect(body).toContain(shared);- }- });-- it("takes neither the height cap nor the raw-text wrapping, which only fit command output", () => {- // Both bodies stream; a nested scrollbox would strand the tail the transcript follows.- for (const only of ["max-h-72", "overflow-auto", "whitespace-pre-wrap"]) {- expect(classes(DISCLOSURE_OUTPUT_PRE_CLASS)).toContain(only);- expect(classes(DISCLOSURE_BODY_MD_CLASS)).not.toContain(only);- }- });-- it("carries no tinted rounded box, the shape the transcript uses for a quotation", () => {- for (const cls of classes(DISCLOSURE_BODY_MD_CLASS)) {- expect(cls).not.toMatch(/^(dark:)?(bg|rounded)-/);- expect(cls).not.toBe("rounded");- }- });-});--describe("both expanded bodies", () => {- it("come from the one shared class, spelled in neither call site", () => {- for (const source of [thinking, compaction]) {- expect(source).toContain("DISCLOSURE_BODY_MD_CLASS");- expect(source).not.toMatch(/className="[^"]*\bmd-body\b/);- }- });-});diff --git a/packages/web/test/dock-launcher-state.test.ts b/packages/web/test/dock-launcher-state.test.tsindex 747e5146..0ac4f176 100644--- a/packages/web/test/dock-launcher-state.test.ts+++ b/packages/web/test/dock-launcher-state.test.ts@@ -1,8 +1,19 @@/**- * The floating dock launcher's decisions (features/dock/dock-launcher-state.ts): when it- * shows, how its resting position clamps to the chat body and round-trips through the- * stored ratio, whether the user put it away, how a drag is bounded, and where on the ring- * its entries land.+ * The floating dock launcher's decisions (features/dock/dock-launcher-state.ts).+ *+ * - It shows on a wide layout while the right dock is hidden and on a narrow one while neither+ * dock is up, hides behind the narrow merged surface, and stays away once put away.+ * - Put away reads only the stored "1"; writing either state notifies subscribers (both+ * renderers follow), and a throwing storage still tells this session.+ * - A resting position clamps inside the body with the edge margin and the caption, pinning to+ * the top margin when the body is too short and treating a non-finite offset as the top.+ * - The stored ratio centres the ball by default, clamps the extremes, round-trips a top offset,+ * falls back for a body with no height, parses and clamps a decimal, rejects anything else,+ * and survives a throwing storage.+ * - A drag tracks the pointer inside the bounds, rubberbands past the ends, pulls off the edge+ * only a damped distance, and settles back inside on release.+ * - The fan spreads its entries evenly over one circle left of the ball, widening only where the+ * arc is trimmed near the body's top or bottom, keeping every entry inside and apart.*/import { describe, expect, it } from "vitest";import {@@ -30,26 +41,12 @@ import {writeLauncherHidden,writeLauncherRatio,} from "../src/features/dock/dock-launcher-state";-import type {- FanSlot,- LauncherStorage,- LauncherVisibility,-} from "../src/features/dock/dock-launcher-state";+import type { FanSlot, LauncherVisibility } from "../src/features/dock/dock-launcher-state";+import { blockedStorage, memoryStorage } from "./helpers/storage";const BODY = 600;const MAX_TOP = BODY - LAUNCHER_SIZE - LAUNCHER_CAPTION_HEIGHT - LAUNCHER_EDGE_MARGIN;-function fakeStorage(initial: Record<string, string> = {}): LauncherStorage & {- map: Map<string, string>;-} {- const map = new Map(Object.entries(initial));- return {- map,- getItem: (key) => map.get(key) ?? null,- setItem: (key, value) => void map.set(key, value),- };-}-describe("visibility", () => {const at = (v: Partial<LauncherVisibility>): boolean =>shouldShowLauncher({@@ -86,14 +83,14 @@ describe("visibility", () => {describe("put away", () => {it('hides only on the stored "1"; anything else — absent, stale, garbage — shows it', () => {- expect(readLauncherHidden(fakeStorage({ [LAUNCHER_HIDDEN_KEY]: "1" }))).toBe(true);- expect(readLauncherHidden(fakeStorage())).toBe(false);- expect(readLauncherHidden(fakeStorage({ [LAUNCHER_HIDDEN_KEY]: "0" }))).toBe(false);- expect(readLauncherHidden(fakeStorage({ [LAUNCHER_HIDDEN_KEY]: "yes" }))).toBe(false);+ expect(readLauncherHidden(memoryStorage({ [LAUNCHER_HIDDEN_KEY]: "1" }))).toBe(true);+ expect(readLauncherHidden(memoryStorage())).toBe(false);+ expect(readLauncherHidden(memoryStorage({ [LAUNCHER_HIDDEN_KEY]: "0" }))).toBe(false);+ expect(readLauncherHidden(memoryStorage({ [LAUNCHER_HIDDEN_KEY]: "yes" }))).toBe(false);});it("writes both states and notifies subscribers, so both renderers of it follow", () => {- const storage = fakeStorage();+ const storage = memoryStorage();let seen = 0;const stop = subscribeLauncherHidden(() => {seen += 1;@@ -111,14 +108,7 @@ describe("put away", () => {});it("survives a storage that throws, and still tells this session", () => {- const broken: LauncherStorage = {- getItem: () => {- throw new Error("blocked");- },- setItem: () => {- throw new Error("blocked");- },- };+ const broken = blockedStorage();expect(readLauncherHidden(broken)).toBe(false);const before = launcherHiddenVersion();expect(() => writeLauncherHidden(true, broken)).not.toThrow();@@ -185,26 +175,21 @@ describe("stored ratio", () => {});it("reads back what it wrote, under the one global key", () => {- const storage = fakeStorage();+ const storage = memoryStorage();writeLauncherRatio(0.3, storage);expect(storage.map.get(LAUNCHER_Y_KEY)).toBe("0.3");expect(readLauncherRatio(storage)).toBe(0.3);});it("falls back to the default when the entry is missing or malformed", () => {- expect(readLauncherRatio(fakeStorage())).toBe(DEFAULT_LAUNCHER_RATIO);- expect(readLauncherRatio(fakeStorage({ [LAUNCHER_Y_KEY]: "{}" }))).toBe(DEFAULT_LAUNCHER_RATIO);+ expect(readLauncherRatio(memoryStorage())).toBe(DEFAULT_LAUNCHER_RATIO);+ expect(readLauncherRatio(memoryStorage({ [LAUNCHER_Y_KEY]: "{}" }))).toBe(+ DEFAULT_LAUNCHER_RATIO,+ );});it("survives a storage that throws", () => {- const broken: LauncherStorage = {- getItem: () => {- throw new Error("blocked");- },- setItem: () => {- throw new Error("blocked");- },- };+ const broken = blockedStorage();expect(readLauncherRatio(broken)).toBe(DEFAULT_LAUNCHER_RATIO);expect(() => writeLauncherRatio(0.4, broken)).not.toThrow();});diff --git a/packages/web/test/dock-state.test.ts b/packages/web/test/dock-state.test.tsindex 724e87a0..b285cdf7 100644--- a/packages/web/test/dock-state.test.ts+++ b/packages/web/test/dock-state.test.ts@@ -1,30 +1,45 @@/**- * The dock store (features/dock/dock-state.ts): two docks (right/bottom) of uniform tabs- * — singleton panels plus per-shell terminal tabs — SCOPED per conversation like browser- * windows managing their own tabs: switching Sessions switches the whole arrangement, and- * no conversation's tabs depend on another's. An open dock with no tabs is still visible- * (it shows the picker); closing a tab removes it, and the last tab closing puts the dock- * away; a dock's own toggle hides it keeping its tabs — and, through closedDockView, the- * mounted bodies behind them.+ * The dock store (features/dock/dock-state.ts): two docks (right and bottom) of uniform tabs —+ * singleton panels and per-shell terminal tabs — scoped per conversation, the way browser+ * windows manage their own tabs. The module reads localStorage at import time, so the storage+ * is installed first (for the whole file: a reload reads it back) and the module imported after.*- * The module reads localStorage at import time, so the stub is installed first and the- * module imported dynamically.+ * - A panel opens as a right-dock tab by default and stays a singleton: opening it in the other+ * dock moves the tab, and reopening shows it where it lives; the scheduled-tasks panel and the+ * built-in browser open like any other. Closing a tab removes it, and the last one puts the+ * dock away.+ * - An open dock with no tabs is visible (the picker); toggling a dock closed keeps its tabs.+ * - Terminal tabs are one per shell, bottom by default, shown where they live rather than+ * duplicated, and mix freely with panel tabs.+ * - The whole arrangement switches with the Session and comes back on return; one Session's+ * terminals never appear in another's docks; a placeholder scope's arrangement passes to the+ * first Session chosen (a draft's to the Session it becomes, never clobbering); dead shells'+ * tabs are pruned in every scope.+ * - A tab moves to the other dock and activates there (the only tab closes its source dock); a+ * whole dock moves, merging after the target's tabs; a strip reorders only with a complete,+ * matching key list.+ * - The terminal toggle reports no tab so the caller adopts or creates one, hides and restores,+ * and brings the terminal to the front when a panel covers it.+ * - Each scope's arrangement round-trips across a reload (sizes are one preference); a stored+ * tab this build does not know is dropped, not the dock, and a malformed entry reads as empty+ * docks.+ * - Scope switches and moves are instant (no animation); toggles animate.+ * - A detached terminal tab returns to the scope it left, unless a conversation already holds+ * the shell again.+ * - There is one view per open dock; a hidden dock keeps its view to stay mounted on, an empty+ * one has none.*/import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";+import { memoryStorage } from "./helpers/storage";let dock: typeof import("../src/features/dock/dock-state");-/** The stub's backing map, so a test can assert what a RELOAD would read back. */-let store: Map<string, string>;beforeAll(async () => {- store = new Map<string, string>();+ // Not vi.stubGlobal: the package config unstubs globals before every test, and the module+ // (and the reload below) must keep reading this one storage for the whole file.Object.defineProperty(globalThis, "localStorage", {configurable: true,- value: {- getItem: (key: string) => store.get(key) ?? null,- setItem: (key: string, value: string) => void store.set(key, value),- removeItem: (key: string) => void store.delete(key),- },+ value: memoryStorage(),});dock = await import("../src/features/dock/dock-state");});@@ -302,7 +317,7 @@ describe("persistence", () => {it("reads a stored schedules tab back and drops a tab key it does not know", async () => {// A layout written by a newer build may name a kind this build lacks; the known tab// survives and the stranger is dropped, never the whole dock.- store.set(+ localStorage.setItem("penguin.dock.layout",'{"scopes": {"s": {"right": {"tabs": ["schedules", "someday"], "active": "schedules", "open": true}}}}',);@@ -326,7 +341,7 @@ describe("persistence", () => {});it("degrades a malformed stored entry to empty docks", async () => {- store.set(+ localStorage.setItem("penguin.dock.layout",'{"scopes": {"s": {"right": {"tabs": [42]}}}, "bottomRatio": "x"}',);diff --git a/packages/web/test/draft-cache.test.ts b/packages/web/test/draft-cache.test.tsindex 91344630..76811c65 100644--- a/packages/web/test/draft-cache.test.ts+++ b/packages/web/test/draft-cache.test.ts@@ -1,12 +1,17 @@/**- * Draft cache parsing/validation and storage access (the auto-cache- * foundation for draft-view):- * - parseDraft validates field by field — localStorage may be corrupted by- * external code, so bad JSON / non-object / invalid fields are always- * discarded instead of crashing the page;- * - load/save/clear are isolated by "user x Project/Session" (#68: switching- * accounts in the same browser must not leak drafts across users); storage- * errors (quota/private mode) are swallowed silently.+ * The composer's draft cache (features/chat/draft-cache.ts), kept in localStorage per user+ * and Project or Session.+ *+ * - A stored draft is validated field by field: bad JSON or a non-object reads as an empty+ * draft, wrongly typed, unknown or half fields are dropped and the rest kept (the permission+ * picks, the paired model references, the AI-prefill mark only as true, the approval mode's+ * four values, the skills list); a legacy string model id is always dropped.+ * - Saved drafts read back equal; Project and Session drafts, and two users' drafts of the+ * same Project, never read or overwrite each other (#68); a cleared draft reads as empty.+ * - Dropping the model pin keeps everything else; dropping the `[default_chat]`-seeded+ * selections keeps user content and the model pin, and changes nothing without them.+ * - A storage that throws (quota, private mode) never escapes: saving and clearing are+ * no-ops and loading is empty.*/import { describe, expect, it } from "vitest";import {@@ -19,18 +24,7 @@ import {saveDraft,sessionDraftKey,} from "../src/features/chat/draft-cache";-import type { DraftStorage } from "../src/features/chat/draft-cache";--/** In-memory storage (vitest runs in a Node environment, no localStorage). */-function memStorage(): DraftStorage & { map: Map<string, string> } {- const map = new Map<string, string>();- return {- map,- getItem: (k) => map.get(k) ?? null,- setItem: (k, v) => void map.set(k, v),- removeItem: (k) => void map.delete(k),- };-}+import { blockedStorage, memoryStorage } from "./helpers/storage";describe("parseDraft (field-by-field validation)", () => {it("keeps the permission picks it recognizes and drops the rest", () => {@@ -153,7 +147,7 @@ describe("parseDraft (field-by-field validation)", () => {describe("load / save / clear (key isolation, errors silenced)", () => {it("saved drafts read back equal; Project and Session drafts do not affect each other", () => {- const s = memStorage();+ const s = memoryStorage();saveDraft(draftKey("user-a1", "project-a"),{@@ -182,7 +176,7 @@ describe("load / save / clear (key isolation, errors silenced)", () => {});it("drafts for the same Project/Session are isolated per user: neither reads nor overwrites the other (#68)", () => {- const s = memStorage();+ const s = memoryStorage();saveDraft(draftKey("user-a1", "project-a"), { text: "A's secret draft" }, s);saveDraft(sessionDraftKey("user-a1", "session-1"), { text: "A's session draft" }, s);// Switch accounts (same browser): B reading the same Project/Session only gets an empty draft.@@ -195,7 +189,7 @@ describe("load / save / clear (key isolation, errors silenced)", () => {});it("reads back an empty draft after clear", () => {- const s = memStorage();+ const s = memoryStorage();saveDraft(draftKey("user-a1", "project-a"), { text: "to be cleared" }, s);clearDraft(draftKey("user-a1", "project-a"), s);expect(loadDraft(draftKey("user-a1", "project-a"), s)).toEqual({});@@ -205,7 +199,7 @@ describe("load / save / clear (key isolation, errors silenced)", () => {it("clearDraftModelRef drops only the model pin, keeping everything else (default-model change follow-through)", () => {// Shared by the models page and the project-settings default-model control: after the// Project default changes, the draft must follow it instead of pinning the old pick.- const s = memStorage();+ const s = memoryStorage();saveDraft(draftKey("user-a1", "project-a"),{@@ -244,7 +238,7 @@ describe("load / save / clear (key isolation, errors silenced)", () => {// reseed Agent / Workspace / approval mode from the fresh defaults, while typed text,// staged skills, the handoff/switch chips and the switch-becomes-default model// carry-over (released only by clearDraftModelRef) all survive.- const s = memStorage();+ const s = memoryStorage();saveDraft(draftKey("user-a1", "project-a"),{@@ -270,7 +264,7 @@ describe("load / save / clear (key isolation, errors silenced)", () => {});it('clearDraftChatDefaults strips any subset of the three fields (a cached "" workspace counts) and is otherwise a no-op', () => {- const s = memStorage();+ const s = memoryStorage();// A single seeded field is enough to rewrite; "" workspace is an explicit "auto temp"// pin and must be stripped like any other value (undefined-check, not truthiness).saveDraft(draftKey("user-a1", "project-a"), { text: "t", workspace: "" }, s);@@ -287,17 +281,7 @@ describe("load / save / clear (key isolation, errors silenced)", () => {});it("storage throwing (quota/private mode): save does not throw, load yields an empty draft", () => {- const broken: DraftStorage = {- getItem: () => {- throw new Error("SecurityError");- },- setItem: () => {- throw new Error("QuotaExceededError");- },- removeItem: () => {- throw new Error("SecurityError");- },- };+ const broken = blockedStorage();expect(() => saveDraft(draftKey("u", "p"), { text: "x" }, broken)).not.toThrow();expect(() => clearDraft(draftKey("u", "p"), broken)).not.toThrow();expect(loadDraft(draftKey("u", "p"), broken)).toEqual({});diff --git a/packages/web/test/draft-sessions.test.ts b/packages/web/test/draft-sessions.test.tsindex 85c9b796..e88159f2 100644--- a/packages/web/test/draft-sessions.test.ts+++ b/packages/web/test/draft-sessions.test.ts@@ -1,15 +1,17 @@/**- * Parked draft conversations (draft-sessions.ts): parking moves the ACTIVE new-chat- * draft into the per-user×Project list (model carry-over stays behind, like a- * successful send), entries round-trip through validated storage, and corrupted- * storage degrades to an empty list instead of crashing.+ * Parked draft conversations (features/chat/draft-sessions.ts), per user and Project. The+ * module keeps an in-memory mirror keyed by storage key, so every test uses its own user id.*- * Note: the module keeps an in-memory mirror keyed by storage key, so every test uses- * its own user id to stay isolated from the others' keys.+ * - Parking moves a typed active draft into the list, leaving only the model carry-over in+ * the active slot; an untyped draft parks nothing, and an AI-composed prompt is dropped+ * rather than parked. The newest parked draft sorts first.+ * - An entry updates in place (unknown ids change nothing); removing is idempotent and the+ * stored key goes with the last entry.+ * - Corrupted storage reads as an empty list, malformed entries dropped field by field.+ * - A parked draft is titled by its first non-empty line, trimmed and capped.*/import { describe, expect, it } from "vitest";import { draftKey, loadDraft, saveDraft } from "../src/features/chat/draft-cache";-import type { DraftStorage } from "../src/features/chat/draft-cache";import {draftSessionsKey,draftSessionTitle,@@ -19,20 +21,11 @@ import {saveDraftSession,} from "../src/features/chat/draft-sessions";-/** In-memory storage (vitest runs in a Node environment, no localStorage). */-function memStorage(): DraftStorage & { map: Map<string, string> } {- const map = new Map<string, string>();- return {- map,- getItem: (k) => map.get(k) ?? null,- setItem: (k, v) => void map.set(k, v),- removeItem: (k) => void map.delete(k),- };-}+import { memoryStorage } from "./helpers/storage";describe("parkActiveDraft", () => {it("moves a typed active draft into the parked list and keeps only the model carry-over", () => {- const s = memStorage();+ const s = memoryStorage();saveDraft(draftKey("u-park", "proj"),{@@ -58,7 +51,7 @@ describe("parkActiveDraft", () => {});it("parks nothing when the active draft has no typed text (empty or whitespace)", () => {- const s = memStorage();+ const s = memoryStorage();expect(parkActiveDraft("u-empty", "proj", s)).toBeNull();saveDraft(draftKey("u-empty", "proj"), { text: " \n", agentId: "a" }, s);expect(parkActiveDraft("u-empty", "proj", s)).toBeNull();@@ -67,7 +60,7 @@ describe("parkActiveDraft", () => {});it("drops an AI-composed prompt instead of parking it, keeping the model carry-over", () => {- const s = memStorage();+ const s = memoryStorage();saveDraft(draftKey("u-ai", "proj"),{@@ -88,7 +81,7 @@ describe("parkActiveDraft", () => {});it("newest parked draft sorts first", () => {- const s = memStorage();+ const s = memoryStorage();saveDraft(draftKey("u-order", "proj"), { text: "first" }, s);const first = parkActiveDraft("u-order", "proj", s)!;saveDraft(draftKey("u-order", "proj"), { text: "second" }, s);@@ -100,7 +93,7 @@ describe("parkActiveDraft", () => {describe("saveDraftSession / removeDraftSession", () => {it("updates an entry's content in place and is a no-op for unknown ids", () => {- const s = memStorage();+ const s = memoryStorage();saveDraft(draftKey("u-save", "proj"), { text: "v1" }, s);const id = parkActiveDraft("u-save", "proj", s)!;const savedAt = getDraftSession("u-save", "proj", id, s)!.savedAt;@@ -114,7 +107,7 @@ describe("saveDraftSession / removeDraftSession", () => {});it("removes entries idempotently and clears the storage key when the list empties", () => {- const s = memStorage();+ const s = memoryStorage();saveDraft(draftKey("u-rm", "proj"), { text: "bye" }, s);const id = parkActiveDraft("u-rm", "proj", s)!;removeDraftSession("u-rm", "proj", id, s);@@ -126,10 +119,10 @@ describe("saveDraftSession / removeDraftSession", () => {describe("stored-list validation", () => {it("corrupted storage degrades to an empty list; malformed entries are dropped field-by-field", () => {- const s = memStorage();+ const s = memoryStorage();s.map.set(draftSessionsKey("u-bad", "proj"), "{not json");expect(getDraftSession("u-bad", "proj", "draft-x", s)).toBeNull();- const s2 = memStorage();+ const s2 = memoryStorage();s2.map.set(draftSessionsKey("u-bad2", "proj"),JSON.stringify([diff --git a/packages/web/test/esc-layers.test.ts b/packages/web/test/esc-layers.test.tsdeleted file mode 100644index d573baae..00000000--- a/packages/web/test/esc-layers.test.ts+++ /dev/null@@ -1,47 +0,0 @@-/**- * Escape-layer stack (the UI package's src/components/overlays/esc-layers/esc-layers.ts):- * modals, drawers, sheets, the lightbox AND Dropdown menus register as layers, and Escape only- * acts on the topmost one. This is what makes one Escape close a menu opened inside a dialog- * while the dialog stays up (the next Escape closes it), and keeps nested dialogs closing one at- * a time.- */-import { describe, expect, it } from "vitest";-import { hasEscLayers, isTopEscLayer, popEscLayer, pushEscLayer } from "@prismshadow/penguin-ui";-import { expectEveryRootScanned, expectSingleHome, scanSources } from "./helpers/roots";--describe("esc layer sources", () => {- it("scan every source root, and find the stack in one place", () => {- const scan = scanSources();- expectEveryRootScanned(scan);- expectSingleHome(scan, "packages/ui/src/components/overlays/esc-layers/esc-layers.ts");- });-});--describe("esc layer stack", () => {- it("only the topmost layer may act; popping restores the one below", () => {- const modal = pushEscLayer();- expect(isTopEscLayer(modal)).toBe(true);- // An open layer is what holds the app's global shortcuts back.- expect(hasEscLayers()).toBe(true);- // A menu opened inside the modal stacks above it: the first Escape belongs to the menu.- const menu = pushEscLayer();- expect(isTopEscLayer(menu)).toBe(true);- expect(isTopEscLayer(modal)).toBe(false);- popEscLayer(menu);- expect(isTopEscLayer(modal)).toBe(true);- popEscLayer(modal);- expect(isTopEscLayer(modal)).toBe(false);- expect(hasEscLayers()).toBe(false);- });-- it("tolerates out-of-order removal (an outer layer unmounting first)", () => {- const outer = pushEscLayer();- const inner = pushEscLayer();- popEscLayer(outer); // e.g. the host dialog unmounts while its menu is still open- expect(isTopEscLayer(inner)).toBe(true);- popEscLayer(inner);- // Double-pop is a no-op, never a throw (effect cleanups can race in tests/strict mode).- popEscLayer(inner);- expect(isTopEscLayer(inner)).toBe(false);- });-});diff --git a/packages/web/test/example-fill.test.ts b/packages/web/test/example-fill.test.tsindex 6a3aef52..0f2a785f 100644--- a/packages/web/test/example-fill.test.ts+++ b/packages/web/test/example-fill.test.ts@@ -1,22 +1,16 @@/**- * Clicking a draft-screen example FILLS the composer and sends nothing.+ * What clicking a draft-screen example puts in the composer (features/chat/example-fill.ts).+ * The click fills the composer and sends nothing, so pressing Send yields exactly the message+ * the card used to submit itself.*- * Two halves. buildExampleFill decides what the composer becomes — the plain prompt (never a- * `[use_skills]` block, which the send path builds and a user cannot sensibly edit), taking the- * text body outright so a typed draft is cleared rather than appended to, with the example's- * installed skills joining the selection so that pressing Send produces exactly the message the- * card used to submit itself.- * And the click path in draft-view.tsx, checked with the TypeScript parser the way- * test/command-policy-add-rule.test.ts checks JSX structure: a regex cannot tell which handler- * an onClick names, and "the card no longer submits" is precisely a claim about that handler.+ * - The text body becomes the plain prompt, verbatim, replacing whatever was there — never a+ * `[use_skills]` block, which the send path builds and a user cannot sensibly edit.+ * - The example's skills join the selection when the Agent has them installed, without+ * duplicates; an example that pins nothing leaves the selection as it was.*/import { describe, expect, it } from "vitest";-import { readFileSync } from "node:fs";-import { fileURLToPath } from "node:url";-import ts from "typescript";import { buildExampleFill } from "../src/features/chat/example-fill";import { buildSkillsMessage } from "../src/features/chat/skill-use";-import { zh } from "../src/lib/strings";const PROMPT = "Build a cute penguin sledding game.";@@ -30,8 +24,10 @@ const fill = (over: Partial<Parameters<typeof buildExampleFill>[0]> = {}) =>});describe("buildExampleFill — what lands in the text body", () => {- it("puts the plain prompt in an empty composer", () => {+ it("is exactly the example's prompt, newlines and all", () => {expect(fill().text).toBe(PROMPT);+ const multiline = "Line one.\n\n- a list item\n- another";+ expect(fill({ prompt: multiline }).text).toBe(multiline);});it("never writes the [use_skills] block into the textarea", () => {@@ -42,24 +38,6 @@ describe("buildExampleFill — what lands in the text body", () => {expect(f.text).not.toContain("use_skills");expect(f.text).not.toBe(buildSkillsMessage(["web-design"], PROMPT));});-- it("clears a typed draft rather than appending behind it", () => {- // A click asks for THIS prompt; leaving the old text in front made the user find and- // delete the leftover half themselves.- expect(fill({ prompt: PROMPT }).text).toBe(PROMPT);- });-- it("leaves nothing of a previous example behind when a second one is clicked", () => {- // Browsing the list must not stack one canned prompt behind another.- const second = fill({ prompt: "Other prompt." });- expect(second.text).toBe("Other prompt.");- expect(second.text).not.toContain(PROMPT);- });-- it("carries the dictionary prompt through verbatim, newlines and all", () => {- const prompt = zh.chat.exampleTasks.gamecenter.prompt;- expect(fill({ prompt }).text).toBe(prompt);- });});describe("buildExampleFill — what lands in the skills dropdown", () => {@@ -92,75 +70,3 @@ describe("buildExampleFill — what lands in the skills dropdown", () => {expect(fill({ selectedSkills, installedSkills: selectedSkills }).skills).toEqual(["memory"]);});});--const SOURCE = fileURLToPath(new URL("../src/features/chat/draft-view.tsx", import.meta.url));-const source = ts.createSourceFile(- SOURCE,- readFileSync(SOURCE, "utf8"),- ts.ScriptTarget.Latest,- /* setParentNodes */ true,- ts.ScriptKind.TSX,-);--/** Attribute text of the first JSX element carrying `marker` among its attributes. */-function attributes(marker: string): string | null {- let found: string | null = null;- const visit = (node: ts.Node): void => {- if (found !== null) return;- const tag = ts.isJsxSelfClosingElement(node)- ? node- : ts.isJsxElement(node)- ? node.openingElement- : null;- if (tag) {- const text = tag.attributes.getText(source);- if (text.includes(marker)) {- found = text;- return;- }- }- ts.forEachChild(node, visit);- };- visit(source);- return found;-}--/** Body of a top-level-ish `const <name> = …` declaration (the click handler). */-function declaration(name: string): string | null {- let found: string | null = null;- const visit = (node: ts.Node): void => {- if (found === null && ts.isVariableDeclaration(node) && node.name.getText(source) === name) {- found = node.getText(source);- }- ts.forEachChild(node, visit);- };- visit(source);- return found;-}--describe("the example row's click path", () => {- it("routes the click to the fill handler", () => {- const attrs = attributes("copy.desc");- expect(attrs, "the example row button").not.toBeNull();- expect(attrs).toContain("fillExample(task)");- });-- it("cannot send: the handler neither posts a task nor creates a Session", () => {- const handler = declaration("fillExample");- expect(handler, "the fillExample handler").not.toBeNull();- expect(handler).toContain("composerRef.current?.fillPrompt");- expect(handler).not.toContain("onSend");- expect(handler).not.toContain("api.");- });-- it("hands the composer handle to ChatInput, or the click would land nowhere", () => {- expect(attributes('status="idle"')).toContain("controlRef={composerRef}");- });-- it("keeps no submit-time machinery on the rows", () => {- const text = source.getFullText();- // The spinner and the shared in-flight guard were the auto-submit's; filling is instant.- expect(text).not.toContain("exampleBusy");- expect(text).not.toContain("keepDraft");- });-});diff --git a/packages/web/test/example-tasks.test.ts b/packages/web/test/example-tasks.test.tsindex bed2fb3d..2d44fcd3 100644--- a/packages/web/test/example-tasks.test.ts+++ b/packages/web/test/example-tasks.test.ts@@ -1,22 +1,24 @@+/**+ * The draft screen's example prompts (features/chat/example-tasks.ts and the dictionaries).+ * They are sent to an Agent as written, so what they must carry is a contract with the skills+ * and schedules that read them, held in both languages alike.+ *+ * - The two agent-evolution prompts carry the ids and targets the build and optimization skills+ * read, name the skills in the order they run, stay short, and leave out what the Agent works+ * out itself.+ * - The folders stay within one row of each other, so the draft page's height does not jump.+ * - Every scheduled-task example says when it fires (never in cron syntax), and the two that+ * need an answer run in the conversation the user is in.+ * - The short example prompts stay under their length ceilings and keep their core in both+ * locales.+ * - The investment Copilot example keeps its "not investment advice" framing.+ */import { describe, expect, it } from "vitest";-import { EXAMPLE_FOLDERS, EXAMPLE_TASKS } from "../src/features/chat/example-tasks";-import { buildSkillsMessage } from "../src/features/chat/skill-use";+import { EXAMPLE_FOLDERS } from "../src/features/chat/example-tasks";import { en } from "../src/lib/strings-en";import { zh } from "../src/lib/strings";describe("draft example tasks", () => {- it.each(["agentBenchmarkBuild", "agentOptimization"] as const)(- "submits the %s prompt without an implicit Skill block",- (id) => {- const task = EXAMPLE_TASKS.find((candidate) => candidate.id === id);- expect(task).toBeDefined();- expect(task?.skills).toEqual([]);- expect(buildSkillsMessage([...(task?.skills ?? [])], zh.chat.exampleTasks[id].prompt)).toBe(- zh.chat.exampleTasks[id].prompt,- );- },- );-it.each([{locale: "zh",@@ -103,23 +105,6 @@ describe("draft example tasks", () => {});describe("draft example catalog", () => {- it("gives every folder and every example copy in both dictionaries", () => {- const ids = EXAMPLE_TASKS.map((task) => task.id);- expect(new Set(ids).size).toBe(ids.length);- for (const dict of [zh, en]) {- for (const folder of EXAMPLE_FOLDERS) {- expect(dict.chat.exampleFolders[folder.id]).not.toBe("");- }- for (const id of ids) {- const copy = dict.chat.exampleTasks[id];- expect(copy.label).not.toBe("");- expect(copy.desc).not.toBe("");- // The prompt is the request; the description is only the row's tooltip for it.- expect(copy.prompt.length).toBeGreaterThan(copy.desc.length);- }- }- });-// The draft page reserves no scroll area: its height is the folder rows plus the open// folder's rows, so a folder much longer than its siblings makes that height jump.it("keeps the folders within one row of each other", () => {@@ -129,13 +114,6 @@ describe("draft example catalog", () => {});describe("scheduled-task examples", () => {- const scheduleIds = ["dailyPlan", "githubDigest", "memoryReview"] as const;-- it("files them all in the schedules folder", () => {- const folder = EXAMPLE_FOLDERS.find((candidate) => candidate.id === "schedules");- expect(folder?.tasks.map((task) => task.id)).toEqual([...scheduleIds]);- });-// Two things a shortened schedule brief cannot lose. WHEN it fires: a schedule with no time// in it is not a schedule, and the Agent has nothing to ask about it that would not be a// guess. And, for the two check-ins that need the user to answer, that they run in thediff --git a/packages/web/test/finance-tree.test.ts b/packages/web/test/finance-tree.test.tsindex e69bfa62..0ee12cbb 100644--- a/packages/web/test/finance-tree.test.ts+++ b/packages/web/test/finance-tree.test.ts@@ -1,9 +1,21 @@/**- * finance-tree.ts unit tests: the spend tree along the reporting line, the ticket ledger- * along parent tickets and the rows its fold leaves visible, period arithmetic, the budget- * tone thresholds, the marks the state column carries, the trend series and its axis breaks,- * the KPI row's numbers, the alert grouping, and the two row tooltips that carry what the- * tables dropped a column for.+ * A company's finance page, as pure data (features/company/finance-tree.ts).+ *+ * - The spend tree walks the reporting line depth first; an unknown manager starts a tree of+ * its own. The ticket ledger nests children under parents the same way.+ * - The ledger shows the roots alone until a parent is expanded, one level per expanded+ * parent, never below a folded ancestor, and a childless row has nothing to fold.+ * - Periods move by whole months across years; other shapes are refused.+ * - A budget reads success under 80%, attention from 80%, danger from 100%, muted without one.+ * - Each day becomes a trend point on its date carrying its cost; the axis breaks after a+ * skipped calendar day (across months too) and never around an unparsable date.+ * - The KPI row measures the total against the root's budget (leaving budget and ratio out+ * without one) and counts budgets, warnings and pauses.+ * - Alerts group into paused and warned, a paused alert under paused only, newest first.+ * - The row tooltips name every figure the tables dropped a column for, with stand-ins for a+ * missing budget or owner.+ * - The state column leads with the live state and adds what the budget did, says paused+ * once however it is spelled, and stands on the budget alone without a live state.*/import { describe, expect, it } from "vitest";import type { OrgFinanceEmployee, OrgFinanceTicket } from "@prismshadow/penguin-server/api";@@ -142,19 +154,14 @@ describe("budgetTone", () => {});describe("financeSeries", () => {- it("shapes daily costs as the trend chart's points", () => {- expect(financeSeries([{ date: "2026-09-01", cost: 2.5 }])).toEqual([- {- bucket: "2026-09-01",- cacheRead: 0,- cacheWrite: 0,- output: 0,- total: 0,- cost: 2.5,- requests: 0,- completed: 0,- denominator: 0,- },+ it("makes each day a trend point on its date carrying its cost", () => {+ const points = financeSeries([+ { date: "2026-09-01", cost: 2.5 },+ { date: "2026-09-02", cost: 0 },+ ]);+ expect(points.map((p) => [p.bucket, p.cost])).toEqual([+ ["2026-09-01", 2.5],+ ["2026-09-02", 0],]);});});diff --git a/packages/web/test/group-list.test.ts b/packages/web/test/group-list.test.tsindex 9f7cf16b..8448e618 100644--- a/packages/web/test/group-list.test.ts+++ b/packages/web/test/group-list.test.ts@@ -1,76 +1,30 @@/**- * group-list.tsx pure helpers: the sidebar header's mode-dependent create button —- * the created object follows the grouping mode (用户口径: 具体新建的对象按分组方式决定).- * Agent grouping creates an Agent (the Agents page's existing create dialog, reached- * via route state); workspace grouping creates a Workspace (a new-chat draft — there- * is no standalone Workspace entity, one comes into being with the conversation- * created in it); time grouping buckets by last activity, which nothing can be created- * into, so it falls back to the conversation itself.+ * The sidebar header's group-list helpers (components/ui/group-list.tsx).*- * Plus the list-options menu's glyphs. The icons are decorative — every row keeps its- * own text label — but they are only worth drawing if they tell the options apart, so- * the mapping is pinned per option rather than merely asserted non-empty. Grouping reads- * its glyphs from the same map the two-icon header toggle uses, so a mode cannot end up- * wearing one icon in the toggle and another in the menu.+ * - The create button creates what the list is grouped into: an Agent in Agent grouping, a+ * Workspace (a new-chat draft) in Workspace grouping, and a conversation in time grouping,+ * which nothing can be created into.+ * - Every grouping and sort option in the list-options menu wears a different glyph, so an+ * icon tells the options apart rather than decorating them.*/import { describe, expect, it } from "vitest";-import { ICONS } from "@prismshadow/penguin-ui";import {GROUP_MODE_ICONS,SORT_MODE_ICONS,newEntityForGroupMode,} from "../src/components/ui/group-list";-import type { GroupMode } from "../src/components/ui/group-list";-import type { SessionSortMode } from "../src/lib/session-order";-import { zh } from "../src/lib/strings";-import { en } from "../src/lib/strings-en";-import { expectEveryRootScanned, expectSingleHome, scanSources, sourceFile } from "./helpers/roots";--const SCAN = scanSources();--describe("the group list's sources", () => {- it("scan every source root, and find the group list in one place", () => {- expectEveryRootScanned(SCAN);- expectSingleHome(SCAN, "packages/web/src/components/ui/group-list.tsx");- });-});describe("newEntityForGroupMode", () => {- it("agent grouping creates an Agent; workspace grouping (the default) creates a Workspace", () => {- expect(newEntityForGroupMode("agent")).toBe("agent");- expect(newEntityForGroupMode("workspace")).toBe("workspace");- });-- it("time grouping has no entity of its own, so it creates a conversation", () => {- expect(newEntityForGroupMode("time")).toBe("chat");+ it.each([+ ["agent", "agent"],+ ["workspace", "workspace"],+ ["time", "chat"],+ ] as const)("%s grouping creates a %s", (mode, entity) => {+ expect(newEntityForGroupMode(mode)).toBe(entity);});});describe("list-options glyphs", () => {- it("names each grouping mode by what the list is grouped into", () => {- // The same glyphs the header's grouping toggle shows, so the two surfaces agree.- expect(GROUP_MODE_ICONS).toEqual({- workspace: ICONS.folder,- agent: ICONS.robot,- time: ICONS.calendar,- });- });-- it("names each sort mode by what decides the order: a clock, and the reorder arrows", () => {- expect(SORT_MODE_ICONS).toEqual({ recent: ICONS.clock, manual: ICONS.arrowUpDown });- });-- it("is what the list-options menu actually renders", () => {- // The claim worth pinning is not the map's contents but that nothing re-picks an icon- // beside it: a hardcoded glyph at a call site is how a row and the mode it names would- // drift apart. Node-only suite, so this reads the sources (title-reveal.test.ts).- const sidebar = sourceFile(SCAN, "packages/web/src/components/layout/sidebar.tsx").text;- for (const mode of ["workspace", "agent", "time"] satisfies GroupMode[])- expect(sidebar).toContain(`glyph={GROUP_MODE_ICONS.${mode}}`);- for (const mode of ["recent", "manual"] satisfies SessionSortMode[])- expect(sidebar).toContain(`glyph={SORT_MODE_ICONS.${mode}}`);- });-it("gives every row a glyph that differs, so an icon distinguishes rather than decorates", () => {// The calendar of "group by time" against the clock of "sort by recency" in particular:// two rows of one menu wearing one mark would read as one setting.@@ -78,16 +32,4 @@ describe("list-options glyphs", () => {expect(icons.every((d) => d.length > 0)).toBe(true);expect(new Set(icons).size).toBe(icons.length);});-- it("leaves every row a real label in both locales — the glyph never carries the name", () => {- for (const dict of [zh, en]) {- expect(dict.chat.groupByWorkspace).toBeTruthy();- expect(dict.chat.groupByAgent).toBeTruthy();- expect(dict.chat.groupByTime).toBeTruthy();- for (const bucket of ["day", "month", "earlier"] as const)- expect(dict.chat.timeGroups[bucket]).toBeTruthy();- expect(dict.chat.sortRecent).toBeTruthy();- expect(dict.chat.sortManual).toBeTruthy();- }- });});diff --git a/packages/web/test/group-order.test.ts b/packages/web/test/group-order.test.tsindex 12e1c78e..6c54a8ac 100644--- a/packages/web/test/group-order.test.ts+++ b/packages/web/test/group-order.test.ts@@ -1,46 +1,36 @@/**- * group-order.ts unit tests: the sidebar's manual order of the GROUPS themselves- * (Workspace folders / Agents), one axis up from session-order.ts's row order.+ * The sidebar's manual order of its groups (Workspace folders / Agents), lib/group-order.ts.*- * The mode is implicit — there is no second sort toggle — so an empty stored order must- * be the identity: a Project that has never been dragged keeps the automatic sort- * exactly. Beyond that: one array per Project AND grouping mode, "time" refused at the- * store because its buckets are a fixed chronological ladder, groups with no stored- * place surfacing at the TOP (including the merged temporary-workspace group, which is- * otherwise forced last), stale keys inert, and pruning gated on a complete live set.- * Beside the stored order stands the demotion of folder-only groups — applied last, inside- * the unpinned cluster only, over the two pure predicates session-grouping.ts exports for it.+ * - Given time mode, an order is neither stored nor read back: its buckets are a fixed ladder.+ * - Given no Project or nothing stored, the order is empty and reading writes nothing.+ * - An order saved for one Project and mode reads back for exactly that pair.+ * - A malformed stored value reads as empty, keeping the well-formed keys.+ * - Given a storage that throws (or no storage at all in node), reads and writes degrade quietly.+ * - With nothing stored, the automatic sort is kept (temp group last, pins first).+ * - With a stored order, stored groups take their places, unstored ones surface on top, stale+ * keys are inert, and the pin boundary is never crossed; neither input is mutated.+ * - The merged temporary-workspace group can be dragged anywhere, like any other group.+ * - A drop splices the rendered list into the stored order: an unmoved drop writes nothing,+ * unloaded groups keep their places, pins and unpins do not fling groups, stale keys stay.+ * - The group order and each group's row order are independent.+ * - Folder-only groups sort last, never when pinned, keeping the manual order in each block.*/import { describe, expect, it } from "vitest";import {- ORDERABLE_GROUP_MODES,commitGroupOrder,groupOrderKey,- isOrderableGroupMode,loadGroupOrder,orderGroups,saveGroupOrder,} from "../src/lib/group-order";import type { GroupOrderStorage } from "../src/lib/group-order";-import { moveInSequence } from "../src/lib/session-order";import {TEMP_WORKSPACE_GROUP_KEY,foldedShare,groupSessionsByWorkspace,- groupSessionsByTime,isFolderOnly,- timeGroupKey,} from "../src/lib/session-grouping";--/** In-memory storage (vitest runs in a Node environment, no localStorage; session-order.test.ts convention). */-function memStorage(): GroupOrderStorage & { map: Map<string, string> } {- const map = new Map<string, string>();- return {- map,- getItem: (k) => map.get(k) ?? null,- setItem: (k, v) => void map.set(k, v),- };-}+import { blockedStorage, memoryStorage } from "./helpers/storage";const id = (x: string) => x;const noPins = { pinned: new Set<string>() };@@ -48,53 +38,24 @@ const noPins = { pinned: new Set<string>() };/** Minimal row shape groupSessionsByWorkspace needs. */const row = (workspace: string, createdAt: string) => ({ workspace, createdAt });-describe("orderable modes (time is excluded, at the store)", () => {- it("exactly Workspace and Agent mode are orderable", () => {- expect([...ORDERABLE_GROUP_MODES]).toEqual(["workspace", "agent"]);- expect(isOrderableGroupMode("workspace")).toBe(true);- expect(isOrderableGroupMode("agent")).toBe(true);- expect(isOrderableGroupMode("time")).toBe(false);- });-- it("time mode cannot store an order: saving writes nothing and loading stays empty", () => {- const s = memStorage();+describe("time mode (excluded at the store)", () => {+ it("time mode neither stores an order nor reads back one planted under its key", () => {+ const s = memoryStorage();saveGroupOrder("p1", "time", ["\0time-earlier", "\0time-day"], s);expect(s.map.size).toBe(0);- expect(loadGroupOrder("p1", "time", s)).toEqual([]);- });-- it("a value planted under the time-mode key is never read back", () => {- const s = memStorage();// Hand-edited storage, or an older build: the gate is on the mode, so the read never- // reaches the value. Guards against the gate drifting below the getItem call.+ // reaches the value.s.map.set("penguin.groupOrder.p1.time", JSON.stringify(["\u0000time-earlier"]));expect(loadGroupOrder("p1", "time", s)).toEqual([]);// And the workspace key of the same Project is unaffected either way.saveGroupOrder("p1", "workspace", ["/a"], s);expect(loadGroupOrder("p1", "workspace", s)).toEqual(["/a"]);- expect(loadGroupOrder("p1", "time", s)).toEqual([]);- });-- it("the time buckets keep their fixed chronological ladder — nothing in this module touches them", () => {- const buckets = groupSessionsByTime(- [- { lastActiveAt: "2020-01-01T00:00:00Z" },- { lastActiveAt: "2026-08-24T11:00:00Z" },- { lastActiveAt: "2026-08-10T00:00:00Z" },- ],- Date.parse("2026-08-24T12:00:00Z"),- );- expect(buckets.map((b) => b.bucket)).toEqual(["day", "month", "earlier"]);- // Even an order naming those keys cannot reach them: time mode never loads one.- const s = memStorage();- saveGroupOrder("p1", "time", [timeGroupKey("earlier"), timeGroupKey("day")], s);- expect(loadGroupOrder("p1", "time", s)).toEqual([]);});});describe("group-order store (per-Project × grouping-mode localStorage)", () => {it("nothing stored — or no Project yet — is empty, reading never writes, saving without a Project is a no-op", () => {- const s = memStorage();+ const s = memoryStorage();expect(loadGroupOrder("p1", "workspace", s)).toEqual([]);expect(loadGroupOrder(null, "workspace", s)).toEqual([]);expect(s.map.size).toBe(0);@@ -102,17 +63,17 @@ describe("group-order store (per-Project × grouping-mode localStorage)", () =>expect(s.map.size).toBe(0);});- it("save → load round-trips per Project; Projects are isolated", () => {- const s = memStorage();- saveGroupOrder("p1", "workspace", ["/b", "/a"], s);+ it("save → load round-trips per Project, the temp group's key included; Projects are isolated", () => {+ const s = memoryStorage();+ saveGroupOrder("p1", "workspace", ["/b", TEMP_WORKSPACE_GROUP_KEY, "/a"], s);saveGroupOrder("p2", "workspace", ["/c"], s);- expect(loadGroupOrder("p1", "workspace", s)).toEqual(["/b", "/a"]);+ expect(loadGroupOrder("p1", "workspace", s)).toEqual(["/b", TEMP_WORKSPACE_GROUP_KEY, "/a"]);expect(loadGroupOrder("p2", "workspace", s)).toEqual(["/c"]);expect(loadGroupOrder("p3", "workspace", s)).toEqual([]);});it("the two orderable modes keep separate orders (their group lists are unrelated)", () => {- const s = memStorage();+ const s = memoryStorage();saveGroupOrder("p1", "workspace", ["/b", "/a"], s);saveGroupOrder("p1", "agent", ["a2", "a1"], s);expect(loadGroupOrder("p1", "workspace", s)).toEqual(["/b", "/a"]);@@ -120,12 +81,8 @@ describe("group-order store (per-Project × grouping-mode localStorage)", () =>expect(groupOrderKey("p1", "workspace")).not.toBe(groupOrderKey("p1", "agent"));});- it("the group order lives under its own key namespace, clear of the row order's", () => {- expect(groupOrderKey("p1", "workspace")).toBe("penguin.groupOrder.p1.workspace");- });-it("malformed JSON / non-array shapes degrade to empty; junk array elements are dropped", () => {- const s = memStorage();+ const s = memoryStorage();for (const raw of ["{not json", '"/a"', "42", "null", "{}", ""]) {s.map.set(groupOrderKey("p1", "workspace"), raw);expect(loadGroupOrder("p1", "workspace", s)).toEqual([]);@@ -143,15 +100,7 @@ describe("group-order store (per-Project × grouping-mode localStorage)", () =>} as unknown as GroupOrderStorage;expect(() => loadGroupOrder("p1", "workspace", hostile)).not.toThrow();expect(loadGroupOrder("p1", "workspace", hostile)).toEqual([]);- const broken: GroupOrderStorage = {- getItem: () => {- throw new Error("denied");- },- setItem: () => {- throw new Error("denied");- },- };- expect(() => saveGroupOrder("p1", "workspace", ["/a"], broken)).not.toThrow();+ expect(() => saveGroupOrder("p1", "workspace", ["/a"], blockedStorage())).not.toThrow();});it("with NO storage injected, resolving localStorage is itself inside the try", () => {@@ -259,12 +208,6 @@ describe("the merged temporary-workspace group is draggable like any other", ()orderGroups(groups, (g) => g.key, { ...noPins, order: stored }).map((g) => g.key),).toEqual(["/home/b", TEMP_WORKSPACE_GROUP_KEY, "/home/a"]);});-- it("its key round-trips through storage like any other group key", () => {- const s = memStorage();- saveGroupOrder("p1", "workspace", [TEMP_WORKSPACE_GROUP_KEY, "/home/a"], s);- expect(loadGroupOrder("p1", "workspace", s)).toEqual([TEMP_WORKSPACE_GROUP_KEY, "/home/a"]);- });});describe("commitGroupOrder (a drop is a splice, not a rewrite)", () => {@@ -357,17 +300,11 @@ describe("commitGroupOrder (a drop is a splice, not a rewrite)", () => {"w2",]);});-- it("the underlying move is still the rows' own moveInSequence", () => {- const seq: readonly string[] = ["a", "b", "c"];- expect(moveInSequence(seq, "a", "a", true)).toBe(seq);- expect(moveInSequence(seq, "c", "a", false)).toEqual(["c", "a", "b"]);- });});describe("group order and row order are independent axes", () => {it("a group order names only group keys, so committing one cannot touch a row order array", () => {- const s = memStorage();+ const s = memoryStorage();// Same Project, same mode, different key namespaces.saveGroupOrder("p1", "workspace", ["/w2", "/w1"], s);s.map.set("penguin.sessionOrder.p1.workspace", JSON.stringify(["s2", "s1"]));diff --git a/packages/web/test/helpers/fetch.ts b/packages/web/test/helpers/fetch.tsnew file mode 100644index 00000000..1914ba88--- /dev/null+++ b/packages/web/test/helpers/fetch.ts@@ -0,0 +1,88 @@+/**+ * Outbound HTTP for the node suite: the package's one `fetch` fake.+ *+ * It stands where the browser's `fetch` does, so a test drives the real `api/endpoints`+ * wrappers and the real `apiFetch` (URL building, routing to a machine, error mapping) and+ * asserts on what went over the wire. Every request is recorded; each is answered by the test's+ * handler, which returns a Response ({@link json}, {@link apiError}), throws (the network+ * failed), or never settles. The package config sets `unstubGlobals`, so the fake is gone+ * before the next test.+ */+import { vi } from "vitest";++/** One request as the app sent it. */+export interface FetchRequest {+ readonly method: string;+ /** The URL as the app built it, query included. */+ readonly url: string;+ /** The machine a `/server/<id>/api/…` URL is routed through; null for this server. */+ readonly machine: string | null;+ /** The API path without the machine prefix and the query, still percent-encoded. */+ readonly path: string;+ readonly query: URLSearchParams;+ /** The body: parsed when it is JSON, as sent otherwise, undefined when there is none. */+ readonly body: unknown;+}++export type FetchHandler = (request: FetchRequest) => Response | Promise<Response>;++export interface FakeFetch {+ /** Every request so far, oldest first. */+ readonly requests: FetchRequest[];+ /** Answers every later request with `handler`. */+ answer(handler: FetchHandler): void;+}++/** Installs the fake as the global `fetch` for the current test. By default everything is a 404. */+export function stubFetch(handler: FetchHandler = () => apiError(404, "not_found")): FakeFetch {+ const requests: FetchRequest[] = [];+ let current = handler;+ vi.stubGlobal("fetch", async (input: string | URL, init: RequestInit = {}) => {+ const url = String(input);+ const parsed = new URL(url, "http://localhost");+ const routed = /^\/server\/([^/]+)(\/.*)$/.exec(parsed.pathname);+ const request: FetchRequest = {+ method: init.method ?? "GET",+ url,+ machine: routed ? decodeURIComponent(routed[1]!) : null,+ path: routed ? routed[2]! : parsed.pathname,+ query: parsed.searchParams,+ body: parseBody(init.body),+ };+ requests.push(request);+ return current(request);+ });+ return {+ requests,+ answer(next) {+ current = next;+ },+ };+}++function parseBody(body: RequestInit["body"]): unknown {+ if (typeof body !== "string") return body ?? undefined;+ try {+ return JSON.parse(body);+ } catch {+ return body;+ }+}++/** A JSON answer, 200 unless `status` says otherwise. */+export function json(body: unknown, status = 200, headers: Record<string, string> = {}): Response {+ return new Response(JSON.stringify(body), {+ status,+ headers: { "content-type": "application/json", ...headers },+ });+}++/** A failure in the server's error envelope, `{ error: { code, message } }`. */+export function apiError(+ status: number,+ code: string,+ message = code,+ headers: Record<string, string> = {},+): Response {+ return json({ error: { code, message } }, status, headers);+}diff --git a/packages/web/test/helpers/storage.ts b/packages/web/test/helpers/storage.tsnew file mode 100644index 00000000..5bf83d5e--- /dev/null+++ b/packages/web/test/helpers/storage.ts@@ -0,0 +1,64 @@+/**+ * Browser storage for the node suite.+ *+ * Every `*Storage` interface in src (`SessionOrderStorage`, `DraftStorage`, …) is a slice of the+ * DOM `Storage`, and the modules that read the global take `localStorage` from it. One in-memory+ * `Storage` serves both: pass {@link memoryStorage} where a function takes a storage, or install+ * it as the global with {@link stubLocalStorage}. The package config sets `unstubGlobals`, so+ * the global goes away before the next test.+ */+import { vi } from "vitest";++/** A DOM `Storage` held in memory, with the map behind it for reading back what was written. */+export interface MemoryStorage extends Storage {+ readonly map: Map<string, string>;+}++/** A `Storage` holding `entries`, nothing else. */+export function memoryStorage(entries: Record<string, string> = {}): MemoryStorage {+ const map = new Map(Object.entries(entries));+ const storage = {+ map,+ get length() {+ return map.size;+ },+ clear: () => map.clear(),+ getItem: (key: string) => map.get(key) ?? null,+ key: (index: number) => [...map.keys()][index] ?? null,+ removeItem: (key: string) => {+ map.delete(key);+ },+ setItem: (key: string, value: string) => {+ map.set(key, String(value));+ },+ };+ return storage as MemoryStorage;+}++/**+ * A `Storage` whose every call throws, the way a browser with site data blocked (or a+ * partitioned iframe) answers.+ */+export function blockedStorage(): Storage {+ const deny = (): never => {+ throw new DOMException("The operation is insecure.", "SecurityError");+ };+ return {+ get length(): number {+ return deny();+ },+ clear: deny,+ getItem: deny,+ key: deny,+ removeItem: deny,+ setItem: deny,+ } as Storage;+}++/** Installs `storage` as the global `localStorage` for the current test, and returns it. */+export function stubLocalStorage<T extends Storage = MemoryStorage>(+ storage: T = memoryStorage() as unknown as T,+): T {+ vi.stubGlobal("localStorage", storage);+ return storage;+}diff --git a/packages/web/test/icon-scale.test.ts b/packages/web/test/icon-scale.test.tsindex 67ae031d..b21122bb 100644--- a/packages/web/test/icon-scale.test.ts+++ b/packages/web/test/icon-scale.test.ts@@ -1,21 +1,23 @@/**- * The icon family as the app uses it: the role-named scale, the registry and the renderers, all in- * the shared UI package (`icon-scale.ts`, `components/icons/…`).+ * Guard: the icon family as the app uses it — the role-named scale, the registry and the+ * renderers, all in the shared UI package (`icon-scale.ts`, `components/icons/…`). A new inline+ * `<svg>` re-drawing a glyph the app already owns, at a stroke weight nobody chose, is what+ * decays, so these are source scans over the web app and the UI package.*- * These are source scans rather than render assertions, because the thing that decays is not any- * one component's output — it is a new inline `<svg>` re-drawing a glyph the app already owns, at- * a stroke weight nobody chose. The three paths asserted below each used to exist in five or six- * hand-typed copies.- *- * The scans cover the web app and the shared UI package (test/helpers/roots.ts): a glyph that moved- * into the package keeps its one home, and a copy re-typed on either side is still a second copy.+ * - The scan reads every source root and finds the icon modules in one place each; every icon+ * rung is a whole pixel value in the legible range.+ * - Each shared glyph (the control caret, the close cross, the collapse chevron, the two dock+ * marks, the memory brain, the background-task trace) is drawn in exactly one place.+ * - No literal stroke weight appears outside the ones the family chose.+ * - Every theme sets a line-family weight for `--ui-icon-stroke` in both modes, and the default+ * theme keeps the weight GlyphIcon falls back to.*/import { existsSync, readFileSync } from "node:fs";import { describe, expect, it } from "vitest";-import { ICON_GAP, ICON_SIZE } from "@prismshadow/penguin-ui";+import { ICON_SIZE } from "@prismshadow/penguin-ui";import { DEFAULT_THEME_ID, THEME_IDS, THEME_MODES } from "../../ui/src/tokens";import { analyzeThemeFile, resolveThemeValue } from "../../ui/src/testing/theme-tokens";-import { expectEveryRootScanned, expectSingleHome, scanSources, sourceFile } from "./helpers/roots";+import { expectEveryRootScanned, expectSingleHome, scanSources } from "./helpers/roots";const SCAN = scanSources();@@ -51,10 +53,6 @@ describe("icon scale", () => {expect(size).toBeLessThan(33);}});-- it("keeps the gap rungs in ascending order, as the text sizes they track are", () => {- expect(Object.values(ICON_GAP)).toEqual(["gap-1", "gap-1.5", "gap-2", "gap-3"]);- });});describe("one glyph, one home", () => {@@ -113,14 +111,6 @@ describe("stroke weights", () => {expect(strays).toEqual([]);});- it("draws the line family at the theme's stroke token, not at a literal", () => {- const glyph = sourceFile(SCAN, GLYPH_ICON).text;- expect(glyph).toContain('strokeWidth: "var(--ui-icon-stroke, 1.7)"');- // The fallback is the default theme's weight; a literal attribute beside it would be dead code- // that reads as the real weight.- expect(glyph).not.toMatch(/strokeWidth="[0-9.]+"/);- });-describe("the --ui-icon-stroke token", () => {/** The weights a theme's line family may take: Primer 1.7, Frost 1.6, Console 1.4. */const LINE_FAMILY = new Set(["1.4", "1.6", "1.7"]);diff --git a/packages/web/test/install-scope.test.ts b/packages/web/test/install-scope.test.tsindex 8d767c1f..ed686f8b 100644--- a/packages/web/test/install-scope.test.ts+++ b/packages/web/test/install-scope.test.ts@@ -1,22 +1,27 @@/**- * install-scope.ts unit tests: reconciling browser-persisted UI state against the data root- * the server is actually serving.+ * Install scope (lib/install-scope.ts): browser state that names one data root's entities is+ * swept when the server starts serving a different root, and nothing else ever is.*- * The decision table, in full — a changed install id sweeps the keys that reference server- * entities and leaves browser preferences alone; an unchanged id (every ordinary restart)- * touches nothing; a first sight with keys and no recorded id ADOPTS without sweeping, so- * upgrading into this release never destroys legitimate state; an unknown id changes- * nothing at all. Plus the two matching traps the classification exists to avoid- * (`penguin.sidebarCollapsed` under `penguin.sidebarCollapsedGroups.`,- * `penguin.terminal.theme` beside `penguin.terminal.page.id`), and storage that throws.- *- * The classification is also checked against the SOURCE rather than against a fixture: a key- * added to the app and forgotten here is the one way this module silently stops working.+ * - Every `penguin.*` key the source persists is classified — checked against the source, since+ * a key added to the app and forgotten here is the one way this module silently stops working;+ * each deliberate exclusion is still a key the source contains.+ * - An exact preference is never captured by a family that shares its stem+ * (`penguin.sidebarCollapsed` beside `penguin.sidebarCollapsedGroups.`, `penguin.terminal.theme`+ * beside `penguin.terminal.page.id`); the rule table is well formed.+ * - A changed install id sweeps the install-scoped keys, orphans of every earlier root included,+ * and keeps the preferences and every key no rule covers.+ * - An unchanged id (every ordinary restart) sweeps nothing; a first sight adopts without+ * sweeping, and the next boot is an ordinary one.+ * - A sweep whose marker cannot be written back is reported apart from one that stuck; a store+ * that throws only on enumeration sweeps nothing rather than half of it.+ * - Asking the server: an unreachable server, a null identity, a 401 and a server that never+ * answers (three seconds) all sweep nothing; blocked site data still lets boot proceed.+ * - A swept boot reloads, and the second pass cannot resurrect the dock; every other outcome+ * mounts, a sweep that could not be recorded included.+ * - A tab left open across the wipe sweeps what it re-persisted when another tab records a+ * different root, and ignores a first recording, a clear, a rewrite and every other key.*/-import fs from "node:fs";-import path from "node:path";-import { fileURLToPath } from "node:url";-import { afterEach, describe, expect, it, vi } from "vitest";+import { describe, expect, it, vi } from "vitest";import { setUnauthorizedHandler } from "../src/api/client";import {bootInstallScope,@@ -28,107 +33,88 @@ import {syncInstallScope,} from "../src/lib/install-scope";import type { InstallScopeStorage } from "../src/lib/install-scope";+import { apiError, json, stubFetch } from "./helpers/fetch";+import { expectEveryRootScanned, scanSources } from "./helpers/roots";+import type { SourceScan } from "./helpers/roots";+import { blockedStorage, memoryStorage, stubLocalStorage } from "./helpers/storage";+import type { MemoryStorage } from "./helpers/storage";++/** State that names the data root's Projects, Sessions, Workspaces and terminals. */+const INSTALL_STATE: Record<string, string> = {+ "penguin.chatDraft.admin.default_project": '{"workspace":"/srv/app","agentId":"default_agent"}',+ "penguin.chatDraft.session.admin.session-1": '{"text":"half a sentence"}',+ "penguin.chatDrafts.admin.default_project": '[{"id":"draft-abcd1234"}]',+ "penguin.sidebarWorkspaces.default_project": '[{"path":"/srv/app"}]',+ "penguin.pinnedSessions.default_project": '["session-1"]',+ "penguin.sessionOrder.default_project.workspace": '["session-1"]',+ "penguin.sessionSeen.default_project": '{"session-1":"2026-08-26T00:00:00Z"}',+ "penguin.groupOrder.default_project.workspace": '["/srv/app"]',+ "penguin.sidebarCollapsedGroups.default_project": '["/srv/app"]',+ "penguin.sidebarPinnedGroups.default_project": '["/srv/app"]',+ "penguin.lastProjectId": "default_project",+ "penguin.lastAgentId.default_project": "default_agent",+ "penguin.memoryCollapsed.admin.default_project.default_agent": '["project"]',+ "penguin.modelsExpandedGroups.default_project": '["anthropic"]',+ "penguin.modelsGroupOrder.default_project": '["anthropic"]',+ "penguin.dock.layout": '{"scopes":{"session-1":{}},"bottomRatio":0.4}',+ "penguin.terminal.page.id": "term-1",+ "penguin.orgTempSessions.admin.default_project.acme":+ '[{"sessionId":"session-2","agentId":"acme_dev","title":"Build the site"}]',+};-/** In-memory storage (vitest runs in a Node environment, no localStorage; pinned-sessions.test.ts convention). */-function memStorage(entries: Record<string, string> = {}): InstallScopeStorage & {- map: Map<string, string>;-} {- const map = new Map<string, string>(Object.entries(entries));- return {- map,- get length() {- return map.size;- },- key: (i) => [...map.keys()][i] ?? null,- getItem: (k) => map.get(k) ?? null,- setItem: (k, v) => void map.set(k, v),- removeItem: (k) => void map.delete(k),- };-}+/** This browser's preferences, whatever root it talks to. */+const PREFERENCES: Record<string, string> = {+ "penguin.theme": "dark",+ "penguin.themeId": "geek",+ "penguin.textSize": "l",+ "penguin.fontScale": "lg",+ "penguin.fontLatin": "mona-sans",+ "penguin.fontCjk": "noto-sans-sc",+ "penguin.accent": "violet",+ "penguin.currency": "CNY",+ "penguin.terminal.theme": "dark",+ "penguin.lang": "en",+ "penguin.sidebarCollapsed": "1",+ "penguin.panelWidth": "420",+ "penguin.sidebarGroupMode": "agent",+ "penguin.sidebarSortMode": "manual",+ "penguin.sidebarNavGroupCollapsed": "collapsed",+ "penguin.sidebarNavPinned": '{"models":false}',+ "penguin.steerMode": "followup",+ "penguin.dock.launcherY": "0.25",+ "penguin.dock.launcherHidden": "1",+ "penguin.files.treeVisible": "0",+ "penguin.files.treeWidth": "220",+ "penguin.files.editorWrap": "1",+ "penguin.notifications": "1",+ "penguin.keybindings": '{"v":1,"linux":{"terminal.close":"Mod+Alt+KeyW"}}',+};-/** A representative populated store: install-scoped state on the left, preferences on the right. */-function populated(): ReturnType<typeof memStorage> {- return memStorage({- "penguin.chatDraft.admin.default_project": '{"workspace":"/srv/app","agentId":"default_agent"}',- "penguin.chatDraft.session.admin.session-1": '{"text":"half a sentence"}',- "penguin.chatDrafts.admin.default_project": '[{"id":"draft-abcd1234"}]',- "penguin.sidebarWorkspaces.default_project": '[{"path":"/srv/app"}]',- "penguin.pinnedSessions.default_project": '["session-1"]',- "penguin.sessionOrder.default_project.workspace": '["session-1"]',- "penguin.sessionSeen.default_project": '{"session-1":"2026-08-26T00:00:00Z"}',- "penguin.groupOrder.default_project.workspace": '["/srv/app"]',- "penguin.sidebarCollapsedGroups.default_project": '["/srv/app"]',- "penguin.sidebarPinnedGroups.default_project": '["/srv/app"]',- "penguin.lastProjectId": "default_project",- "penguin.lastAgentId.default_project": "default_agent",- "penguin.memoryCollapsed.admin.default_project.default_agent": '["project"]',- "penguin.modelsExpandedGroups.default_project": '["anthropic"]',- "penguin.modelsGroupOrder.default_project": '["anthropic"]',- "penguin.dock.layout": '{"scopes":{"session-1":{}},"bottomRatio":0.4}',- "penguin.terminal.page.id": "term-1",- "penguin.orgTempSessions.admin.default_project.acme":- '[{"sessionId":"session-2","agentId":"acme_dev","title":"Build the site"}]',-- "penguin.theme": "dark",- "penguin.themeId": "geek",- "penguin.textSize": "l",- "penguin.fontScale": "lg",- "penguin.fontLatin": "mona-sans",- "penguin.fontCjk": "noto-sans-sc",- "penguin.accent": "violet",- "penguin.currency": "CNY",- "penguin.terminal.theme": "dark",- "penguin.lang": "en",- "penguin.sidebarCollapsed": "1",- "penguin.panelWidth": "420",- "penguin.sidebarGroupMode": "agent",- "penguin.sidebarSortMode": "manual",- "penguin.sidebarNavGroupCollapsed": "collapsed",- "penguin.sidebarNavPinned": '{"models":false}',- "penguin.steerMode": "followup",- "penguin.dock.launcherY": "0.25",- "penguin.dock.launcherHidden": "1",- "penguin.files.treeVisible": "0",- "penguin.files.treeWidth": "220",- "penguin.files.editorWrap": "1",- "penguin.notifications": "1",- "penguin.keybindings": '{"v":1,"linux":{"terminal.close":"Mod+Alt+KeyW"}}',+/** A store holding both halves, with `marker` recorded as the install id when given. */+function populated(marker?: string): MemoryStorage {+ return memoryStorage({+ ...INSTALL_STATE,+ ...PREFERENCES,+ ...(marker === undefined ? {} : { [INSTALL_ID_KEY]: marker }),});}/** Order-independent snapshot of a store, so assertions do not depend on Map insertion order. */-function snap(map: Map<string, string>): [string, string][] {- return [...map.entries()].sort(([a], [b]) => a.localeCompare(b));+function snap(entries: Iterable<[string, string]>): [string, string][] {+ return [...entries].sort(([a], [b]) => a.localeCompare(b));+}++/** `before` with the marker set to `installId`. */+function marked(before: [string, string][], installId: string): [string, string][] {+ const entries = new Map(before);+ entries.set(INSTALL_ID_KEY, installId);+ return snap(entries);}-const PREFERENCE_KEYS = [- "penguin.theme",- "penguin.themeId",- "penguin.textSize",- "penguin.fontScale",- "penguin.fontLatin",- "penguin.fontCjk",- "penguin.accent",- "penguin.currency",- "penguin.terminal.theme",- "penguin.lang",- "penguin.sidebarCollapsed",- "penguin.panelWidth",- "penguin.sidebarGroupMode",- "penguin.sidebarSortMode",- "penguin.sidebarNavGroupCollapsed",- "penguin.sidebarNavPinned",- "penguin.steerMode",- "penguin.dock.launcherY",- "penguin.dock.launcherHidden",- "penguin.files.treeVisible",- "penguin.files.treeWidth",- "penguin.files.editorWrap",- "penguin.notifications",- "penguin.keybindings",-];--const WEB_SRC = fileURLToPath(new URL("../src", import.meta.url));+/** What a populated store holds once swept onto `installId`: the preferences and the marker. */+function sweptOnto(installId: string): [string, string][] {+ return marked(Object.entries(PREFERENCES), installId);+}/*** Keys the source contains that KEY_RULES deliberately does not classify, each with the@@ -142,59 +128,40 @@ const UNCLASSIFIED_ON_PURPOSE: Record<string, string> = {};/**- * Every `penguin.*` key literal in the web source, mapped to the file it was found in.+ * Every `penguin.*` key literal in the scanned source, mapped to the file it was found in.** Block comments are stripped first, and a match must follow a quote or backtick: prose* names key PREFIXES (`penguin.terminal.`), a family without its dot, and the product's own* domain in an example URL (`penguin.ooo`), and none of those is a storage key.*/-function storageKeysInSource(): Map<string, string> {+function storageKeysIn(scan: SourceScan): Map<string, string> {const found = new Map<string, string>();- const walk = (dir: string): void => {- for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {- const full = path.join(dir, entry.name);- if (entry.isDirectory()) {- walk(full);- } else if (/\.tsx?$/.test(entry.name)) {- const code = fs.readFileSync(full, "utf8").replace(/\/\*[\s\S]*?\*\//g, "");- for (const match of code.matchAll(/["'`](penguin\.[A-Za-z0-9_.]*)/g)) {- const key = match[1]!;- if (!found.has(key)) found.set(key, path.relative(WEB_SRC, full));- }- }+ for (const file of scan.files) {+ const code = file.text.replace(/\/\*[\s\S]*?\*\//g, "");+ for (const match of code.matchAll(/["'`](penguin\.[A-Za-z0-9_.]*)/g)) {+ const key = match[1]!;+ if (!found.has(key)) found.set(key, file.id);}- };- walk(WEB_SRC);+ }return found;}describe("install-scope classification", () => {- it("classifies every penguin.* key the web source actually persists", () => {- const found = storageKeysInSource();+ it("classifies every penguin.* key the source persists, and each exclusion is still one of them", () => {+ const scan = scanSources([".ts", ".tsx"]);+ expectEveryRootScanned(scan);+ const found = storageKeysIn(scan);// A scan that finds nothing would pass every assertion below without checking anything.expect(found.size).toBeGreaterThan(20);for (const [key, file] of found) {if (key in UNCLASSIFIED_ON_PURPOSE) continue;- expect(scopeOfKey(key), `${key} (src/${file}) is missing from KEY_RULES`).not.toBeNull();+ expect(scopeOfKey(key), `${key} (${file}) is missing from KEY_RULES`).not.toBeNull();}- });-- it("keeps the deliberate exclusions honest: each is still a key the source contains", () => {- const found = storageKeysInSource();for (const key of Object.keys(UNCLASSIFIED_ON_PURPOSE)) {expect(found.has(key), `${key} is no longer in the source`).toBe(true);}});- it("covers every key the populated fixture holds, with no key both scopes", () => {- for (const key of populated().map.keys()) {- expect(scopeOfKey(key), key).not.toBeNull();- }- for (const key of PREFERENCE_KEYS) {- expect(scopeOfKey(key), key).toBe("browser");- }- });-it("an exact preference is not captured by a family that shares its stem", () => {// The two traps plain prefix matching would fall into.expect(scopeOfKey("penguin.sidebarCollapsed")).toBe("browser");@@ -203,12 +170,6 @@ describe("install-scope classification", () => {expect(scopeOfKey("penguin.terminal.page.id")).toBe("install");});- it("an unclassified key has no scope, so the sweep leaves it alone", () => {- expect(scopeOfKey("penguin.somethingAddedLater")).toBeNull();- expect(scopeOfKey("unrelated-app-key")).toBeNull();- expect(scopeOfKey(INSTALL_ID_KEY)).toBeNull();- });-it("rules are well formed: penguin-namespaced, families dotted, no duplicates", () => {const seen = new Set<string>();for (const rule of KEY_RULES) {@@ -222,104 +183,57 @@ describe("install-scope classification", () => {});describe("reconcileInstallScope", () => {- it("a changed install id sweeps install-scoped keys and keeps preferences", () => {- const storage = populated();- storage.map.set(INSTALL_ID_KEY, "root-a");+ it("a changed install id sweeps the install-scoped keys and keeps the preferences", () => {+ const storage = populated("root-a");expect(reconcileInstallScope("root-b", storage)).toBe("swept");-- for (const key of storage.map.keys()) {- expect(scopeOfKey(key), `${key} survived the sweep`).not.toBe("install");- }- for (const key of PREFERENCE_KEYS) {- expect(storage.map.has(key), key).toBe(true);- }- expect(storage.map.get("penguin.theme")).toBe("dark");- expect(storage.map.get(INSTALL_ID_KEY)).toBe("root-b");+ expect(snap(storage.map)).toEqual(sweptOnto("root-b"));});- it("the sweep collects orphans from every earlier root, not just the last one", () => {+ it("the sweep collects orphans of every earlier root, and leaves keys no rule covers", () => {// Keys are id-suffixed, so a Project or Session that no longer exists leaves an entry// nothing would ever read again. Walking the store is what reaches them.- const storage = memStorage({+ const storage = memoryStorage({[INSTALL_ID_KEY]: "root-a","penguin.chatDraft.admin.default_project": "{}","penguin.pinnedSessions.long_gone_project": '["session-9"]',"penguin.sessionSeen.another_dead_project": "{}","penguin.theme": "dark",+ "penguin.somethingAddedLater": "1",+ "unrelated-app-key": "1",});expect(reconcileInstallScope("root-b", storage)).toBe("swept");- expect([...storage.map.keys()].sort()).toEqual([INSTALL_ID_KEY, "penguin.theme"]);+ expect([...storage.map.keys()].sort()).toEqual(+ [INSTALL_ID_KEY, "penguin.somethingAddedLater", "penguin.theme", "unrelated-app-key"].sort(),+ );});it("an unchanged install id sweeps nothing (the ordinary server restart)", () => {- const storage = populated();- storage.map.set(INSTALL_ID_KEY, "root-a");- const before = new Map(storage.map);+ const storage = populated("root-a");+ const before = snap(storage.map);expect(reconcileInstallScope("root-a", storage)).toBe("unchanged");- expect(snap(storage.map)).toEqual(snap(before));+ expect(snap(storage.map)).toEqual(before);});- it("first sight — keys but no recorded id — adopts without sweeping", () => {+ it("first sight — keys but no recorded id — adopts without sweeping, and the next boot is an ordinary one", () => {const storage = populated();- const before = new Map(storage.map);+ const before = snap(storage.map);expect(reconcileInstallScope("root-a", storage)).toBe("adopted");- expect(storage.map.get(INSTALL_ID_KEY)).toBe("root-a");- storage.map.delete(INSTALL_ID_KEY);- expect(snap(storage.map)).toEqual(snap(before));- });-- it("an adopted id makes the very next boot an ordinary unchanged one", () => {- const storage = populated();- expect(reconcileInstallScope("root-a", storage)).toBe("adopted");+ expect(snap(storage.map)).toEqual(marked(before, "root-a"));expect(reconcileInstallScope("root-a", storage)).toBe("unchanged");expect(reconcileInstallScope("root-b", storage)).toBe("swept");});- it("an unknown id (server could not establish one) changes nothing at all", () => {- const storage = populated();- const before = new Map(storage.map);-- expect(reconcileInstallScope(null, storage)).toBe("unknown");- expect(snap(storage.map)).toEqual(snap(before));- });-- it("a throwing store degrades instead of escaping", () => {- const throwing: InstallScopeStorage = {- get length(): number {- throw new Error("site data is blocked");- },- key: () => {- throw new Error("site data is blocked");- },- getItem: () => {- throw new Error("site data is blocked");- },- setItem: () => {- throw new Error("site data is blocked");- },- removeItem: () => {- throw new Error("site data is blocked");- },- };- // getItem throwing reads as "nothing recorded", so this is a first sight that adopts;- // the adopting write throws too and is swallowed.- expect(() => reconcileInstallScope("root-a", throwing)).not.toThrow();- expect(reconcileInstallScope("root-a", throwing)).toBe("adopted");- });-it("a sweep whose marker cannot be recorded is reported apart from one that stuck", () => {- const storage = populated();- storage.map.set(INSTALL_ID_KEY, "root-a");+ const storage = populated("root-a");const readOnlyMarker: InstallScopeStorage = {...storage,get length(): number {return storage.length;},- key: (i) => storage.key(i),setItem: () => {throw new Error("quota exceeded");},@@ -327,110 +241,47 @@ describe("reconcileInstallScope", () => {// The keys still go; only the marker fails to land, so the next load compares again.expect(reconcileInstallScope("root-b", readOnlyMarker)).toBe("swept-unrecorded");- expect(storage.map.has("penguin.chatDraft.admin.default_project")).toBe(false);- expect(storage.map.get(INSTALL_ID_KEY)).toBe("root-a");- expect(storage.map.get("penguin.theme")).toBe("dark");+ expect(snap(storage.map)).toEqual(sweptOnto("root-a"));});it("a store that throws only on enumeration sweeps nothing rather than half of it", () => {- const storage = populated();- storage.map.set(INSTALL_ID_KEY, "root-a");- const before = new Map(storage.map);+ const storage = populated("root-a");+ const before = snap(storage.map);const half: InstallScopeStorage = {...storage,get length(): number {throw new Error("site data is blocked");},- setItem: (k, v) => storage.setItem(k, v),};expect(reconcileInstallScope("root-b", half)).toBe("swept");- before.set(INSTALL_ID_KEY, "root-b");- expect(snap(storage.map)).toEqual(snap(before));+ expect(snap(storage.map)).toEqual(marked(before, "root-b"));});});describe("syncInstallScope", () => {- afterEach(() => {- vi.unstubAllGlobals();- });-- it("reconciles against the id the server reports", async () => {- vi.stubGlobal(- "fetch",- async () =>- new Response(JSON.stringify({ installId: "root-b" }), {- status: 200,- headers: { "content-type": "application/json" },- }),- );- const storage = populated();- storage.map.set(INSTALL_ID_KEY, "root-a");-- expect(await syncInstallScope(storage)).toBe("swept");- expect(storage.map.has("penguin.chatDraft.admin.default_project")).toBe(false);- expect(storage.map.get("penguin.theme")).toBe("dark");- });-it("a server that cannot be reached sweeps nothing and never rejects", async () => {- vi.stubGlobal("fetch", async () => {+ stubFetch(() => {throw new Error("connection refused");});- const storage = populated();- storage.map.set(INSTALL_ID_KEY, "root-a");- const before = new Map(storage.map);+ const storage = populated("root-a");+ const before = snap(storage.map);await expect(syncInstallScope(storage)).resolves.toBe("unknown");- expect(snap(storage.map)).toEqual(snap(before));+ expect(snap(storage.map)).toEqual(before);});it("a server reporting a null identity sweeps nothing", async () => {- vi.stubGlobal(- "fetch",- async () =>- new Response(JSON.stringify({ installId: null }), {- status: 200,- headers: { "content-type": "application/json" },- }),- );- const storage = populated();- storage.map.set(INSTALL_ID_KEY, "root-a");- const before = new Map(storage.map);+ stubFetch(() => json({ installId: null }));+ const storage = populated("root-a");+ const before = snap(storage.map);await expect(syncInstallScope(storage)).resolves.toBe("unknown");- expect(snap(storage.map)).toEqual(snap(before));- });-- it("a storage that throws on every access still lets boot proceed", async () => {- vi.stubGlobal(- "fetch",- async () =>- new Response(JSON.stringify({ installId: "root-b" }), {- status: 200,- headers: { "content-type": "application/json" },- }),- );- const exploding = new Proxy({} as InstallScopeStorage, {- get() {- throw new Error("site data is blocked");- },- });-- // Every read reads as empty, so this looks like a first sight and adopts — an adoption- // that stores nothing, because the write throws too. Nothing is destroyed and boot- // continues, which is the whole requirement.- await expect(syncInstallScope(exploding)).resolves.toBe("adopted");+ expect(snap(storage.map)).toEqual(before);});it("a non-2xx answer sweeps nothing", async () => {- vi.stubGlobal(- "fetch",- async () =>- new Response(- JSON.stringify({ error: { code: "unauthorized", message: "Not signed in." } }),- { status: 401, headers: { "content-type": "application/json" } },- ),- );+ stubFetch(() => apiError(401, "unauthorized", "Not signed in."));// apiFetch takes a different branch from the network failure above: it parses the error// body and, for a 401 outside /api/auth/, calls the global sign-out hook. Nothing is// registered at this point in the boot — AuthProvider installs one during the first@@ -438,14 +289,13 @@ describe("syncInstallScope", () => {// hook is reached at all, since registering one EARLIER would then sign the user out.const signedOut = vi.fn();setUnauthorizedHandler(signedOut);- const storage = populated();- storage.map.set(INSTALL_ID_KEY, "root-a");- const before = new Map(storage.map);+ const storage = populated("root-a");+ const before = snap(storage.map);try {await expect(syncInstallScope(storage)).resolves.toBe("unknown");expect(signedOut).toHaveBeenCalledTimes(1);- expect(snap(storage.map)).toEqual(snap(before));+ expect(snap(storage.map)).toEqual(before);} finally {setUnauthorizedHandler(null);}@@ -456,10 +306,9 @@ describe("syncInstallScope", () => {try {// A request that never settles: the page renders nothing until this resolves, so the// bound is the whole reason the timeout exists.- vi.stubGlobal("fetch", () => new Promise<Response>(() => {}));- const storage = populated();- storage.map.set(INSTALL_ID_KEY, "root-a");- const before = new Map(storage.map);+ stubFetch(() => new Promise<Response>(() => {}));+ const storage = populated("root-a");+ const before = snap(storage.map);const pending = syncInstallScope(storage);let settled = false;@@ -472,11 +321,20 @@ describe("syncInstallScope", () => {await vi.advanceTimersByTimeAsync(1);await expect(pending).resolves.toBe("unknown");- expect(snap(storage.map)).toEqual(snap(before));+ expect(snap(storage.map)).toEqual(before);} finally {vi.useRealTimers();}});++ it("blocked site data still lets boot proceed", async () => {+ stubFetch(() => json({ installId: "root-b" }));++ // Every read reads as empty, so this looks like a first sight and adopts — an adoption+ // that stores nothing, because the write throws too. Nothing is destroyed and boot+ // continues, which is the whole requirement.+ await expect(syncInstallScope(blockedStorage())).resolves.toBe("adopted");+ });});/**@@ -498,34 +356,16 @@ describe("bootInstallScope", () => {bottomRatio: 0.4,});- function installStorageGlobal(storage: InstallScopeStorage): void {- Object.defineProperty(globalThis, "localStorage", { configurable: true, value: storage });- }-- function serverReports(installId: string | null): void {- vi.stubGlobal(- "fetch",- async () =>- new Response(JSON.stringify({ installId }), {- status: 200,- headers: { "content-type": "application/json" },- }),- );- }-- afterEach(() => {- vi.unstubAllGlobals();- Reflect.deleteProperty(globalThis, "localStorage");- vi.resetModules();- });+ const serverReports = (installId: string | null) => stubFetch(() => json({ installId }));it("a swept boot reloads instead of rendering, and the second pass cannot resurrect the dock", async () => {- const storage = memStorage({- [INSTALL_ID_KEY]: "root-a",- "penguin.dock.layout": DOCK_FROM_ROOT_A,- "penguin.theme": "dark",- });- installStorageGlobal(storage);+ const storage = stubLocalStorage(+ memoryStorage({+ [INSTALL_ID_KEY]: "root-a",+ "penguin.dock.layout": DOCK_FROM_ROOT_A,+ "penguin.theme": "dark",+ }),+ );serverReports("root-b");// Pass one. Every module evaluates before main.tsx runs a statement, so dock-state is@@ -552,29 +392,25 @@ describe("bootInstallScope", () => {});it("mounts on every outcome that swept nothing, and on a sweep that could not be recorded", async () => {- const unchanged = memStorage({ [INSTALL_ID_KEY]: "root-a" });- installStorageGlobal(unchanged);+ stubLocalStorage(memoryStorage({ [INSTALL_ID_KEY]: "root-a" }));serverReports("root-a");expect(await bootInstallScope()).toBe("mount");- const firstSight = memStorage({ "penguin.theme": "dark" });- installStorageGlobal(firstSight);+ stubLocalStorage(memoryStorage({ "penguin.theme": "dark" }));serverReports("root-a");expect(await bootInstallScope()).toBe("mount");- const unknown = memStorage({ [INSTALL_ID_KEY]: "root-a" });- installStorageGlobal(unknown);+ stubLocalStorage(memoryStorage({ [INSTALL_ID_KEY]: "root-a" }));serverReports(null);expect(await bootInstallScope()).toBe("mount");// The reload would otherwise repeat forever: sweep, fail to record, reload, sweep again.- const backing = memStorage({ [INSTALL_ID_KEY]: "root-a", "penguin.lastProjectId": "p1" });- installStorageGlobal({+ const backing = memoryStorage({ [INSTALL_ID_KEY]: "root-a", "penguin.lastProjectId": "p1" });+ stubLocalStorage({...backing,get length(): number {return backing.length;},- key: (i) => backing.key(i),setItem: () => {throw new Error("quota exceeded");},@@ -587,8 +423,7 @@ describe("bootInstallScope", () => {describe("a tab left open across the wipe", () => {it("sweeps its own re-persisted state when another tab records a different root", () => {- const storage = populated();- storage.map.set(INSTALL_ID_KEY, "root-b"); // the other tab already recorded it+ const storage = populated("root-b"); // the other tab already recorded itconst stale = reactToInstallIdChange({ key: INSTALL_ID_KEY, oldValue: "root-a", newValue: "root-b" },@@ -596,25 +431,22 @@ describe("a tab left open across the wipe", () => {);expect(stale).toBe(true);- for (const key of storage.map.keys()) {- expect(scopeOfKey(key), `${key} survived the sweep`).not.toBe("install");- }- expect(storage.map.get("penguin.theme")).toBe("dark");+ expect(snap(storage.map)).toEqual(sweptOnto("root-b"));});it("ignores the other tab's FIRST recording, which swept nothing itself", () => {const storage = populated();- const before = new Map(storage.map);+ const before = snap(storage.map);expect(reactToInstallIdChange({ key: INSTALL_ID_KEY, oldValue: null, newValue: "root-a" }, storage),).toBe(false);- expect(snap(storage.map)).toEqual(snap(before));+ expect(snap(storage.map)).toEqual(before);});it("ignores site data being cleared, and a rewrite of the same id", () => {const storage = populated();- const before = new Map(storage.map);+ const before = snap(storage.map);expect(reactToInstallIdChange({ key: INSTALL_ID_KEY, oldValue: "root-a", newValue: null }, storage),@@ -625,12 +457,12 @@ describe("a tab left open across the wipe", () => {storage,),).toBe(false);- expect(snap(storage.map)).toEqual(snap(before));+ expect(snap(storage.map)).toEqual(before);});it("ignores every other key, including the ones it would otherwise sweep", () => {const storage = populated();- const before = new Map(storage.map);+ const before = snap(storage.map);expect(reactToInstallIdChange(@@ -641,6 +473,6 @@ describe("a tab left open across the wipe", () => {expect(reactToInstallIdChange({ key: null, oldValue: null, newValue: null }, storage)).toBe(false,);- expect(snap(storage.map)).toEqual(snap(before));+ expect(snap(storage.map)).toEqual(before);});});diff --git a/packages/web/test/machine-cache.test.ts b/packages/web/test/machine-cache.test.tsindex cffadccd..67da407c 100644--- a/packages/web/test/machine-cache.test.ts+++ b/packages/web/test/machine-cache.test.ts@@ -1,9 +1,14 @@/**- * What each machine was last seen holding (lib/machine-cache.ts): replaced wholesale by the- * machine's own answer — including with nothing, which is how a deleted Session stops coming- * back — kept per machine, and degrading to nothing when storage refuses or holds junk.+ * What each machine was last seen holding (lib/machine-cache.ts), kept in localStorage so a+ * restart can show a machine's rows before it answers.+ *+ * - A machine's answer replaces only its own entry, per Project and machine.+ * - An empty answer clears the entry, so something deleted over there stops coming back.+ * - At most the placeholder's worth of rows is kept.+ * - Junk in storage reads as nothing remembered, and rows without an id are dropped.+ * - A storage that refuses is not an error: the answer is merely not remembered.*/-import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { beforeEach, describe, expect, it } from "vitest";import type { AgentSummary, SessionInfo } from "@prismshadow/penguin-server/api";import {CACHED_ROWS_PER_MACHINE,@@ -12,21 +17,7 @@ import {rememberMachineAgents,rememberMachineSessions,} from "../src/lib/machine-cache";--/** The browser's storage, as far as this module needs it. Node has none. */-function memoryStorage(): Storage {- const map = new Map<string, string>();- return {- get length() {- return map.size;- },- clear: () => map.clear(),- getItem: (k) => map.get(k) ?? null,- key: (i) => [...map.keys()][i] ?? null,- removeItem: (k) => void map.delete(k),- setItem: (k, v) => void map.set(k, String(v)),- };-}+import { blockedStorage, stubLocalStorage } from "./helpers/storage";const row = (sessionId: string): SessionInfo =>({@@ -39,12 +30,8 @@ const row = (sessionId: string): SessionInfo =>const agent = (agentId: string): AgentSummary => ({ agentId, name: agentId }) as AgentSummary;describe("machine cache", () => {- const original = (globalThis as { localStorage?: Storage }).localStorage;beforeEach(() => {- (globalThis as { localStorage?: Storage }).localStorage = memoryStorage();- });- afterEach(() => {- (globalThis as { localStorage?: Storage }).localStorage = original;+ stubLocalStorage();});it("remembers per (project, machine), and a machine's answer replaces only its own entry", () => {@@ -82,15 +69,7 @@ describe("machine cache", () => {});it("storage that refuses is not an error — the answer is merely not remembered", () => {- (globalThis as { localStorage?: Storage }).localStorage = {- ...memoryStorage(),- setItem: () => {- throw new Error("QuotaExceededError");- },- getItem: () => {- throw new Error("SecurityError");- },- } as Storage;+ stubLocalStorage(blockedStorage());expect(() => rememberMachineAgents("p", "M1", [agent("a")])).not.toThrow();expect(cachedMachineAgents("p", "M1")).toEqual([]);});diff --git a/packages/web/test/machines-probe-schedule.test.ts b/packages/web/test/machines-probe-schedule.test.tsindex ac01fae7..5a40604a 100644--- a/packages/web/test/machines-probe-schedule.test.ts+++ b/packages/web/test/machines-probe-schedule.test.ts@@ -5,6 +5,12 @@* The fingerprint deliberately excludes `checkedAt`. Every probe moves that timestamp, so* including it would make every round look like a change and pin the interval at its* shortest step forever — an ssh child per machine every 15 seconds, indefinitely.+ *+ * - The wait never exceeds ten minutes, never shortens as the quiet spell grows, and a+ * nonsensical round count reads as the first step.+ * - The fingerprint ignores `checkedAt`, and changes when a server goes down, comes up or moves+ * port, when a machine is installed, reinstalled or appears, and between "not probed yet" and+ * every real state.*/import { describe, expect, it } from "vitest";import {@@ -25,15 +31,6 @@ const machine = (});describe("probeDelayMs", () => {- it("starts at 15s and widens through a minute to a ten-minute ceiling", () => {- expect(probeDelayMs(0)).toBe(15_000);- expect(probeDelayMs(1)).toBe(30_000);- expect(probeDelayMs(2)).toBe(45_000);- expect(probeDelayMs(3)).toBe(60_000);- expect(probeDelayMs(4)).toBe(120_000);- expect(probeDelayMs(PROBE_STEPS_MS.length - 1)).toBe(600_000);- });-it("never exceeds ten minutes, however long everything has been quiet", () => {for (const rounds of [20, 100, 10_000]) expect(probeDelayMs(rounds)).toBe(600_000);});diff --git a/packages/web/test/markdown-math.test.ts b/packages/web/test/markdown-math.test.tsdeleted file mode 100644index 4d006263..00000000--- a/packages/web/test/markdown-math.test.ts+++ /dev/null@@ -1,88 +0,0 @@-/**- * The app's side of the shared Markdown pipeline: every renderer in the Web App and the shared UI- * package takes the same plugin lists, and KaTeX's fonts ship with the build. How the pipeline- * renders math is the package's own suite (packages/ui/test/prose-math.test.ts).- */-import { describe, expect, it } from "vitest";-import { dropNonWoff2FontSources } from "../vite.config.js";-import { expectEveryRootScanned, scanSources } from "./helpers/roots";--const SCAN = scanSources();--describe("the pipeline every renderer shares", () => {- /**- * A renderer that quietly dropped the shared list would still render Markdown, so no behavioural- * test would fail — only its math and its URL boundaries would be wrong, on one surface. Hence a- * source scan: every `<ReactMarkdown` in either root has to carry both stages.- */- const renderers = SCAN.files.filter(- (file) => file.name.endsWith(".tsx") && file.text.includes("<ReactMarkdown"),- );-- /**- * Matched by the constant each prop names rather than by an exact string, because `Md` picks its- * rehype stage by `streaming`. What is being guarded is that the name comes from the shared- * module, not the shape of the expression around it.- */- const SHARED = { remarkPlugins: "REMARK_PLUGINS", rehypePlugins: "REHYPE_PLUGINS" };-- /** Where each root takes the lists from: the package's own module, or the package. */- const HOME: Record<string, string> = {- ui: 'from "./markdown-plugins"',- web: 'from "@prismshadow/penguin-ui"',- };-- it("are looked for in every source root", () => {- expectEveryRootScanned(SCAN);- });-- it("are the known renderers: Md, a Trace event and a plugin's page", () => {- // The shared file browser draws its Markdown through `Md`, so it is not one of them.- expect(renderers.map((file) => file.id).sort()).toEqual([- "packages/ui/src/components/content/prose/prose.tsx",- "packages/web/src/features/plugins/plugin-detail-page.tsx",- "packages/web/src/features/traces/trace-event-row.tsx",- ]);- });-- it("every ReactMarkdown is given both shared plugin lists", () => {- let total = 0;- for (const file of renderers) {- const uses = file.text.split("<ReactMarkdown").length - 1;- total += uses;- for (const [prop, constant] of Object.entries(SHARED)) {- const values = [...file.text.matchAll(new RegExp(`${prop}=\\{([^}]*)\\}`, "g"))];- expect(values.length, `${file.id} ${prop}`).toBe(uses);- for (const [, value] of values) expect(value, `${file.id} ${prop}`).toContain(constant);- }- expect(file.text, file.id).toContain(HOME[file.root]);- }- expect(total).toBe(4); // Md, a plugin's page, two in trace-event-row- });-- it("no renderer assembles its own pipeline out of the underlying plugins", () => {- for (const file of renderers) {- // The quotes are the point: a renderer may name a plugin in a comment, not import one.- for (const plugin of ["remark-gfm", "remark-math", "rehype-katex"]) {- expect(file.text, `${file.id} imports ${plugin} directly`).not.toContain(`"${plugin}"`);- }- }- });-});--describe("KaTeX fonts ship locally, woff2 only", () => {- const SRC = `@font-face{font-display:block;font-family:KaTeX_Main;src:url(fonts/KaTeX_Main-Regular.woff2) format("woff2"),url(fonts/KaTeX_Main-Regular.woff) format("woff"),url(fonts/KaTeX_Main-Regular.ttf) format("truetype")}`;-- it("keeps the woff2 source and drops the woff and truetype ones", () => {- const stripped = dropNonWoff2FontSources(SRC);- expect(stripped).toContain('url(fonts/KaTeX_Main-Regular.woff2) format("woff2")');- expect(stripped).not.toContain(".woff)");- expect(stripped).not.toContain(".ttf)");- expect(stripped).toContain("font-family:KaTeX_Main");- });-- it("leaves a stylesheet that has no fallbacks untouched", () => {- const only = `@font-face{src:url(fonts/A.woff2) format("woff2")}`;- expect(dropNonWoff2FontSources(only)).toBe(only);- });-});diff --git a/packages/web/test/markdown-pipeline.test.ts b/packages/web/test/markdown-pipeline.test.tsnew file mode 100644index 00000000..395e8f89--- /dev/null+++ b/packages/web/test/markdown-pipeline.test.ts@@ -0,0 +1,61 @@+/**+ * Guard: every Markdown renderer in the Web App and the shared UI package uses the one shared+ * plugin pipeline (the UI package's prose/markdown-plugins.ts). A renderer that quietly dropped it+ * would still render Markdown, so no behaviour test fails; only its math and its URL boundaries go+ * wrong, on one surface. How the pipeline renders is the UI package's own suite+ * (packages/ui/test/prose-math.test.ts). The rule is held over every source file rather than a+ * list of known renderers, so a new renderer is covered the moment it is written.+ *+ * - Every `<ReactMarkdown>` is given both shared plugin lists, taken from the shared module (the+ * package's own module inside the UI package, the package entry in the Web App).+ * - No source file imports the underlying remark/rehype plugins itself.+ */+import { describe, expect, it } from "vitest";+import { expectEveryRootScanned, scanSources } from "./helpers/roots";++const SCAN = scanSources([".ts", ".tsx"]);+const SHARED_MODULE = "packages/ui/src/components/content/prose/markdown-plugins.ts";++/** Where a renderer in each root takes the lists from. */+const HOME: Record<string, string> = {+ ui: 'from "./markdown-plugins"',+ web: 'from "@prismshadow/penguin-ui"',+};++describe("the Markdown pipeline every renderer shares", () => {+ it("gives every ReactMarkdown both shared plugin lists, from the shared module", () => {+ expectEveryRootScanned(SCAN);+ const renderers = SCAN.files.filter((file) => file.text.includes("<ReactMarkdown"));+ expect(renderers.length).toBeGreaterThan(0);+ const offenders: string[] = [];+ for (const file of renderers) {+ const uses = file.text.split("<ReactMarkdown").length - 1;+ // Matched by the constant each prop names rather than by an exact string: `Md` picks its+ // rehype stage by `streaming`. What is guarded is that the name comes from the shared module.+ for (const [prop, constant] of [+ ["remarkPlugins", "REMARK_PLUGINS"],+ ["rehypePlugins", "REHYPE_PLUGINS"],+ ] as const) {+ const values = [...file.text.matchAll(new RegExp(`${prop}=\\{([^}]*)\\}`, "g"))];+ if (values.length !== uses || values.some(([, value]) => !value!.includes(constant))) {+ offenders.push(`${file.id}: ${prop}`);+ }+ }+ if (!file.text.includes(HOME[file.root]!)) offenders.push(`${file.id}: not the shared lists`);+ }+ expect(offenders).toEqual([]);+ });++ it("leaves the underlying plugins to the shared module", () => {+ // The quotes are the point: a file may name a plugin in a comment, not import one.+ const offenders = SCAN.files+ .filter((file) => file.id !== SHARED_MODULE)+ .filter((file) =>+ ["remark-gfm", "remark-math", "rehype-katex"].some((plugin) =>+ file.text.includes(`from "${plugin}"`),+ ),+ )+ .map((file) => file.id);+ expect(offenders).toEqual([]);+ });+});diff --git a/packages/web/test/memory-changes-card.test.ts b/packages/web/test/memory-changes-card.test.tsindex 904cf2a6..77fe240c 100644--- a/packages/web/test/memory-changes-card.test.ts+++ b/packages/web/test/memory-changes-card.test.ts@@ -1,10 +1,12 @@/**- * The memory-change card's header (src/features/chat/memory-changes-card.tsx): the card's- * own brain mark leads it, and the action that opens the Memory panel on its list is words.- * A second brain glyph there reads as a duplicate of the first rather than as a way into the- * list, so the header carries exactly one memory mark whether or not the action is wired.+ * The memory-change card's header (features/chat/memory-changes-card.tsx), rendered to static+ * markup. The card's own brain mark leads it; a second brain glyph on the action would read as+ * a duplicate rather than as a way into the list.*- * react-dom/server static markup (node env, no DOM), as message-stream.test.ts renders.+ * - With the Memory panel wired, the header opens the list through a text button (no tooltip,+ * no glyph), and the brain mark stays the only one.+ * - With nothing to open, there is no action and still one mark.+ * - The action's words follow the UI language.*/import { afterEach, describe, expect, it } from "vitest";import { createElement } from "react";@@ -39,7 +41,9 @@ afterEach(() => {describe("MemoryChangesCard header", () => {it("opens the list through a text action, leaving the card's own brain mark the only one", () => {const html = render(() => {});- expect(html).toMatch(/<button type="button"[^>]*>打开记忆列表<\/button>/);+ expect(html).toMatch(+ new RegExp(`<button type="button"[^>]*>${S.chat.memoryOpenList}</button>`),+ );expect(memoryMarks(html)).toBe(1);});@@ -63,6 +67,8 @@ describe("MemoryChangesCard header", () => {it("follows the UI language", () => {setActiveStrings(en);- expect(render(() => {})).toMatch(/<button type="button"[^>]*>Open memory list<\/button>/);+ const html = render(() => {});+ expect(html).toContain(en.chat.memoryOpenList);+ expect(html).not.toContain(zh.chat.memoryOpenList);});});diff --git a/packages/web/test/menu-style.test.ts b/packages/web/test/menu-style.test.tsindex 1e7c2b0a..443e0f50 100644--- a/packages/web/test/menu-style.test.ts+++ b/packages/web/test/menu-style.test.ts@@ -1,16 +1,17 @@/**- * One look for every picker and menu: Select's panel, row states and check mark, which the UI- * package owns (`menuPanelClass`, `menuRowClass`, `menuRowTone`, `ChoiceCheck` in- * components/overlays/menu-panel/menu-panel.tsx), shared by Select, OptionMenu, Dropdown and the- * pickers built on Dropdown, and the Menu rows built on them. The pieces themselves are tested in- * the package; this suite checks how the app uses them, as source, because the web suite renders- * no DOM.+ * Guard: one look for every picker and menu. Select's panel, row states and check mark are the+ * UI package's (`menuPanelClass`, `menuRowClass`, `menuRowTone`, `ChoiceCheck` in+ * components/overlays/menu-panel/menu-panel.tsx) and are tested there; this holds how the app+ * uses them.+ *+ * - The panel, rows and check live in the UI package, and no other file declares a copy.+ * - No web module hand-builds a menu row from the row classes (the Session row menu pending).+ * - No web module marks the current choice with a typed ✓.*/import { describe, expect, it } from "vitest";-import { expectSingleHome, scanSources, sourceFile } from "./helpers/roots";+import { expectSingleHome, scanSources } from "./helpers/roots";const SCAN = scanSources();-const text = (id: string) => sourceFile(SCAN, id).text;const MENU_PANEL = "packages/ui/src/components/overlays/menu-panel/menu-panel.tsx";describe("menus and pickers", () => {@@ -27,16 +28,6 @@ describe("menus and pickers", () => {expect(copies).toEqual([]);});- it("open Select's panel", () => {- for (const id of [- "packages/ui/src/components/forms/select/select.tsx",- "packages/ui/src/components/forms/select/option-menu.tsx",- "packages/ui/src/components/overlays/dropdown/dropdown.tsx",- ]) {- expect(text(id), id).toContain("${menuPanelClass}");- }- });-it("draw their rows with the Menu family, never a hand-built menu row", () => {const handBuilt = SCAN.files.filter((file) => file.root === "web")diff --git a/packages/web/test/message-item.test.ts b/packages/web/test/message-item.test.tsdeleted file mode 100644index 889e6eaf..00000000--- a/packages/web/test/message-item.test.ts+++ /dev/null@@ -1,27 +0,0 @@-/**- * How the transcript draws a message (src/features/chat/message-item.tsx): through the UI- * package's reply body and bubbles, with no Markdown, caret or bubble chrome of its own — so a- * theme's reveal and the package's tests cover what the transcript shows. vitest runs node-only- * here, so the source is read.- */-import { readFileSync } from "node:fs";-import { fileURLToPath } from "node:url";-import { describe, expect, it } from "vitest";--const item = readFileSync(- fileURLToPath(new URL("../src/features/chat/message-item.tsx", import.meta.url)),- "utf8",-);--describe("the transcript's messages (source contract)", () => {- it("renders every assistant reply through AssistantText", () => {- expect(item).toContain("<AssistantText text={item.text} streaming={item.streaming}>");- expect(item).not.toContain("▌");- expect(item).not.toMatch(/<Md\b/);- });-- it("draws what the person sent through the package's bubbles", () => {- expect(item).toContain('<MessageBubble variant="user">{text}</MessageBubble>');- expect(item).not.toContain("max-w-[88%]");- });-});diff --git a/packages/web/test/messaging-binding-editor.test.ts b/packages/web/test/messaging-binding-editor.test.tsindex 302755c7..55ddd9e4 100644--- a/packages/web/test/messaging-binding-editor.test.ts+++ b/packages/web/test/messaging-binding-editor.test.ts@@ -1,18 +1,24 @@/**- * The messaging binding editor's rendered shape (src/features/messaging/messaging-binding-editor.tsx).+ * The messaging binding editor, rendered to static markup+ * (features/messaging/messaging-binding-editor.tsx).*- * Six rules this pins, all of which are invisible to a type checker: the form opens on its- * FIELDS (the explanation lives in the collapsed FAQ under the save area, not above the first- * input), each channel's credential-source link rides the credential field's corner, that- * link's label names the place it actually opens, the connection switch — which IS the- * bind/unbind — carries that sentence as its own tooltip rather than as a line the form- * would have to make room for, a stored secret is removed by the models-page clear checkbox- * and that checkbox is gated, on screen, while the channel holds the connection, and a- * connection error's detail reaches the reader whole rather than as a few words of a shared- * row.+ * - The form opens on its fields, the explanation living in the collapsed help below; each+ * channel's credential-source link rides the credential field's corner and is labelled with+ * what it opens.+ * - A stored secret is removed through the clear checkbox, gated on screen while the channel+ * holds the connection; the connection switch carries the bind/unbind sentence as its+ * tooltip, and its gating reason when another channel holds the connection.+ * - A connection error gets its own line, whole, and stays on screen after the connection+ * recovers; arrival is reported while connecting and erroring, naming the inbound stage when+ * a message arrived but its task never started.+ * - The delivery and Markdown options close the form, each switch rendered from its own field+ * with its explanation behind a "?"; QQ's replies-only rule is stated on screen; the selector+ * offers all four channels.+ * - The help stacks three collapsed, self-titled folds with the relocated explanation, the+ * Telegram-only troubleshooting entries, and each channel's tutorial link.+ * - A Telegram test reports success with the Group Privacy caveat as a second line, nothing+ * extra when privacy is off or unknown, and a failure as one error line.*/-import { readFileSync } from "node:fs";-import { fileURLToPath } from "node:url";import { afterEach, describe, expect, it } from "vitest";import { createElement } from "react";import { renderToStaticMarkup } from "react-dom/server";@@ -539,36 +545,6 @@ describe("MessagingBindingHelp", () => {});});-describe("the Group Privacy copy, in both dictionaries", () => {- // `S` is the zh dictionary at import time, so each rule is asserted per dictionary — the- // two drifted apart once already (zh promised 三选一 and listed two options).- const entries = [- [en.messaging.troubleGroupPrivacy, "Making the bot an administrator"],- [zh.messaging.troubleGroupPrivacy, "把机器人设为该群的管理员"],- ] as const;-- it("leads the fold entry with the admin route, then the @BotFather one", () => {- // Making the bot an administrator is the only remedy that fixes the group without- // touching its membership, and it is what a user whose bot already works has done — so- // it comes first, and the /setprivacy route (which requires a re-add) follows it.- for (const [entry, adminRemedy] of entries) {- expect(entry).toContain(adminRemedy);- expect(entry).toContain("/setprivacy");- expect(entry.indexOf(adminRemedy)).toBeLessThan(entry.indexOf("/setprivacy"));- }- });-- it("points the toast at that fold instead of repeating the remedies in it", () => {- // The notice rides an `info` toast: four seconds, no hover-pause. So the toast carries- // the diagnosis and names the fold — by the fold's own title, which stays true if the- // fold is renamed — and the steps stay where they can be read.- for (const dict of [en, zh]) {- expect(dict.messaging.testPrivacyOn).toContain(dict.messaging.faqTroubleTitle);- expect(dict.messaging.testPrivacyOn).not.toContain("/setprivacy");- }- });-});-describe("telegramTestNotices", () => {it("adds the privacy notice as a second line, leaving the success line untouched", () => {// Two lines, not one longer one: the credentials passed and a direct chat will answer,@@ -602,24 +578,4 @@ describe("telegramTestNotices", () => {{ tone: "error", text: S.messaging.testFail("Unauthorized") },]);});-- it("is shown by testConnection, one toast per notice, each in its own tone", () => {- // The hook itself is out of reach from a node-only suite (`environment: "node"`, no- // jsdom), and dropping the info branch would silently lose the only line that reports- // Group Privacy — so the dispatch is pinned here (account-menu.test.ts convention).- const src = readFileSync(- fileURLToPath(- new URL("../src/features/messaging/messaging-binding-editor.tsx", import.meta.url),- ),- "utf8",- );- const loop = /for \(const notice of telegramTestNotices\(res\)\) \{[\s\S]*?\n {8}\}/.exec(src);- expect(- loop,- "testConnection should show every notice telegramTestNotices returns",- ).not.toBeNull();- expect(loop![0]).toContain("toastError(notice.text)");- expect(loop![0]).toContain("toastInfo(notice.text)");- expect(loop![0]).toContain("toastSuccess(notice.text)");- });});diff --git a/packages/web/test/modal-focus.test.ts b/packages/web/test/modal-focus.test.tsdeleted file mode 100644index 0c2563ed..00000000--- a/packages/web/test/modal-focus.test.ts+++ /dev/null@@ -1,174 +0,0 @@-/**- * Focus behaviour of the Modal primitive (the UI package's- * src/components/overlays/modal/modal.tsx), which every dialog in the app inherits: focus enters- * the panel on open, Tab and Shift+Tab cycle inside it, and focus returns to the trigger on close.- * The wiring lives in `useDialogLayer` (src/components/overlays/esc-layers/esc-layers.ts), which- * the command palette and the harness history overlay share with Modal, so what is pinned here- * holds for those two as well.- *- * `nextFocusIndex` is the arithmetic and is exercised directly. The wiring around it cannot- * be: this suite is `environment: "node"` with no jsdom, and Modal renders through- * `createPortal(…, document.body)`, so it cannot even be handed to `renderToStaticMarkup` the- * way the UI package's field.test.ts renders Field. So the wiring is asserted against the- * source, the way portal-panel-dismiss.test.ts asserts its hook's listeners — thin, but it pins- * the parts that are silent when they break: an aria attribute that reappears inside the- * `headerless` branch names only half the dialogs, and a restore target read one commit too late- * is a dialog that hands focus back to itself.- */-import { describe, expect, it } from "vitest";-import { nextFocusIndex } from "@prismshadow/penguin-ui";-import { expectEveryRootScanned, expectSingleHome, scanSources, sourceFile } from "./helpers/roots";--const SCAN = scanSources();-const MODAL = "packages/ui/src/components/overlays/modal/modal.tsx";-const LAYER = "packages/ui/src/components/overlays/esc-layers/esc-layers.ts";-const DROPDOWN = "packages/ui/src/components/overlays/dropdown/dropdown.tsx";-const modal = sourceFile(SCAN, MODAL).text;-const layer = sourceFile(SCAN, LAYER).text;-/** `useDialogLayer`'s body: the focus wiring, without the Escape hook declared above it. */-const dialogLayer = layer.slice(layer.indexOf("export function useDialogLayer("));-const dropdown = sourceFile(SCAN, DROPDOWN).text;--describe("the dialog primitives' sources", () => {- it("scan every source root, and find Modal, its layer and Dropdown in one place each", () => {- expectEveryRootScanned(SCAN);- expectSingleHome(SCAN, MODAL);- expectSingleHome(SCAN, LAYER);- expectSingleHome(SCAN, DROPDOWN);- expect(layer).toContain("export function useDialogLayer(");- });-});--/** The panel div's opening tag — the element carrying the dialog's role and its focus wiring. */-function panelTag(): string {- const tag = /<div\n\s+ref=\{panelRef\}[\s\S]*?\n {6}>/.exec(modal);- expect(tag, "the panel div should carry ref={panelRef}").not.toBeNull();- return tag![0];-}--/** The `useEffect(...)` block of `src` holding `marker`, up to and including its dependencies. */-function effectWith(src: string, marker: string): string {- const at = src.indexOf(marker);- expect(at, `expected ${marker} in esc-layers.ts`).toBeGreaterThan(-1);- const start = src.lastIndexOf("useEffect(", at);- expect(start, `${marker} should sit inside a useEffect`).toBeGreaterThan(-1);- const deps = src.indexOf("}, [", at);- return src.slice(start, src.indexOf(");", deps) + 2);-}--describe("nextFocusIndex", () => {- it("steps forward and wraps past the last element", () => {- expect(nextFocusIndex(3, 0, false)).toBe(1);- expect(nextFocusIndex(3, 2, false)).toBe(0);- });-- it("steps backward and wraps past the first element", () => {- expect(nextFocusIndex(3, 2, true)).toBe(1);- expect(nextFocusIndex(3, 0, true)).toBe(2);- });-- it("enters the ring at the end the direction implies when focus is on the panel itself", () => {- // -1 is focus sitting on the container: a dialog whose focusable content mounted after- // open, or one whose only control was just disabled. Shift+Tab must reach the last- // element, not the second-to-last — the plain modulo gets this wrong.- expect(nextFocusIndex(4, -1, false)).toBe(0);- expect(nextFocusIndex(4, -1, true)).toBe(3);- });-- it("holds a single-element ring in place rather than escaping it", () => {- expect(nextFocusIndex(1, 0, false)).toBe(0);- expect(nextFocusIndex(1, 0, true)).toBe(0);- });-});--describe("Modal dialog semantics", () => {- it("is a modal dialog on both branches, not only the headerless one", () => {- const tag = panelTag();- expect(tag).toContain('role="dialog"');- expect(tag).toContain('aria-modal="true"');- // The branch may only choose HOW the dialog is named. A role that moved back inside it- // would leave every titled dialog — the majority — as an unannounced div.- const branch = /\{\.\.\.\(headerless[\s\S]*?\)\}/.exec(tag);- expect(branch, "the headerless branch should be a spread on the panel").not.toBeNull();- expect(branch![0]).not.toContain("role");- expect(branch![0]).not.toContain("aria-modal");- });-- it("names the titled branch from its own heading instead of a second copy of the string", () => {- expect(panelTag()).toContain('"aria-labelledby": titleId');- expect(modal).toContain("<h2 id={titleId}");- // The headerless branch has no heading to point at, so it keeps the string itself.- expect(panelTag()).toContain('"aria-label": title');- });-- it("keeps the container focusable so a dialog with no controls can still hold focus", () => {- expect(panelTag()).toContain("tabIndex={-1}");- });-- it("takes its keyboard wiring from the shared dialog layer", () => {- expect(modal).toContain("useDialogLayer(open, panelRef, onClose)");- expect(panelTag()).toContain("onKeyDown={onPanelKeyDown}");- });-});--describe("Modal focus containment", () => {- it("moves focus into the panel on open, yielding to a child that autofocused", () => {- const effect = effectWith(dialogLayer, "FOCUSABLE_SELECTOR) ?? panel");- // A child with autoFocus is focused during the commit, before this effect runs; stealing- // focus back to the close button would undo it at every call site that uses autoFocus.- expect(effect).toContain("!panel.contains(document.activeElement)");- expect(effect).toContain("[open]");- });-- it("returns focus on every close path", () => {- // Keyed on `open` alone, so the cleanup runs for Escape, the close button, the overlay- // mousedown, the prop going false, and an outright unmount alike.- const effect = effectWith(dialogLayer, "restoreFocusRef.current?.focus()");- expect(effect).toContain("return () => restoreFocusRef.current?.focus();");- expect(effect).toContain("[open]");- });-- it("reads the element to return to during render, before any effect can run", () => {- // autoFocus fires in the same commit, so an effect-time read would capture a node inside- // the dialog and hand focus back to the dialog that just closed.- const capture = dialogLayer.indexOf("restoreFocusRef.current =");- expect(capture).toBeGreaterThan(-1);- expect(capture).toBeLessThan(dialogLayer.indexOf("useEffect("));- });-- it("cycles Tab within the panel, and yields to the two things that own it first", () => {- const handler = /const onPanelKeyDown = [\s\S]*?\n {2}\};/.exec(dialogLayer);- expect(handler, "onPanelKeyDown should be declared in useDialogLayer").not.toBeNull();- const body = handler![0];- expect(body).toContain("nextFocusIndex(");- expect(body).toContain("e.shiftKey");- expect(body).toContain("e.preventDefault()");- // A control that drives Tab itself (the composer's slash picker accepts a completion with- // it) marks the event handled.- expect(body).toContain("e.defaultPrevented");- // A menu or popover opened inside the dialog is portaled out of this subtree but still- // bubbles here as a React child; it owns its own focus while it is open.- expect(body).toContain("panel?.contains(document.activeElement)");- });-- it("leaves Escape on the layer stack, so only the topmost dialog closes", () => {- expect(dialogLayer).toContain("useEscLayer(open, onClose)");- expect(effectWith(layer, "const id = pushEscLayer();")).toContain("isTopEscLayer(id)");- });-});--describe("focusable selector", () => {- it("is shared with Dropdown rather than copied into it", () => {- expect(layer).toContain("export const FOCUSABLE_SELECTOR =");- expect(dropdown).toContain("querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR)");- expect(dropdown).not.toContain("a[href]");- });-- it("keeps visually hidden controls in the ring", () => {- // The app's file pickers are hidden the `sr-only` way — position/clip, not `display:- // none` — specifically so they stay Tab-reachable (hidden-file-input.tsx). A selector- // narrowed to visible boxes would drop every "upload" and "import" control in a dialog.- expect(layer).toContain("input:not([disabled])");- expect(layer).not.toContain("offsetParent");- });-});diff --git a/packages/web/test/model-picker.test.ts b/packages/web/test/model-picker.test.tsindex 9dd8df65..a9dcf1f2 100644--- a/packages/web/test/model-picker.test.ts+++ b/packages/web/test/model-picker.test.ts@@ -1,13 +1,20 @@/**- * The model-picker dialog's pure logic (model-picker-logic.ts): which groups the rail shows- * and how the key-less models stay reachable, which group is active on open, which marks a- * row wears, how search ranks and groups results across providers, and how the keyboard moves- * between the rail and the list. A short source contract pins what the node suite cannot- * render: every host opens the dialog, the dialog is the shared Modal rather than an overlay- * of its own, and a row reads as logo, name and marks rather than as an upstream id.+ * The model-picker dialog's logic (features/chat/model-picker-logic.ts).+ *+ * - The rail shows the groups holding a key-configured model, in the user's saved order; the+ * selected and the default model stay visible without a key, the toggle counts and then lists+ * the key-less ones, and with no key anywhere everything is listed with nothing to toggle.+ * - The dialog opens on the current model's group and row, else the first group with a key,+ * else the first group, else nothing.+ * - A row's marks follow the model card's order (default, vision, fast, discount): an+ * unannotated entry counts as vision-capable, a zero-cost row is free, an unpriced one+ * unmarked, and only this Project's default model is marked default.+ * - Search ranks exact, prefix, word-boundary, substring, then provider-only matches, groups+ * the results by provider best-first, and finds exactly what the old dropdown found.+ * - The keyboard wraps up and down through the list's rows or the rail's groups, moves between+ * rail and list with left, right and Tab, and names a group with ⌥/Alt+1–9 while leaving+ * ⌘/Ctrl+digit to the browser.*/-import { readFileSync } from "node:fs";-import { fileURLToPath } from "node:url";import { describe, expect, it } from "vitest";import type { ModelCredentialRowLike } from "../src/features/models/model-grouping";import {@@ -242,31 +249,3 @@ describe("keyboard", () => {expect(groupShortcutIndex(k("3", { altKey: true, shiftKey: true }))).toBeNull();});});--describe("wiring (source contract)", () => {- const read = (rel: string) => readFileSync(fileURLToPath(new URL(rel, import.meta.url)), "utf8");- const select = read("../src/features/chat/model-select.tsx");- const modal = read("../src/features/chat/model-picker-modal.tsx");- const chatInput = read("../src/features/chat/chat-input.tsx");-- it("both trigger variants open the dialog, not a dropdown", () => {- expect(select).toContain("<ModelPickerModal");- expect(select).not.toMatch(/<Dropdown\b|<FormPicker\b/);- });-- it("the dialog is the shared Modal, so stacked dialogs and Escape behave as elsewhere", () => {- expect(modal).toContain("<Modal");- expect(modal).not.toContain("createPortal");- });-- it("/model opens the same dialog", () => {- expect(chatInput).toMatch(/<ModelPickerModal[\s\S]*?open=\{modelSwitchOpen\}/);- expect(chatInput).not.toContain("ModelMenuList");- });-- it("a row reads as its provider's logo, its name and its marks; the id is only its tooltip", () => {- expect(modal).toContain("<ProviderLogo provider={m.provider}");- expect(modal).toContain("pickerRowTags(m, defaultModel");- expect(modal).not.toMatch(/>\s*\{m\.modelId\}\s*</);- });-});diff --git a/packages/web/test/nav-group-collapse.test.ts b/packages/web/test/nav-group-collapse.test.tsindex 6e461a66..13a44559 100644--- a/packages/web/test/nav-group-collapse.test.ts+++ b/packages/web/test/nav-group-collapse.test.ts@@ -1,19 +1,29 @@/**- * nav-group-collapse.ts unit tests: the sidebar's nav entries and how they fold. In- * development mode every entry — New chat, then the page manifest — is pinned (always shown)- * or collapsible (inside the area a nav-row-wide chevron button folds away; no label —- * tooltip and aria carry the collapse/expand names; arrow up = collapse, and the button- * itself stays while collapsed as the way back). New chat, Agents, Models and Plugins are- * pinned by default; a pin toggle or a drop moves an entry across, only the changes from the- * defaults are stored, and both areas keep manifest order. The fold and the pin choices each- * persist in one global localStorage key (injectable storage): a remount reads them back, and- * nothing stored / unrecognized values / throwing storage all fall back to the defaults.+ * The sidebar's nav entries and how they fold (lib/nav-group-collapse.ts): every entry — New+ * chat, then the viewer's pages — is pinned (always shown) or collapsible (inside the area the+ * chevron folds away), and the fold and the pin choices each persist in one global+ * localStorage key.+ *+ * - New chat comes first, then the viewer's pages; a member sees the admin's pages minus the+ * admin-only Machines page, and nothing else. New chat's nav label is its tooltip's, and the+ * Machines page heading is its nav label.+ * - By default New chat, Agents, Models and Plugins are pinned and the rest collapsible; a+ * member's areas are cut from their own entries.+ * - A pin toggle stores only the deviation from the default, both areas keep manifest order+ * whatever order the moves came in, moving back removes the stored choice, and a move that+ * changes nothing returns the same record. New chat is always pinned.+ * - Everything pinned leaves nothing to fold; everything collapsible folds to New chat alone.+ * - Expanded shows the pinned area then the collapsible one; collapsed shows the pinned area.+ * - With nothing stored the fold is expanded and no pin is moved, and reading writes nothing;+ * each choice persists and a remount reads it back.+ * - An unrecognized fold value reads as expanded; pin choices keep only known entries with+ * boolean values, and anything unparseable reads as none.+ * - A storage that throws (quota, private mode, a throwing getter) never escapes: storing is a+ * no-op and reading yields the defaults.*/import { describe, expect, it } from "vitest";import {- DEFAULT_PINNED_NAV_KEYS,NAV_GROUP_COLLAPSED_KEY,- NAV_GROUP_KEYS,NAV_PINNED_KEY,initialNavGroupCollapsed,initialNavPinOverrides,@@ -28,29 +38,9 @@ import {withNavPinned,} from "../src/lib/nav-group-collapse";import type { NavCollapseStorage, NavPinOverrides } from "../src/lib/nav-group-collapse";-import { NAV_ICONS } from "../src/lib/nav-icons";import { zh } from "../src/lib/strings";import { en } from "../src/lib/strings-en";--/** In-memory storage (vitest runs in a Node environment, no localStorage; draft-cache.test.ts convention). */-function memStorage(): NavCollapseStorage & { map: Map<string, string> } {- const map = new Map<string, string>();- return {- map,- getItem: (k) => map.get(k) ?? null,- setItem: (k, v) => void map.set(k, v),- };-}--/** Storage whose every call throws (quota exceeded / private mode). */-const brokenStorage: NavCollapseStorage = {- getItem: () => {- throw new Error("denied");- },- setItem: () => {- throw new Error("denied");- },-};+import { blockedStorage, memoryStorage } from "./helpers/storage";/** Storage whose GETTER throws (blocked site data): touching the method itself raises. */const hostileStorage = {@@ -60,65 +50,12 @@ const hostileStorage = {setItem: () => undefined,} as unknown as NavCollapseStorage;-describe("NAV_GROUP_KEYS", () => {- it("covers exactly the Agents → Evaluation Center range, in rendered order", () => {- // Traces is deliberately absent: the Trace panel moved into the chat toolbar's panel- // switcher (features/dock), and /traces stays reachable through its deep links only.- expect([...NAV_GROUP_KEYS]).toEqual([- "agents",- "models",- "plugins",- "machines",- "usage",- "benchmark",- ]);- // Pin the endpoints by label: a manifest edit that shifts the range shows up here.- expect(zh.nav[NAV_GROUP_KEYS[0]!]).toBe("智能体");- expect(zh.nav[NAV_GROUP_KEYS[NAV_GROUP_KEYS.length - 1]!]).toBe("评估中心");- });-- it("every entry has a zh label, an en label, and a nav icon (the sidebar renders straight off the manifest)", () => {- for (const key of NAV_GROUP_KEYS) {- expect(zh.nav[key]).toBeTruthy();- expect(en.nav[key]).toBeTruthy();- expect(NAV_ICONS[key]).toBeTruthy();- }- });-- it("New chat is not a page of the manifest: it opens a draft, not a route", () => {- expect(NAV_GROUP_KEYS as readonly string[]).not.toContain("newChat");- expect(NAV_GROUP_KEYS as readonly string[]).not.toContain("chat");- });-});-describe("navEntryKeysFor", () => {it("puts New chat first, then this user's pages", () => {expect([...navEntryKeysFor(true)]).toEqual(["newChat", ...navKeysFor(true)]);expect([...navEntryKeysFor(false)]).toEqual(["newChat", ...navKeysFor(false)]);});- it("reads one set of names in one order, in both languages", () => {- const keys = navEntryKeysFor(true);- expect(keys.map((key) => zh.nav[key])).toEqual([- "新建对话",- "智能体",- "模型库",- "插件市场",- "机器管理",- "成本中心",- "评估中心",- ]);- expect(keys.map((key) => en.nav[key])).toEqual([- "New chat",- "Agents",- "Models",- "Plugins",- "Machines",- "Cost Center",- "Evaluation Center",- ]);- });-it("New chat's nav label is the one its tooltip and the collapsed rail use", () => {expect(zh.nav.newChat).toBe(zh.chat.newSessionMenu);expect(en.nav.newChat).toBe(en.chat.newSessionMenu);@@ -131,21 +68,16 @@ describe("navEntryKeysFor", () => {});describe("navKeysFor", () => {- it("hides the admin-only entries from a member, and nothing else", () => {+ it("a member sees the admin's entries minus Machines, which the server refuses them", () => {// /api/machines is admin-gated server-side (it spawns ssh with the server account's// keys), so offering a member the row would only ever produce a 403.- expect([...navKeysFor(false)]).toEqual(["agents", "models", "plugins", "usage", "benchmark"]);- // An admin sees the whole manifest, machines included — the row it hides from a member.- // The Plugins page carries the built-in library and the deployment's registry both,- // under one key.- expect([...navKeysFor(true)]).toEqual([...NAV_GROUP_KEYS]);- expect(NAV_GROUP_KEYS as readonly string[]).toContain("machines");+ expect(navKeysFor(true)).toContain("machines");+ expect(navKeysFor(false)).toEqual(navKeysFor(true).filter((key) => key !== "machines"));});});describe("pinned vs. collapsible", () => {it("defaults: New chat, Agents, Models and Plugins pinned; the rest collapsible", () => {- expect([...DEFAULT_PINNED_NAV_KEYS]).toEqual(["newChat", "agents", "models", "plugins"]);expect(splitNavEntries(navEntryKeysFor(true), {})).toEqual({pinned: ["newChat", "agents", "models", "plugins"],collapsible: ["machines", "usage", "benchmark"],@@ -205,7 +137,7 @@ describe("pinned vs. collapsible", () => {expect(withNavPinned(overrides, "newChat", false)).toBe(overrides);expect(isNavPinned("newChat", { newChat: false })).toBe(true);expect(splitNavEntries(navEntryKeysFor(true), { newChat: false }).pinned[0]).toBe("newChat");- const storage = memStorage();+ const storage = memoryStorage();storage.setItem(NAV_PINNED_KEY, JSON.stringify({ newChat: false, usage: true }));expect(initialNavPinOverrides(storage)).toEqual({ usage: true });});@@ -225,26 +157,12 @@ describe("pinned vs. collapsible", () => {expect(splitNavEntries(navEntryKeysFor(true), overrides).pinned).toEqual(["newChat"]);expect(visibleNavKeys(true, true, overrides)).toEqual(["newChat"]);});-- it("the pin toggle's accessible names exist in both languages, pin and unpin distinct", () => {- for (const [locale, dict] of [- ["zh", zh],- ["en", en],- ] as const) {- expect(dict.nav.pinEntry, locale).toBeTruthy();- expect(dict.nav.unpinEntry, locale).toBeTruthy();- expect(dict.nav.pinEntry, locale).not.toBe(dict.nav.unpinEntry);- }- });});describe("visibleNavKeys", () => {- it("expanded shows every entry; collapsed leaves only the pinned ones visible and reachable (the sidebar renders the folded rows inert at zero height)", () => {+ it("expanded shows the viewer's every entry; collapsed leaves only the pinned ones visible and reachable (the sidebar renders the folded rows inert at zero height)", () => {expect(visibleNavKeys(false)).toEqual(navEntryKeysFor(true));expect(visibleNavKeys(true)).toEqual(["newChat", "agents", "models", "plugins"]);- });-- it("a member's nav is their own manifest, not the admin's", () => {expect(visibleNavKeys(false, false)).toEqual(navEntryKeysFor(false));expect(visibleNavKeys(true, false)).toEqual(["newChat", "agents", "models", "plugins"]);});@@ -262,29 +180,17 @@ describe("visibleNavKeys", () => {]);expect(visibleNavKeys(true, true, overrides)).toEqual(["newChat", "agents", "plugins"]);});-- it("the chevron-button toggle's accessible names exist in both languages (icon-only button: aria + tooltip carry them)", () => {- for (const [locale, dict] of [- ["zh", zh],- ["en", en],- ] as const) {- expect(dict.nav.collapseGroup, locale).toBeTruthy();- expect(dict.nav.expandGroup, locale).toBeTruthy();- // One button, two states: the same name for both would leave the state unreadable.- expect(dict.nav.collapseGroup, locale).not.toBe(dict.nav.expandGroup);- }- });});describe("persisted collapse state (one global localStorage key)", () => {it("default is expanded with nothing stored, and reading never writes", () => {- const s = memStorage();+ const s = memoryStorage();expect(initialNavGroupCollapsed(s)).toBe(false);expect(s.map.size).toBe(0);});it("toggle → store → a fresh mount-time read restores the collapsed state", () => {- const s = memStorage();+ const s = memoryStorage();// Collapse: what the sidebar renders shrinks to the pinned entries and the toggle …storeNavGroupCollapsed(true, s);expect(s.map.get(NAV_GROUP_COLLAPSED_KEY)).toBe("collapsed");@@ -304,15 +210,14 @@ describe("persisted collapse state (one global localStorage key)", () => {});it("a stored collapsed state folds the collapsible area only; the pinned entries stay", () => {- const s = memStorage();- s.map.set(NAV_GROUP_COLLAPSED_KEY, "collapsed");+ const s = memoryStorage({ [NAV_GROUP_COLLAPSED_KEY]: "collapsed" });expect(initialNavGroupCollapsed(s)).toBe(true);const shown = visibleNavKeys(initialNavGroupCollapsed(s), true, initialNavPinOverrides(s));expect(shown).toEqual(["newChat", "agents", "models", "plugins"]);});it("unrecognized stored values fall back to expanded", () => {- const s = memStorage();+ const s = memoryStorage();for (const raw of ["", "true", "1", "COLLAPSED", "yes"]) {s.map.set(NAV_GROUP_COLLAPSED_KEY, raw);expect(initialNavGroupCollapsed(s)).toBe(false);@@ -320,8 +225,9 @@ describe("persisted collapse state (one global localStorage key)", () => {});it("storage throwing (quota/private mode): store does not throw, read yields the default", () => {- expect(() => storeNavGroupCollapsed(true, brokenStorage)).not.toThrow();- expect(initialNavGroupCollapsed(brokenStorage)).toBe(false);+ const broken = blockedStorage();+ expect(() => storeNavGroupCollapsed(true, broken)).not.toThrow();+ expect(initialNavGroupCollapsed(broken)).toBe(false);});it("storage whose GETTER throws (blocked site data) degrades instead of escaping the useState initializer", () => {@@ -332,13 +238,13 @@ describe("persisted collapse state (one global localStorage key)", () => {describe("persisted pin choices (one global localStorage key)", () => {it("nothing stored reads as no choices — the defaults — and reading never writes", () => {- const s = memStorage();+ const s = memoryStorage();expect(initialNavPinOverrides(s)).toEqual({});expect(s.map.size).toBe(0);});it("a move → store → a fresh mount-time read restores the areas", () => {- const s = memStorage();+ const s = memoryStorage();const moved = withNavPinned(withNavPinned({}, "models", false), "usage", true);storeNavPinOverrides(moved, s);expect(JSON.parse(s.map.get(NAV_PINNED_KEY)!)).toEqual({ models: false, usage: true });@@ -351,30 +257,34 @@ describe("persisted pin choices (one global localStorage key)", () => {});it("only the deviations are stored: moving back empties the record", () => {- const s = memStorage();+ const s = memoryStorage();storeNavPinOverrides(withNavPinned(withNavPinned({}, "models", false), "models", true), s);expect(s.map.get(NAV_PINNED_KEY)).toBe("{}");});it("keys this build does not know are ignored, so a page without a stored choice takes its default", () => {- const s = memStorage();- s.map.set(- NAV_PINNED_KEY,- JSON.stringify({ traces: true, apps: false, models: false, machines: true }),- );+ const s = memoryStorage({+ [NAV_PINNED_KEY]: JSON.stringify({+ traces: true,+ apps: false,+ models: false,+ machines: true,+ }),+ });// machines is admin-only but still a manifest key: an admin's choice survives a member's// visit in the same browser.expect(initialNavPinOverrides(s)).toEqual({ models: false, machines: true });});it("a value that is not a boolean is ignored, and the entry keeps its default", () => {- const s = memStorage();- s.map.set(NAV_PINNED_KEY, JSON.stringify({ models: "false", usage: 1, agents: null }));+ const s = memoryStorage({+ [NAV_PINNED_KEY]: JSON.stringify({ models: "false", usage: 1, agents: null }),+ });expect(initialNavPinOverrides(s)).toEqual({});});it("unparseable or non-object values read as no choices", () => {- const s = memStorage();+ const s = memoryStorage();for (const raw of ["", "{", "null", "[]", '["models"]', "true", "7", '"models"']) {s.map.set(NAV_PINNED_KEY, raw);expect(initialNavPinOverrides(s), raw).toEqual({});@@ -382,8 +292,9 @@ describe("persisted pin choices (one global localStorage key)", () => {});it("storage throwing (quota/private mode): store does not throw, read yields the defaults", () => {- expect(() => storeNavPinOverrides({ models: false }, brokenStorage)).not.toThrow();- expect(initialNavPinOverrides(brokenStorage)).toEqual({});+ const broken = blockedStorage();+ expect(() => storeNavPinOverrides({ models: false }, broken)).not.toThrow();+ expect(initialNavPinOverrides(broken)).toEqual({});});it("storage whose GETTER throws degrades instead of escaping the useState initializer", () => {diff --git a/packages/web/test/new-chat.test.ts b/packages/web/test/new-chat.test.tsindex be7f9e8d..9197eae0 100644--- a/packages/web/test/new-chat.test.ts+++ b/packages/web/test/new-chat.test.ts@@ -1,32 +1,23 @@/**- * What a "New chat" entry point starts (src/features/chat/new-chat.ts):- * - newChatAgentId: the Project's `[default_chat].agent_id` while it names a listed Agent, else- * default_agent, else the first Agent;- * - prepareNewChatDraft: parks typed text, then rewrites the active slot to the model carry-over- * and staged skills alone, releasing everything else an earlier visit left there.+ * What a "New chat" entry point starts (features/chat/new-chat.ts). draft-sessions.ts keeps an+ * in-memory mirror keyed by storage key, so every test uses its own user id.*- * Note: draft-sessions.ts keeps an in-memory mirror keyed by storage key, so every test uses- * its own user id to stay isolated from the others' keys.+ * - The new chat starts on the Project's default Agent while it names a listed Agent, else+ * default_agent wherever it sits, else the first Agent, else none.+ * - Preparing the draft parks typed text with its selections, then leaves only the model+ * carry-over and staged skills in the active slot: a text-less draft's other selections+ * and an emptied evaluation draft's run mark are released, a slot holding nothing it keeps+ * is emptied, and an empty slot is left alone.*/import { describe, expect, it } from "vitest";import type { AgentSummary } from "@prismshadow/penguin-server/api";import { draftKey, loadDraft, saveDraft } from "../src/features/chat/draft-cache";-import type { DraftStorage } from "../src/features/chat/draft-cache";import { getDraftSession } from "../src/features/chat/draft-sessions";import { newChatAgentId, prepareNewChatDraft } from "../src/features/chat/new-chat";+import { memoryStorage } from "./helpers/storage";const agent = (agentId: string) => ({ agentId }) as AgentSummary;-/** In-memory storage (vitest runs in a Node environment, no localStorage). */-function memStorage(): DraftStorage {- const map = new Map<string, string>();- return {- getItem: (k) => map.get(k) ?? null,- setItem: (k, v) => void map.set(k, v),- removeItem: (k) => void map.delete(k),- };-}-describe("newChatAgentId", () => {const agents = [agent("coder"), agent("default_agent"), agent("writer")];@@ -54,7 +45,7 @@ describe("newChatAgentId", () => {describe("prepareNewChatDraft", () => {it("releases the selections a text-less draft left behind, keeping the model and staged skills", () => {- const s = memStorage();+ const s = memoryStorage();// What an abandoned Workspace-group "+" leaves: its path and an Agent, pinned by the draft// page's persist-on-mount, with nothing typed.saveDraft(@@ -77,7 +68,7 @@ describe("prepareNewChatDraft", () => {});it("drops an emptied evaluation draft's run mark, so the next New chat is not an evaluation run", () => {- const s = memStorage();+ const s = memoryStorage();// Evaluation Center -> Use -> Evaluate seeds the slot with a composed prompt marked as an// evaluation run. Editing the prompt drops aiPrefill, and deleting all of it leaves this// behind (the draft page's persist): no text to park, but the run mark is still set, and a@@ -105,7 +96,7 @@ describe("prepareNewChatDraft", () => {});it("empties a slot that holds nothing it keeps", () => {- const s = memStorage();+ const s = memoryStorage();saveDraft(draftKey("u-nothing-kept", "proj"),{ text: " ", agentId: "coder", handoffAgentId: "writer", source: "benchmark" },@@ -116,7 +107,7 @@ describe("prepareNewChatDraft", () => {});it("parks typed text with its selections, leaving only the model carry-over in the slot", () => {- const s = memStorage();+ const s = memoryStorage();saveDraft(draftKey("u-typed", "proj"),{@@ -143,7 +134,7 @@ describe("prepareNewChatDraft", () => {});it("is a no-op on an empty slot", () => {- const s = memStorage();+ const s = memoryStorage();expect(prepareNewChatDraft("u-empty", "proj", s)).toBeNull();expect(loadDraft(draftKey("u-empty", "proj"), s)).toEqual({});});diff --git a/packages/web/test/notice-chart-hooks.test.ts b/packages/web/test/notice-chart-hooks.test.tsindex a5838334..4b714a8a 100644--- a/packages/web/test/notice-chart-hooks.test.ts+++ b/packages/web/test/notice-chart-hooks.test.ts@@ -1,15 +1,16 @@/**- * The notice and chart hooks on the real app: every notice renders through the package's- * NoticeStrip (so it carries `ui-notice` and a `data-tone` in the hook's words), the toast- * included, a mark a call site draws before a notice's text sits in its icon slot, and the charts'- * roots carry `ui-chart` with their parts named by literal `data-part` values.+ * Guard: the notice hook themes restyle (the `ui-notice` box and its icon slot) is written in one+ * place. What NoticeStrip and the toast render is the UI package's to test+ * (packages/ui/test/notice-strip.test.ts, toaster.test.ts).+ *+ * - NoticeStrip and the toaster live in the UI package, one copy each.+ * - No file but NoticeStrip spells the `ui-notice` hook.+ * - A mark a call site draws inside a NoticeStrip sits in its icon slot, so a theme that draws+ * its own tone mark can hide it (the check is exercised on known shapes too).*/import ts from "typescript";-import { createElement } from "react";-import { renderToStaticMarkup } from "react-dom/server";import { describe, expect, it } from "vitest";-import { NOTICE_TONE, NoticeStrip, ToastStack } from "@prismshadow/penguin-ui";-import { expectSingleHome, scanSources, sourceFile } from "./helpers/roots";+import { expectSingleHome, scanSources } from "./helpers/roots";const SCAN = scanSources();@@ -22,32 +23,12 @@ describe("notices", () => {expectSingleHome(SCAN, TOASTER);});- it("render the hook with the tone in the hook's words", () => {- const html = renderToStaticMarkup(- createElement(NoticeStrip, { tone: "attention", className: "px-3" }, "Heads up"),- );- expect(html).toContain("ui-notice");- expect(html).toContain('data-tone="warning"');- expect(new Set(Object.values(NOTICE_TONE))).toEqual(- new Set(["info", "success", "warning", "danger", "neutral"]),- );- });-- it("go through NoticeStrip, the toast included", () => {- // The strip is the one place a notice's box is spelled: no other file writes the hook.+ it("go through NoticeStrip: no other file spells the hook", () => {const own = SCAN.files.filter((file) => file.name.endsWith(".tsx") && file.id !== NOTICE_STRIP).filter((file) => /\bui-notice\b/.test(file.text.replace(/\/\*[\s\S]*?\*\/|\/\/.*/g, ""))).map((file) => file.id);expect(own).toEqual([]);- const html = renderToStaticMarkup(- createElement(ToastStack, {- items: [{ id: 1, kind: "error", text: "Connection failed" }],- onDismiss: () => {},- }),- );- expect(html).toContain("ui-notice");- expect(html).toContain('data-tone="danger"');});});@@ -136,42 +117,3 @@ describe("a notice's own mark", () => {).toEqual([]);});});--const CHARTS = "packages/ui/src/components/charts";-const CHART_MARKS = `${CHARTS}/marks/marks.tsx`;-const TIMELINE_BAR = `${CHARTS}/marks/timeline-bar.tsx`;--describe("charts", () => {- it("live in the shared UI package, one copy each", () => {- // The primitives' marks.tsx is left out: the icon marks share its file name.- for (const id of [- TIMELINE_BAR,- `${CHARTS}/chart-style.ts`,- `${CHARTS}/chart-frame/chart-frame.tsx`,- `${CHARTS}/chart-frame/chart-geom.ts`,- `${CHARTS}/token-donut/token-donut.tsx`,- `${CHARTS}/sparkline/sparkline.tsx`,- `${CHARTS}/ring/ring.tsx`,- `${CHARTS}/legend/legend.tsx`,- ]) {- expectSingleHome(SCAN, id);- }- });-- it("carry ui-chart on their roots and name their parts", () => {- for (const id of [- `${CHARTS}/chart-frame/chart-frame.tsx`,- `${CHARTS}/token-donut/token-donut.tsx`,- `${CHARTS}/sparkline/sparkline.tsx`,- `${CHARTS}/ring/ring.tsx`,- "packages/web/src/features/traces/timeline-chart.tsx",- ]) {- expect(sourceFile(SCAN, id).text, id).toContain("ui-chart");- }- // The parts are written by the chart primitives, the one place marks are drawn.- const parts = [CHART_MARKS, TIMELINE_BAR].map((id) => sourceFile(SCAN, id).text).join("\n");- for (const part of ["series", "area", "bar", "point", "grid", "axis"]) {- expect(parts, part).toMatch(new RegExp(`data-part(?:=|": )"${part}"`));- }- });-});diff --git a/packages/web/test/notification-pref.test.ts b/packages/web/test/notification-pref.test.tsindex dd8ea80f..f082f037 100644--- a/packages/web/test/notification-pref.test.ts+++ b/packages/web/test/notification-pref.test.ts@@ -1,13 +1,22 @@/*** The task-completion notification's opt-in (lib/notification-pref): what the stored- * preference reads as, and what a request for OS permission does to it.+ * preference reads as, and what a request for OS permission does to it. The preference and+ * the permission are separate facts, and the switch must never latch on over notifications+ * that can never be shown.*- * The defect this covers is that the preference and the permission are separate facts.- * Nothing may store the opt-in unless the platform granted permission in that same- * request, or the switch latches on over notifications that can never be shown — and the- * default has to be off, because turning it on is what opens the system prompt.+ * - The opt-in is off unless the stored value is exactly the on marker.+ * - A write round-trips and tells the subscribers (until they unsubscribe).+ * - A storage that throws costs persistence only: reads are off and writes do not throw.+ * - A platform with no Notification API is unsupported and is asked nothing; otherwise the+ * platform's own answer passes through, falling back to the live permission when the+ * request answers with neither.+ * - Turning the preference on stores the opt-in only when the request came back granted,+ * judged by the request's answer rather than the permission it started from; a denial, a+ * dismissed prompt and a missing API all leave it off.+ * - The hint under the switch is silent until something needs saying, names a dismissed+ * prompt, and keeps a refusal or a missing API on screen.*/-import { afterEach, describe, expect, it, vi } from "vitest";+import { describe, expect, it, vi } from "vitest";import {NOTIFICATIONS_KEY,enableNotifications,@@ -19,19 +28,7 @@ import {subscribeNotificationsEnabled,writeNotificationsEnabled,} from "../src/lib/notification-pref";-import type { NotificationStorage } from "../src/lib/notification-pref";--/** In-memory storage: vitest runs in a Node environment, so there is no localStorage. */-function fakeStorage(entries: Record<string, string> = {}): NotificationStorage & {- map: Map<string, string>;-} {- const map = new Map(Object.entries(entries));- return {- map,- getItem: (k) => map.get(k) ?? null,- setItem: (k, v) => void map.set(k, v),- };-}+import { blockedStorage, memoryStorage } from "./helpers/storage";/*** A platform whose permission answer is fixed. `requestPermission` records its calls so a@@ -49,18 +46,16 @@ function stubNotification(permission: NotificationPermission): { requests: numbereturn calls;}-afterEach(() => vi.unstubAllGlobals());-describe("the stored opt-in", () => {it("is off unless the stored value is exactly the on marker", () => {- expect(readNotificationsEnabled(fakeStorage())).toBe(false);- expect(readNotificationsEnabled(fakeStorage({ [NOTIFICATIONS_KEY]: "1" }))).toBe(true);- expect(readNotificationsEnabled(fakeStorage({ [NOTIFICATIONS_KEY]: "0" }))).toBe(false);- expect(readNotificationsEnabled(fakeStorage({ [NOTIFICATIONS_KEY]: "true" }))).toBe(false);+ expect(readNotificationsEnabled(memoryStorage())).toBe(false);+ expect(readNotificationsEnabled(memoryStorage({ [NOTIFICATIONS_KEY]: "1" }))).toBe(true);+ expect(readNotificationsEnabled(memoryStorage({ [NOTIFICATIONS_KEY]: "0" }))).toBe(false);+ expect(readNotificationsEnabled(memoryStorage({ [NOTIFICATIONS_KEY]: "true" }))).toBe(false);});it("round-trips a write and tells its subscribers", () => {- const storage = fakeStorage();+ const storage = memoryStorage();let notified = 0;const stop = subscribeNotificationsEnabled(() => {notified += 1;@@ -80,14 +75,7 @@ describe("the stored opt-in", () => {});it("survives storage that throws, which only costs persistence", () => {- const broken: NotificationStorage = {- getItem: () => {- throw new Error("site data blocked");- },- setItem: () => {- throw new Error("site data blocked");- },- };+ const broken = blockedStorage();expect(readNotificationsEnabled(broken)).toBe(false);expect(() => writeNotificationsEnabled(true, broken)).not.toThrow();});@@ -121,7 +109,7 @@ describe("asking the platform for permission", () => {describe("turning the preference on", () => {it("stores the opt-in once the request came back granted", async () => {- const storage = fakeStorage();+ const storage = memoryStorage();const calls = stubNotification("granted");await expect(enableNotifications(storage)).resolves.toBe("granted");@@ -129,36 +117,24 @@ describe("turning the preference on", () => {expect(readNotificationsEnabled(storage)).toBe(true);});- it("does not latch on when the platform denies", async () => {- const storage = fakeStorage();- stubNotification("denied");-- await expect(enableNotifications(storage)).resolves.toBe("denied");- expect(readNotificationsEnabled(storage)).toBe(false);- expect(storage.map.has(NOTIFICATIONS_KEY)).toBe(false);- });-- it("does not latch on when the prompt is dismissed, which leaves the answer at default", async () => {- const storage = fakeStorage();- stubNotification("default");+ it.each(["denied", "default", "unsupported"] as const)(+ "does not latch on when the answer is %s (a refusal, a dismissed prompt, no API at all)",+ async (answer) => {+ const storage = memoryStorage();+ if (answer === "unsupported") vi.stubGlobal("Notification", undefined);+ else stubNotification(answer);- await expect(enableNotifications(storage)).resolves.toBe("default");- expect(readNotificationsEnabled(storage)).toBe(false);- });-- it("does not latch on where the platform has no notifications at all", async () => {- const storage = fakeStorage();- vi.stubGlobal("Notification", undefined);-- await expect(enableNotifications(storage)).resolves.toBe("unsupported");- expect(readNotificationsEnabled(storage)).toBe(false);- });+ await expect(enableNotifications(storage)).resolves.toBe(answer);+ expect(readNotificationsEnabled(storage)).toBe(false);+ expect(storage.map.has(NOTIFICATIONS_KEY)).toBe(false);+ },+ );it("takes the answer the request gave, not the permission it started from", async () => {// The real sequence, which a stub answering with a fixed permission cannot express:// the permission is "default" until the prompt is answered, and only the request// reports what the user chose.- const storage = fakeStorage();+ const storage = memoryStorage();let permission: NotificationPermission = "default";vi.stubGlobal("Notification", {get permission() {diff --git a/packages/web/test/org-draft.test.ts b/packages/web/test/org-draft.test.tsindex 274d5e31..f7037d71 100644--- a/packages/web/test/org-draft.test.ts+++ b/packages/web/test/org-draft.test.ts@@ -1,10 +1,16 @@/**- * org-draft.ts unit tests: the key's user and Project scope, the defensive parse of whatever- * is in storage, what counts as a draft worth keeping, and the round trip through an injected- * storage — including a storage that throws, which must cost the dialog nothing.+ * The create-organization dialog's draft (features/company/org-draft.ts), kept in+ * localStorage per user and Project.+ *+ * - Two users, two Projects and a signed-out browser each get their own draft.+ * - A draft is worth keeping once the user typed something; the prefilled budget does not count.+ * - A full draft round-trips; an absent, unparsable or empty stored value reads as no draft,+ * and a wrong-shaped field costs only itself.+ * - A draft with content is stored and removed once empty again; clearing one key leaves+ * another user's draft alone; a storage that throws costs the dialog nothing.*/import { describe, expect, it } from "vitest";-import type { DraftStorage, OrgCreateDraft } from "../src/features/company/org-draft";+import type { OrgCreateDraft } from "../src/features/company/org-draft";import {EMPTY_ORG_DRAFT,clearOrgDraft,@@ -15,6 +21,7 @@ import {saveOrgDraft,serializeOrgDraft,} from "../src/features/company/org-draft";+import { blockedStorage, memoryStorage } from "./helpers/storage";const draft = (over: Partial<OrgCreateDraft> = {}): OrgCreateDraft => ({...EMPTY_ORG_DRAFT,@@ -22,36 +29,17 @@ const draft = (over: Partial<OrgCreateDraft> = {}): OrgCreateDraft => ({...over,});-function memoryStorage(initial: Record<string, string> = {}): DraftStorage & {- map: Map<string, string>;-} {- const map = new Map(Object.entries(initial));- return {- map,- getItem: (k) => map.get(k) ?? null,- setItem: (k, v) => void map.set(k, v),- removeItem: (k) => void map.delete(k),- };-}--const throwingStorage: DraftStorage = {- getItem: () => {- throw new Error("private mode");- },- setItem: () => {- throw new Error("quota");- },- removeItem: () => {- throw new Error("quota");- },-};+const throwingStorage = blockedStorage();describe("orgDraftKey", () => {it("separates users and Projects, and gives a signed-out browser its own bucket", () => {- expect(orgDraftKey("alice", "p1")).toBe("penguin.orgCreateDraft.alice.p1");- expect(orgDraftKey("alice", "p1")).not.toBe(orgDraftKey("bob", "p1"));- expect(orgDraftKey("alice", "p1")).not.toBe(orgDraftKey("alice", "p2"));- expect(orgDraftKey(null, "p1")).toBe("penguin.orgCreateDraft..p1");+ const keys = [+ orgDraftKey("alice", "p1"),+ orgDraftKey("bob", "p1"),+ orgDraftKey("alice", "p2"),+ orgDraftKey(null, "p1"),+ ];+ expect(new Set(keys).size).toBe(keys.length);});});diff --git a/packages/web/test/org-examples.test.ts b/packages/web/test/org-examples.test.tsdeleted file mode 100644index 5ec849e8..00000000--- a/packages/web/test/org-examples.test.ts+++ /dev/null@@ -1,37 +0,0 @@-/**- * org-examples.ts: the four example missions offered under the create-organization- * dialog's mission field. The registry holds ids only and the chips are rendered from them,- * so an id with no entry in one of the dictionaries would render a blank chip rather than- * fail to compile — which is what this covers.- */-import { describe, expect, it } from "vitest";-import { ORG_EXAMPLES } from "../src/features/company/org-examples";-import { zh } from "../src/lib/strings";-import { en } from "../src/lib/strings-en";--describe("organization mission examples", () => {- it("lists the four in their rendered order, each id once", () => {- const ids = ORG_EXAMPLES.map((example) => example.id);- expect(ids).toEqual(["research", "agentTuning", "cloudReseller", "mirror"]);- expect(new Set(ids).size).toBe(ids.length);- });-- it("gives every example a name and a mission in both dictionaries", () => {- for (const dict of [zh, en]) {- for (const { id } of ORG_EXAMPLES) {- const copy = dict.company.missionExamples[id];- expect(copy.name).not.toBe("");- // The mission is what a click fills; the name is only the chip's one-line label, so- // a "mission" no longer than its own name is a copy mistake.- expect(copy.mission.length).toBeGreaterThan(copy.name.length);- }- }- });-- it("keeps the names distinct, so four chips never read as one", () => {- for (const dict of [zh, en]) {- const names = ORG_EXAMPLES.map(({ id }) => dict.company.missionExamples[id].name);- expect(new Set(names).size).toBe(names.length);- }- });-});diff --git a/packages/web/test/org-sessions.test.ts b/packages/web/test/org-sessions.test.tsindex 76c9205f..49c16aaa 100644--- a/packages/web/test/org-sessions.test.ts+++ b/packages/web/test/org-sessions.test.ts@@ -1,14 +1,20 @@/*** The company sidebar's 工位 group (features/company/org-sessions.ts) and the development- * list's organization filter (session-grouping): a desk row per employee in chart order- * whether or not a desk exists, the session list's live status winning over both snapshots,- * the messaging mark read from the sessions route and patched by a bind or an unbind,- * the titles the route gives the ticket sessions the Temporary group lists, the glyph a row- * draws, an employee's own state read from every Session the organization- * attributes to it — its ticket sessions included, though no list shows them as a group —- * and the render-time guard that keeps an organization's row out of the development list when- * one still reaches it (the server leaves them out of the list's own fetches; see- * sessions-own-rows.test.ts).+ * list's organization filter (lib/session-grouping.ts).+ *+ * - There is a desk row per employee in chart order, whether or not the desk was ever opened;+ * its state is the session list's live status, else the sessions route's, else the chart's.+ * - A desk row carries the messaging channel the sessions route names, follows a bind, a+ * switch and an unbind written into the loaded answer, and hands back the same answer when+ * nothing changes.+ * - The Temporary group's ticket sessions are named from the route, and nothing is named+ * before it is read.+ * - A row draws the live states and nothing once settled.+ * - An employee's own state reads every Session the organization attributes to it, running+ * while any of them runs or compacts, falling back to the snapshots; a budget pause wins.+ * - A Session belongs to an organization by either mark (an empty orgId is none), and the+ * development list drops those rows at render time whatever the switches say (its fetches+ * already leave them out; see sessions-store.test.ts).*/import { describe, expect, it } from "vitest";import type {diff --git a/packages/web/test/overview-summary.test.ts b/packages/web/test/overview-summary.test.tsindex 6aae03f5..d421a5ad 100644--- a/packages/web/test/overview-summary.test.ts+++ b/packages/web/test/overview-summary.test.ts@@ -1,8 +1,21 @@/**- * The overview page's shaping (features/company/overview-summary.ts): the employee counts,- * the board as a segmented bar, today's timeline with its marks, the spend against the- * budget, the inbox rows with their order and filters, the first-steps decision and the- * mission fold's guess.+ * The overview page's shaping (features/company/overview-summary.ts).+ *+ * - Employees are counted by desk, running and budget-paused, live states overriding the+ * snapshot where known; no employees count zero.+ * - The board lists every column in lifecycle order with its share; a missing column is zero+ * and an empty board has no shares.+ * - Today's timeline orders instances by time (the last firing over the next), marks the+ * unevaluated ones upcoming, and buckets the outcomes.+ * - Spend derives ratio and remainder from a budget (the server's ratio winning, overspend a+ * negative remainder), and neither without a budget.+ * - The inbox orders rows newest first (undated last, ties by mention, blocked, done), says+ * what each row is about and where it leads, dates a ticket by its close then its id's day,+ * keeps the newest rows under the cap, and is empty for an older server.+ * - The filter chips count and admit rows by category.+ * - First steps: fresh while only the CEO is employed and the board is empty, the CEO first+ * while the desk was never opened, and no next step once all three are done.+ * - The mission fold is offered for a mission with a line break or longer than a line.*/import { describe, expect, it } from "vitest";import type {@@ -12,10 +25,7 @@ import type {OrgTicketItem,} from "@prismshadow/penguin-server/api";import {- BOARD_SEGMENT_TONE,- FIRST_STEPS,INBOX_ROWS,- TIMELINE_TONE,boardSummary,employeeCounts,firstSteps,@@ -88,10 +98,6 @@ describe("boardSummary", () => {expect(b.open).toBe(0);expect(b.segments.every((s) => s.count === 0 && s.share === 0)).toBe(true);});-- it("gives every column a fill tone", () => {- for (const status of TICKET_COLUMNS) expect(BOARD_SEGMENT_TONE[status]).toBeTruthy();- });});describe("todaySummary", () => {@@ -146,13 +152,6 @@ describe("todaySummary", () => {]);expect(t.entries[0]?.at).toBe(Date.parse("2026-09-02T08:00:00Z"));});-- it("gives every mark a tone, failures in danger", () => {- expect(TIMELINE_TONE.missed).toBe("danger");- expect(TIMELINE_TONE.error).toBe("danger");- expect(TIMELINE_TONE.fired).toBe("success");- expect(TIMELINE_TONE.upcoming).toBe("attention");- });});describe("spendSummary", () => {@@ -385,7 +384,6 @@ describe("firstSteps", () => {});expect(s.done).toEqual({ ceo: true, hire: true, schedule: true });expect(s.next).toBeNull();- expect(FIRST_STEPS).toEqual(["ceo", "hire", "schedule"]);});});diff --git a/packages/web/test/page-hints.test.ts b/packages/web/test/page-hints.test.tsindex 1704bc8f..62617629 100644--- a/packages/web/test/page-hints.test.ts+++ b/packages/web/test/page-hints.test.ts@@ -1,47 +1,28 @@/**- * page-hints.ts unit tests: the key's user / Project / organization / page scope, the round- * trip through an injected storage, and the two ways a browser refuses to cooperate — a- * storage that throws, and one that silently drops the write. Both must read as "not- * dismissed" rather than throwing while an empty page renders.+ * The dismissible hints on company pages (features/company/page-hints.ts), remembered per+ * user, Project, organization and page.+ *+ * - Each of those scopes separates the hint, and a signed-out browser gets its own bucket.+ * - A hint nobody dismissed stands; a dismissal is remembered for that hint alone, and a+ * second dismissal changes nothing.+ * - A storage that throws, or one that silently drops the write, reads as "not dismissed"+ * without costing the click anything.*/import { describe, expect, it } from "vitest";import type { HintStorage } from "../src/features/company/page-hints";import { dismissHint, hintKey, isHintDismissed } from "../src/features/company/page-hints";+import { blockedStorage, memoryStorage } from "./helpers/storage";-function memoryStorage(initial: Record<string, string> = {}): HintStorage & {- map: Map<string, string>;-} {- const map = new Map(Object.entries(initial));- return {- map,- getItem: (k) => map.get(k) ?? null,- setItem: (k, v) => void map.set(k, v),- };-}--const throwingStorage: HintStorage = {- getItem: () => {- throw new Error("private mode");- },- setItem: () => {- throw new Error("quota");- },-};+const throwingStorage = blockedStorage();describe("hintKey", () => {- it("names the user, the Project, the organization and the page", () => {- expect(hintKey("alice", "p1", "acme", "calendar")).toBe(- "penguin.orgPageHint.alice.p1.acme.calendar",- );- });-it("separates every scope it carries, and gives a signed-out browser its own bucket", () => {const key = hintKey("alice", "p1", "acme", "calendar");expect(key).not.toBe(hintKey("bob", "p1", "acme", "calendar"));expect(key).not.toBe(hintKey("alice", "p2", "acme", "calendar"));expect(key).not.toBe(hintKey("alice", "p1", "other", "calendar"));expect(key).not.toBe(hintKey("alice", "p1", "acme", "tickets"));- expect(hintKey(null, "p1", "acme", "calendar")).toBe("penguin.orgPageHint..p1.acme.calendar");+ expect(hintKey(null, "p1", "acme", "calendar")).not.toBe(key);});});diff --git a/packages/web/test/pages.test.ts b/packages/web/test/pages.test.tsindex f27a9ec1..88a0723f 100644--- a/packages/web/test/pages.test.ts+++ b/packages/web/test/pages.test.ts@@ -1,9 +1,18 @@/**- * The web app's page manifest (src/module.json) and how server contributions fold in.+ * The web app's page manifest (src/module.json) and how server contributions fold in+ * (lib/pages.ts).+ *+ * - Every nav key the JSON manifest names has a nav label and an icon (the JSON is not+ * type-checked against them).+ * - Every page has a unique id, key and path, and a renderer.+ * - A member's nav drops admin-only and unreleased pages and adds nothing the admin lacks.+ * - A server page whose renderer this build carries is appended after the local ones.+ * - A server page with an unknown builtin renderer is skipped, and a local page wins over a+ * same-key server one.+ * - An iframe renderer needs no registry entry.*/import { describe, expect, it } from "vitest";import { NAV_PAGE_KEYS, PAGES, mergePages, navPagesFor } from "../src/lib/pages";-import { NAV_GROUP_KEYS } from "../src/lib/nav-group-collapse";import { zh } from "../src/lib/strings";import { NAV_ICONS } from "../src/lib/nav-icons";@@ -13,7 +22,6 @@ describe("the page manifest", () => {expect(zh.nav).toHaveProperty(key);expect(NAV_ICONS).toHaveProperty(key);}- expect(NAV_GROUP_KEYS).toEqual(NAV_PAGE_KEYS);});it("every page has a unique id, key and path, and a renderer", () => {diff --git a/packages/web/test/permission-level.test.ts b/packages/web/test/permission-level.test.tsindex a0ad48e4..5bc953dc 100644--- a/packages/web/test/permission-level.test.ts+++ b/packages/web/test/permission-level.test.ts@@ -1,14 +1,15 @@/**- * The composer's permission level: one colour for how much the Agent may do on its own.+ * The composer's permission level (lib/permission-level.ts): how much the Agent may do on its+ * own, in one mark.+ *+ * - The level is all only when nothing holds the Agent back; any approval, network or+ * sandbox limit makes it partial.+ * - It is read-only when commands cannot write, and off when every call is denied.+ * - Each level wears its own glyph, so the level never depends on colour alone.*/import { describe, expect, it } from "vitest";import type { SessionSandbox } from "@prismshadow/penguin-server/api";-import {- PERMISSION_LEVEL_GLYPH,- PERMISSION_LEVEL_TONE,- SHIELD,- permissionLevel,-} from "../src/lib/permission-level";+import { PERMISSION_LEVEL_GLYPH, permissionLevel } from "../src/lib/permission-level";const FULL: SessionSandbox = { mode: "danger-full-access", network: "open" };@@ -27,22 +28,9 @@ describe("permission level", () => {expect(permissionLevel("deny-all", { mode: "read-only", network: "none" })).toBe("off");});- it("gives each level its own tone, loudest for the most access", () => {- expect(PERMISSION_LEVEL_TONE).toEqual({- all: "danger",- partial: "attention",- "read-only": "success",- off: "muted",- });- });-it("draws each level with its own mark, so the level never depends on colour alone", () => {const glyphs = Object.values(PERMISSION_LEVEL_GLYPH);expect(glyphs).toHaveLength(4);expect(new Set(glyphs).size).toBe(4);- // lucide's shield family: the three that keep the whole outline start with it.- for (const level of ["all", "partial", "read-only"] as const) {- expect(PERMISSION_LEVEL_GLYPH[level].startsWith(SHIELD)).toBe(true);- }});});diff --git a/packages/web/test/pinned-sessions.test.ts b/packages/web/test/pinned-sessions.test.tsindex 6de99094..bac0ca22 100644--- a/packages/web/test/pinned-sessions.test.ts+++ b/packages/web/test/pinned-sessions.test.ts@@ -1,13 +1,16 @@/**- * pinned-sessions.ts unit tests: the sidebar conversation list's row-level pin. Pinned- * ids persist per Project in localStorage (injectable storage; no server field exists —- * SessionPatchRequest accepts no pin, so persistence is deliberately frontend-side):- * nothing stored or corrupted storage degrades to "nothing pinned", junk array elements- * are dropped, Projects are isolated, and deleting a Session prunes its id (other stale- * ids stay inert — a pin is a pure membership test). Ordering composes with the group- * lists through the same pinnedFirst helper the group pins use: the pinned cluster- * sits at the top of a group's ACTIVE rows in either grouping mode, keeping each- * partition's own recency order; folder rows are untouched.+ * Row pins in the sidebar's conversation list (lib/pinned-sessions.ts), kept per Project in+ * localStorage because the server has no pin field.+ *+ * - Given no Project or nothing stored, nothing is pinned, and reading writes nothing.+ * - Toggling, saving and loading round-trips the user's set; Projects keep separate sets.+ * - A malformed stored value reads as nothing pinned, keeping the well-formed ids.+ * - A storage that throws (quota, private mode, a throwing getter) never escapes: saving is a+ * no-op and loading is empty.+ * - Toggling adds or removes one id without mutating the input; removing an unpinned id+ * returns the same set, so the caller skips its writes.+ * - The pinned cluster tops a group's active rows, each partition keeping its order; folder+ * rows ignore pins and a pin of a deleted Session surfaces nothing.*/import { describe, expect, it } from "vitest";import type { SessionInfo } from "@prismshadow/penguin-server/api";@@ -20,16 +23,7 @@ import {} from "../src/lib/pinned-sessions";import type { PinnedSessionsStorage } from "../src/lib/pinned-sessions";import { partitionSessions, pinnedFirst } from "../src/lib/session-grouping";--/** In-memory storage (vitest runs in a Node environment, no localStorage; draft-cache.test.ts convention). */-function memStorage(): PinnedSessionsStorage & { map: Map<string, string> } {- const map = new Map<string, string>();- return {- map,- getItem: (k) => map.get(k) ?? null,- setItem: (k, v) => void map.set(k, v),- };-}+import { blockedStorage, memoryStorage } from "./helpers/storage";/** Minimal SessionInfo (session-grouping.test.ts convention: only the fields the logic reads matter). */function session(@@ -58,7 +52,7 @@ function session(describe("persisted pins (per-Project localStorage)", () => {it("nothing stored — or no Project yet — is the empty set, and reading never writes", () => {- const s = memStorage();+ const s = memoryStorage();expect(loadPinnedSessions("p1", s).size).toBe(0);expect(loadPinnedSessions(null, s).size).toBe(0);expect(s.map.size).toBe(0); // load never writes; save without a Project is a no-op@@ -67,7 +61,7 @@ describe("persisted pins (per-Project localStorage)", () => {});it("toggle → save → load round-trips the user's set (fresh instance per load)", () => {- const s = memStorage();+ const s = memoryStorage();let set = loadPinnedSessions("p1", s);set = togglePinnedSession(set, "session-a");set = togglePinnedSession(set, "session-b");@@ -78,7 +72,7 @@ describe("persisted pins (per-Project localStorage)", () => {});it("Projects are isolated: each key holds its own set", () => {- const s = memStorage();+ const s = memoryStorage();savePinnedSessions("p1", new Set(["a"]), s);savePinnedSessions("p2", new Set(["b", "c"]), s);expect([...loadPinnedSessions("p1", s)]).toEqual(["a"]);@@ -87,7 +81,7 @@ describe("persisted pins (per-Project localStorage)", () => {});it("malformed JSON / non-array shapes degrade to empty; junk array elements are dropped", () => {- const s = memStorage();+ const s = memoryStorage();for (const raw of ["{not json", '"a"', "42", "null", "{}", ""]) {s.map.set(pinnedSessionsKey("p1"), raw);expect(loadPinnedSessions("p1", s).size).toBe(0);@@ -97,14 +91,7 @@ describe("persisted pins (per-Project localStorage)", () => {});it("storage throwing (quota/private mode): save does not throw, load yields empty", () => {- const broken: PinnedSessionsStorage = {- getItem: () => {- throw new Error("denied");- },- setItem: () => {- throw new Error("denied");- },- };+ const broken = blockedStorage();expect(() => savePinnedSessions("p1", new Set(["a"]), broken)).not.toThrow();expect(loadPinnedSessions("p1", broken).size).toBe(0);});@@ -160,10 +147,4 @@ describe("pinned ordering composes with the group lists", () => {// … and a stored id of a Session deleted elsewhere never surfaces a row.expect(active.some((s) => s.sessionId === "deleted-elsewhere")).toBe(false);});-- it("no pins = the group's original order, untouched", () => {- const rows = [session("s1"), session("s2")];- const active = pinnedFirst(partitionSessions(rows).active, (s) => s.sessionId, new Set());- expect(active.map((s) => s.sessionId)).toEqual(["s1", "s2"]);- });});diff --git a/packages/web/test/plugin-config-machine.test.ts b/packages/web/test/plugin-config-machine.test.tsindex b9e2063e..6ed7a4d9 100644--- a/packages/web/test/plugin-config-machine.test.ts+++ b/packages/web/test/plugin-config-machine.test.ts@@ -1,41 +1,35 @@/*** Plugin settings are kept by each server in its own database, so the Settings dialog's* Plugins page reads and writes a picked machine's settings through that machine's proxy- * prefix, and this server's own when none is picked.+ * prefix (api/endpoints.ts).+ *+ * - With a machine picked, reading, writing and running an action go to that machine; with+ * none, they stay on this server.*/-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { describe, expect, it, vi } from "vitest";import * as api from "../src/api/endpoints";+import { json, stubFetch } from "./helpers/fetch";const ID = "noeSE0FFHhNXl2J5";describe("plugin config endpoints", () => {- const calls: { url: string; method: string }[] = [];- beforeEach(() => {- calls.length = 0;- vi.stubGlobal("WebSocket", undefined);- vi.stubGlobal("fetch", async (url: string, init?: { method?: string }) => {- calls.push({ url, method: init?.method ?? "GET" });- return new Response(JSON.stringify({ plugins: [], ok: true, message: "" }), {- status: 200,- headers: { "content-type": "application/json" },- });- });- });- afterEach(() => {- vi.unstubAllGlobals();- });-it("goes to the picked machine, and stays here otherwise", async () => {+ vi.stubGlobal("WebSocket", undefined);+ const fetch = stubFetch(() => json({ plugins: [], ok: true, message: "" }));await api.adminGetPluginConfig();await api.adminGetPluginConfig(ID);await api.adminPutPluginConfig({ name: "sandbox", values: {} }, ID);await api.adminRunPluginConfigAction({ name: "sandbox", action: "setup" }, ID);// The client may probe the session first; only the plugin-config calls are in question.- expect(calls.filter((c) => c.url.includes("plugin-config"))).toEqual([- { url: "/api/admin/plugin-config", method: "GET" },- { url: `/server/${ID}/api/admin/plugin-config`, method: "GET" },- { url: `/server/${ID}/api/admin/plugin-config`, method: "PUT" },- { url: `/server/${ID}/api/admin/plugin-config/action`, method: "POST" },+ expect(+ fetch.requests+ .filter((r) => r.path.includes("plugin-config"))+ .map((r) => [r.machine, r.method, r.path]),+ ).toEqual([+ [null, "GET", "/api/admin/plugin-config"],+ [ID, "GET", "/api/admin/plugin-config"],+ [ID, "PUT", "/api/admin/plugin-config"],+ [ID, "POST", "/api/admin/plugin-config/action"],]);});});diff --git a/packages/web/test/plugin-machine-view.test.ts b/packages/web/test/plugin-machine-view.test.tsdeleted file mode 100644index e2ee6009..00000000--- a/packages/web/test/plugin-machine-view.test.ts+++ /dev/null@@ -1,78 +0,0 @@-/**- * The Plugins page's machine picker: all machines show every table with where each plugin- * runs; a machine's view shows what that machine is asked for, in the state that machine- * reports, and edits only its own table.- */-import { describe, expect, it } from "vitest";-import type { InstalledPluginsResponse } from "@prismshadow/penguin-server/api";-import {- availablePluginRows,- installedPluginRows,- type PluginView,-} from "../src/features/plugins/plugins-page";--const SELF = "Self000000000000";-const GPU = "Gpu0000000000000";--const row = (- specifier: string,- where: { everywhere: boolean; machines: string[]; here: boolean },- active = where.here,-): InstalledPluginsResponse["plugins"][number] => ({- specifier,- active,- builtin: false,- modules: [],- replaces: [],- ...where,-});--const deployment: InstalledPluginsResponse = {- plugins: [- row("@acme/shared", { everywhere: true, machines: [], here: true }),- row("@acme/gpu-only", { everywhere: false, machines: [GPU], here: false }),- ],- shipped: [],- file: ".project_config.toml",- machineId: SELF,- restartPending: false,-};--const nameOf = (id: string) => (id === GPU ? "gpu-box" : "this server");-const modules = (rows: ReturnType<typeof installedPluginRows>) =>- rows.flatMap((r) => (r.kind === "module" ? [r] : []));--describe("plugin rows per machine", () => {- it("all machines: every plugin, and a machine-only one says where it runs", () => {- const view: PluginView = { machineId: null, remote: null, nameOf };- const rows = modules(installedPluginRows([], "en", deployment, [], view));- expect(rows.map((r) => [r.specifier, r.state, r.onlyOn])).toEqual([- ["@acme/shared", "active", undefined],- ["@acme/gpu-only", "elsewhere", ["gpu-box"]],- ]);- // Offered for all machines, since the shared table does not list it.- expect(availablePluginRows(deployment, [], view)).toEqual([]);- });-- it("this server: what it is asked for, and a shared plugin cannot be removed from its table", () => {- const view: PluginView = { machineId: SELF, remote: null, nameOf };- const rows = modules(installedPluginRows([], "en", deployment, [], view));- expect(rows.map((r) => r.specifier)).toEqual(["@acme/shared"]);- expect(rows[0]!.removeBlocked).toBeDefined();- });-- it("another machine: the state it reports, and what it has not received yet", () => {- const remote: InstalledPluginsResponse = {- ...deployment,- machineId: GPU,- plugins: [row("@acme/gpu-only", { everywhere: true, machines: [], here: true }, false)],- };- remote.plugins[0]!.error = "npm: 404";- const view: PluginView = { machineId: GPU, remote, nameOf };- const rows = modules(installedPluginRows([], "en", deployment, [], view));- expect(rows.map((r) => [r.specifier, r.state, r.removeBlocked === undefined])).toEqual([- ["@acme/shared", "unsynced", false],- ["@acme/gpu-only", "failed", true],- ]);- });-});diff --git a/packages/web/test/plugin-outdated.test.ts b/packages/web/test/plugins-page.test.tssimilarity index 61%rename from packages/web/test/plugin-outdated.test.tsrename to packages/web/test/plugins-page.test.tsindex c64c49d3..6c84991a 100644--- a/packages/web/test/plugin-outdated.test.ts+++ b/packages/web/test/plugins-page.test.ts@@ -1,21 +1,99 @@/**- * The plugin library page's install questions, pure and unit tested:- * - `pluginInstalled` / `installedPluginVersion` — a plugin is installed on an Agent when any- * part of it is there (a skill, or the hook package when it ships one), read off the two- * installed lists the page fetches per Agent;- * - `outdatedAgentIds`, the per-plugin reminder's data source — the Agents the SERVER lists as- * behind on it (`AgentSummary.pluginUpdates`), since versions are `YYYY.MM.DD.N` strings the- * web never compares itself;- * - `pluginUpdatePlan`, the page notice's "update all of them" version of the same question.+ * The Plugins page's pure decisions (features/plugins/plugins-page.tsx). One file, so the page+ * module is imported once.+ *+ * - All machines: every plugin is listed, and a machine-only one says where it runs. This+ * server: what it is asked for, a shared plugin not removable from its table. Another+ * machine: the state that machine reports, and what it has not received yet.+ * - A plugin is installed on an Agent once any part of it is there (a skill, or its hook+ * package), read off the two installed lists; nothing is installed for an Agent with no+ * snapshot or for a plugin that ships nothing.+ * - The installed version is the hook package's where there is one, else the first installed+ * skill's, and undefined where the plugin is not installed.+ * - The per-plugin reminder names the Agents the server lists as behind on it, in list order+ * (versions are never compared here).+ * - The "update all" plan is empty when no Agent is behind, sends one request per Agent with+ * every plugin it is behind on, and counts distinct plugins as the notice does.*/import { describe, expect, it } from "vitest";+import type { InstalledPluginsResponse } from "@prismshadow/penguin-server/api";import {+ availablePluginRows,+ installedPluginRows,installedPluginVersion,outdatedAgentIds,pluginInstalled,pluginUpdatePlan,+ type AgentInstalls,+ type PluginParts,+ type PluginView,} from "../src/features/plugins/plugins-page";-import type { AgentInstalls, PluginParts } from "../src/features/plugins/plugins-page";++const SELF = "Self000000000000";+const GPU = "Gpu0000000000000";++const row = (+ specifier: string,+ where: { everywhere: boolean; machines: string[]; here: boolean },+ active = where.here,+): InstalledPluginsResponse["plugins"][number] => ({+ specifier,+ active,+ builtin: false,+ modules: [],+ replaces: [],+ ...where,+});++const deployment: InstalledPluginsResponse = {+ plugins: [+ row("@acme/shared", { everywhere: true, machines: [], here: true }),+ row("@acme/gpu-only", { everywhere: false, machines: [GPU], here: false }),+ ],+ shipped: [],+ file: ".project_config.toml",+ machineId: SELF,+ restartPending: false,+};++const nameOf = (id: string) => (id === GPU ? "gpu-box" : "this server");+const modules = (rows: ReturnType<typeof installedPluginRows>) =>+ rows.flatMap((r) => (r.kind === "module" ? [r] : []));++describe("plugin rows per machine", () => {+ it("all machines: every plugin, and a machine-only one says where it runs", () => {+ const view: PluginView = { machineId: null, remote: null, nameOf };+ const rows = modules(installedPluginRows([], "en", deployment, [], view));+ expect(rows.map((r) => [r.specifier, r.state, r.onlyOn])).toEqual([+ ["@acme/shared", "active", undefined],+ ["@acme/gpu-only", "elsewhere", ["gpu-box"]],+ ]);+ // Offered for all machines, since the shared table does not list it.+ expect(availablePluginRows(deployment, [], view)).toEqual([]);+ });++ it("this server: what it is asked for, and a shared plugin cannot be removed from its table", () => {+ const view: PluginView = { machineId: SELF, remote: null, nameOf };+ const rows = modules(installedPluginRows([], "en", deployment, [], view));+ expect(rows.map((r) => r.specifier)).toEqual(["@acme/shared"]);+ expect(rows[0]!.removeBlocked).toBeDefined();+ });++ it("another machine: the state it reports, and what it has not received yet", () => {+ const remote: InstalledPluginsResponse = {+ ...deployment,+ machineId: GPU,+ plugins: [row("@acme/gpu-only", { everywhere: true, machines: [], here: true }, false)],+ };+ remote.plugins[0]!.error = "npm: 404";+ const view: PluginView = { machineId: GPU, remote, nameOf };+ const rows = modules(installedPluginRows([], "en", deployment, [], view));+ expect(rows.map((r) => [r.specifier, r.state, r.removeBlocked === undefined])).toEqual([+ ["@acme/shared", "unsynced", false],+ ["@acme/gpu-only", "failed", true],+ ]);+ });+});const skill = (name: string) => ({ name, description: "", version: "2026.08.01.1" });diff --git a/packages/web/test/portal-panel-dismiss.test.ts b/packages/web/test/portal-panel-dismiss.test.tsindex 9c99cb4f..42e88c8c 100644--- a/packages/web/test/portal-panel-dismiss.test.ts+++ b/packages/web/test/portal-panel-dismiss.test.ts@@ -1,67 +1,21 @@/**- * Scroll dismissal for the shared portal panel (the UI package's- * src/components/overlays/portal-panel/use-portal-panel.ts), which OptionMenu, Select,- * InfoPopover and the composer toolbar's context ring all open through.+ * Guard: every consumer of the shared portal panel (the UI package's use-portal-panel.ts, which+ * OptionMenu, Select, InfoPopover and the composer's context ring open through) attaches the+ * hook's `triggerRef`. The scroll-dismissal rule asks whether a scroll moved the panel's trigger+ * (`scrollMovesAnchor`, tested in the package's portal-panel.test.ts); a consumer without the ref+ * hands it a null owner and silently gets close-on-any-scroll back. The consumers are discovered,+ * not listed, so a new one is covered the day it is written.*- * The panel listens for scroll in the capture phase because scroll does not bubble, and the- * price of capture on `window` is that it hears every scrolling element in the document. The- * rule that closes a panel whose position has gone stale must therefore ask whether the- * scrolled container holds this panel's trigger — otherwise a chat pane auto-following a- * streaming reply closes a panel opened in the composer toolbar, over content that never- * moved.- *- * `scrollMovesAnchor` itself is exercised in the package's portal-panel.test.ts; what cannot be- * reached from a node-only suite (`environment: "node"`, no jsdom) is the wiring, and the wiring is- * where this silently breaks: the rule is answered with the trigger element, so a consumer- * that never attaches `triggerRef` hands it a null owner and quietly gets the old- * close-on-any-scroll behavior back for its own panel. So the scan below discovers the- * hook's consumers rather than listing them, and a fifth one is covered on the day it is- * written.+ * - The scan finds the call sites the rule covers, the reported one (the context ring) among them.+ * - Each attaches the hook's triggerRef.*/import { describe, expect, it } from "vitest";-import { expectEveryRootScanned, expectSingleHome, scanSources, sourceFile } from "./helpers/roots";+import { scanSources, sourceFile } from "./helpers/roots";/** Every .ts/.tsx under web and the shared UI package: a consumer is covered on either side. */const SCAN = scanSources([".ts", ".tsx"]);const HOOK = "packages/ui/src/components/overlays/portal-panel/use-portal-panel.ts";-/** The body of a handler declared as `const <name> = ...` up to its closing `};`. */-function handler(src: string, name: string): string {- const body = new RegExp(`const ${name} = [\\s\\S]*?\\n {4}\\};`).exec(src);- expect(body, `${name} should be declared in use-portal-panel.ts`).not.toBeNull();- return body![0];-}--describe("use-portal-panel scroll dismissal", () => {- const hook = sourceFile(SCAN, HOOK).text;-- it("reads every source root, and finds the hook in one place", () => {- expectEveryRootScanned(SCAN);- expectSingleHome(SCAN, HOOK);- });-- it("asks whether the scroll moved this panel's trigger before closing", () => {- const onScroll = handler(hook, "onScroll");- expect(onScroll).toMatch(/if \(!scrollMovesAnchor\(/);- // The trigger is the owner: the panel is placed against that element's box, so a scroll- // that did not move it did not invalidate the position.- expect(onScroll).toContain("triggerRef.current");- });-- it("still exempts the panel's own internal scroll", () => {- // A long list scrolling inside the panel must not close the panel around it — the guard- // that does this predates the ownership test and has to survive it.- expect(handler(hook, "onScroll")).toContain("panelRef.current?.contains(");- });-- it("leaves a resize closing unconditionally, because it moves every trigger at once", () => {- const onResize = /const onResize = .*/.exec(hook);- expect(onResize).not.toBeNull();- expect(onResize![0]).toContain("onCloseRef.current()");- expect(onResize![0]).not.toContain("scrollMovesAnchor");- });-});-describe("use-portal-panel consumers", () => {/** Files that open a panel through the hook — the hook's own module excluded. */const consumers = SCAN.filesdiff --git a/packages/web/test/process-list.test.ts b/packages/web/test/process-list.test.tsindex a20deff0..7de3d089 100644--- a/packages/web/test/process-list.test.ts+++ b/packages/web/test/process-list.test.ts@@ -1,15 +1,11 @@/**- * The details card's background-process list (src/features/chat/process-list.ts and its use in- * chat-page.tsx): which entries "clear exited" removes, which failure of a batch of per-entry- * requests reaches the user, and how a command too long for its row is read whole.+ * The details card's background-process list (features/chat/process-list.ts).*- * The last part is a source scan, as in title-reveal.test.ts: vitest runs node-only here- * (`environment: "node"`, no jsdom), and a native `title` creeping back onto the command line —- * two tooltips over each other — is not something a rendered-markup assertion would see.+ * - "Clear exited" picks every exited entry in list order, and never a running one.+ * - Of a batch of per-entry requests, nothing is reported when all succeed or only failed+ * with the action's own "stale list" statuses; otherwise the first other failure is+ * reported once, a network failure included.*/-import { readFileSync } from "node:fs";-import { dirname, resolve } from "node:path";-import { fileURLToPath } from "node:url";import { describe, expect, it } from "vitest";import { ApiError } from "../src/api/client";import { exitedProcessIds, reportableProcessFailure } from "../src/features/chat/process-list";@@ -79,24 +75,3 @@ describe("reportableProcessFailure", () => {expect(reportableProcessFailure([rejected(conflict)], [404])).toEqual({ error: conflict });});});--describe("the process row's command line", () => {- const src = resolve(dirname(fileURLToPath(import.meta.url)), "../src");- const chatPage = readFileSync(resolve(src, "features/chat/chat-page.tsx"), "utf8");-- it("shows a truncated command whole in the code tooltip, never in a native title", () => {- expect(chatPage).toContain(- '<Truncated text={p.cmd} className="font-mono text-xs" codeTooltip />',- );- expect(chatPage).not.toContain("title={p.cmd}");- });-- it("clears exited entries through the same per-entry route a row's Remove uses", () => {- expect(chatPage).toMatch(- /runProcessAction\(exitedIds, api\.removeSessionProcess, \[404, 409\]\)/,- );- expect(chatPage).toMatch(- /runProcessAction\(\[processId\], api\.removeSessionProcess, \[404, 409\]\)/,- );- });-});diff --git a/packages/web/test/qq-scan-connect.test.ts b/packages/web/test/qq-scan-connect.test.tsindex b17d77a3..b2298e79 100644--- a/packages/web/test/qq-scan-connect.test.ts+++ b/packages/web/test/qq-scan-connect.test.ts@@ -1,21 +1,15 @@/**- * The QQ scan-to-connect block: the shape it renders, and the decision the poll loop makes- * on each answer.+ * The QQ scan-to-connect block (features/messaging/qq-scan-connect.tsx): what it renders, and+ * the decision its poll loop makes on each answer (`qqScanStep`, tested by value).*- * Three rendered rules that a type checker cannot see. The QR is generated locally and- * inlined as `<svg>`, so no third party ever learns the task handle from an image request.- * It is drawn dark-on-white in BOTH themes rather than inheriting the panel's colours,- * because a code inverted for a dark background is read unreliably by phone cameras. And it- * carries the four-module quiet zone the QR spec requires, without which scanners lose the- * finder patterns against a busy page.- *- * The fourth is the one that matters most and is asserted here as well as server-side: the- * copy tells the reader the decryption key stays on the server, because "why is it safe to- * let a web page fetch my App Secret" is the question this flow has to answer.- *- * The loop itself is tested by value rather than by mounting: this package's vitest runs in- * `node`, deliberately, so the classification lives in a pure function (`qqScanStep`, the- * `updateCheckOutcome` idiom) and the effects around it stay a thin shell.+ * - The QR is generated locally and inlined as SVG (no image request can leak the task+ * handle), with the spec's four-module quiet zone, dark-on-white in both themes.+ * - The scan is offered as a control alone, its explanation disclosed in the setup fold, and+ * nothing is requested before the user asks; it is gated, with the reason, while the+ * connection is enabled.+ * - The loop keeps waiting until the scan happens, hands the binding on so the editor adopts it+ * without a second GET, rides out a transient failure (giving up, and releasing the task,+ * only after repeated ones), and replaces a lapsed code a bounded number of times.*/import { describe, expect, it } from "vitest";import { createElement } from "react";@@ -25,8 +19,7 @@ import type { QQBindingInfo, QQScanPollResponse } from "@prismshadow/penguin-serimport { ApiError } from "../src/api/client";import { QQScanConnect, QrCode, qqScanStep } from "../src/features/messaging/qq-scan-connect";import type { QQScanTally } from "../src/features/messaging/qq-scan-connect";-import { S, zh } from "../src/lib/strings";-import { en } from "../src/lib/strings-en";+import { S } from "../src/lib/strings";const QR_URL = "https://q.qq.com/qqbot/openclaw/connect.html?task_id=t-1&source=&_wv=2";@@ -142,12 +135,4 @@ describe("qqScanStep", () => {releaseTask: false,});});-- it("names no position for the code, which wraps above the text in a narrow panel", () => {- // The waiting panel is `flex flex-wrap`: in the dock or on a phone the steps sit BELOW- // the QR, so copy that says "the code on the left" is wrong exactly where it is read.- for (const dict of [zh, en]) {- expect(dict.qq.scanSteps).not.toMatch(/左侧|右侧|left|right/);- }- });});diff --git a/packages/web/test/random-id.test.ts b/packages/web/test/random-id.test.tsindex 46264306..db8cc420 100644--- a/packages/web/test/random-id.test.ts+++ b/packages/web/test/random-id.test.ts@@ -1,15 +1,18 @@/*** randomHex (lib/random-id.ts) and the two ids it mints: parked drafts (draft-sessions.ts) and- * user shortcuts (user-shortcuts.ts). Both have to work in an insecure context — a Web App served- * over plain HTTP from any address but localhost — where `crypto.randomUUID` does not exist and- * the previous generator threw on the "+" button.+ * user shortcuts (user-shortcuts.ts).+ *+ * - randomHex returns exactly the requested number of lowercase hex characters, and does not+ * repeat.+ * - In an insecure context (plain HTTP from any address but localhost, where crypto has no+ * randomUUID), parking a draft and saving a shortcut still mint their ids instead of throwing.*/-import { afterEach, describe, expect, it, vi } from "vitest";+import { describe, expect, it, vi } from "vitest";import { draftKey, saveDraft } from "../src/features/chat/draft-cache";-import type { DraftStorage } from "../src/features/chat/draft-cache";import { parkActiveDraft } from "../src/features/chat/draft-sessions";import { newShortcutId } from "../src/features/chat/user-shortcuts";import { randomHex } from "../src/lib/random-id";+import { memoryStorage } from "./helpers/storage";describe("randomHex", () => {it("returns exactly the requested number of lowercase hex characters", () => {@@ -30,25 +33,13 @@ describe("randomHex", () => {* such a test passes just as happily with randomUUID put back into either call site.*/describe("an insecure context, where crypto carries getRandomValues and no randomUUID", () => {- afterEach(() => vi.unstubAllGlobals());-function stubInsecureCrypto(): void {const real = globalThis.crypto;vi.stubGlobal("crypto", { getRandomValues: real.getRandomValues.bind(real) });}- /** In-memory storage: vitest runs in a Node environment, so there is no localStorage. */- function memStorage(): DraftStorage {- const map = new Map<string, string>();- return {- getItem: (k) => map.get(k) ?? null,- setItem: (k, v) => void map.set(k, v),- removeItem: (k) => void map.delete(k),- };- }-it("parks a typed draft rather than throwing on the '+' click", () => {- const s = memStorage();+ const s = memoryStorage();stubInsecureCrypto();saveDraft(draftKey("u-insecure", "proj"), { text: "half-written prompt" }, s);expect(parkActiveDraft("u-insecure", "proj", s)).toMatch(/^draft-[0-9a-f]{8}$/);diff --git a/packages/web/test/required-mark.test.ts b/packages/web/test/required-mark.test.tsindex f92874b4..dc9736ad 100644--- a/packages/web/test/required-mark.test.ts+++ b/packages/web/test/required-mark.test.ts@@ -1,20 +1,20 @@/**- * The field-marker contract (the UI package's forms/field/field.tsx): **a required field carries- * the red "*", an optional field carries nothing at all, and no label or placeholder writes the- * word "optional".**+ * Guard: the field-marker contract (the UI package's forms/field/field.tsx) — **a required field+ * carries the red "*", an optional field carries nothing at all, and no label or placeholder+ * writes the word "optional".** How RequiredMark and a required Input render is the UI package's+ * to test (packages/ui/test/field.test.ts, input.test.ts); this file holds the rule across the+ * app.*- * The absence of the mark is the whole signal, so it only reads if the mark is spelled one way- * everywhere and never competes with a second, wordier convention — the same reason- * test/icon-scale.test.ts fails on a second copy of the close cross.+ * - The field module lives in one place, and no other file hand-rolls a red "*" (found however+ * its className is written).+ * - Neither dictionary says "optional" in a label, and every prose exception still says it (so+ * the allow-list cannot rot).** The source scan parses the real JSX with the TypeScript parser: whether a red span holds a lone* "*" is a question about an element's children, and a regex cannot see children.*/import { describe, expect, it } from "vitest";-import { createElement } from "react";-import { renderToStaticMarkup } from "react-dom/server";import ts from "typescript";-import { Input, RequiredMark } from "@prismshadow/penguin-ui";import { zh } from "../src/lib/strings";import { en } from "../src/lib/strings-en";import { expectEveryRootScanned, expectSingleHome, scanSources } from "./helpers/roots";@@ -136,37 +136,6 @@ describe("required mark", () => {expectSingleHome(SCAN, FIELD);});- it("renders only when the field is required", () => {- const required = renderToStaticMarkup(- createElement(Input, { label: "Name", required: true, value: "", readOnly: true }),- );- expect(required).toContain("*");- expect(required).toContain("text-tone-danger-fg");- // Decorative to assistive tech — aria-required on the control is what gets announced.- expect(required).toMatch(/<span[^>]*aria-hidden[^>]*>\*<\/span>/);- expect(required).toContain('aria-required="true"');- });-- it("states itself where no control carries aria-required", () => {- // The trace viewer's schema table is not a form: nothing else there says "required".- const spoken = renderToStaticMarkup(createElement(RequiredMark, { label: "required" }));- expect(spoken).toMatch(/<span[^>]*aria-hidden[^>]*>\*<\/span>/);- expect(spoken).toContain("required");- expect(spoken).not.toMatch(/^<span[^>]*aria-hidden/);- });-- it("leaves an optional field completely unmarked", () => {- // No counterpart mark and no wording: absence is the signal, so anything here would blunt it.- const optional = renderToStaticMarkup(- createElement(Input, { label: "Name", value: "", readOnly: true }),- );- // Scoped to the mark's own shape: a bare `toContain("*")` over the markup would also trip- // on a Tailwind `*:` variant landing in any class the control renders.- expect(optional).not.toMatch(/<span[^>]*>\*<\/span>/);- expect(optional).not.toMatch(RED_INK);- expect(optional).not.toContain("aria-required");- });-it("is spelled in exactly one place", () => {expect(handRolledMarks(),diff --git a/packages/web/test/schedule-store.test.ts b/packages/web/test/schedule-store.test.tsindex d04509d8..43800809 100644--- a/packages/web/test/schedule-store.test.ts+++ b/packages/web/test/schedule-store.test.ts@@ -1,25 +1,25 @@/**- * The scheduled-tasks store (src/features/schedules/schedule-store.ts), which two surfaces read:- * the session list's alarm-clock marks and the dock's scheduled-tasks panel. What is asserted- * here is that the one list they share is the PROJECT's — every Agent's tasks in a single answer,- * cached per Project — so a row's mark never depends on which Agent happens to be current. A- * per-Agent list was what made the marks come and go as the user walked the list: the chat page- * moves the current Agent to whatever conversation is open, and every other Agent's rows then had- * no list to be marked from.+ * The scheduled-tasks store (features/schedules/schedule-store.ts), which the session list's+ * marks and the dock's scheduled-tasks panel both read: one list per PROJECT (every Agent's+ * tasks in a single answer), so a row's mark never depends on which Agent is current. Driven+ * through the real `listProjectSchedules` against the fetch fake; each test uses its own+ * Project ids, so the module-level cache needs no reset.*- * No React and no DOM: the hook is a thin wrapper over these functions, and the caching is the- * part that was wrong. Each test uses its own project ids, so the module-level cache needs no- * reset between them.+ * - Each Project keeps its own list, and a Project never answered reads as nothing.+ * - A Project asked for while another's read is out gets its own request, and each answer+ * lands in its own Project's entry, whatever order they arrive in.+ * - One request per Project is shared while it is out; once settled, the next refresh asks again.+ * - A failure is confined to the Project that failed.+ * - A schedule event re-reads a Project only while a reader is mounted on it (readers are+ * counted, so one surface unmounting does not silence the other), and never one nobody asked+ * about.+ * - The session list marks the Sessions of every Agent out of one answer.*/-import { beforeEach, describe, expect, it, vi } from "vitest";+import { beforeEach, describe, expect, it } from "vitest";import type {ProjectScheduleItem,ProjectSchedulesResponse,} from "@prismshadow/penguin-server/api";--vi.mock("../src/api/endpoints", () => ({ listProjectSchedules: vi.fn() }));--import * as api from "../src/api/endpoints";import { pendingScheduleSessions } from "../src/features/schedules/schedule-panel-state";import {noteScheduleEvent,@@ -28,8 +28,8 @@ import {scheduleError,scheduleItems,} from "../src/features/schedules/schedule-store";--const listProjectSchedules = vi.mocked(api.listProjectSchedules);+import { apiError, json, stubFetch } from "./helpers/fetch";+import type { FakeFetch, FetchRequest } from "./helpers/fetch";/** A task as the Project-wide listing returns it: stamped with the agent whose directory holds it. */function task(name: string, over: Partial<ProjectScheduleItem> = {}): ProjectScheduleItem {@@ -51,23 +51,34 @@ function response(...names: string[]): ProjectSchedulesResponse {const names = (projectId: string) => scheduleItems(projectId)?.map((i) => i.name) ?? null;-/** A promise plus its resolve handle, so a request can be held open across assertions. */-function deferred<T>(): { promise: Promise<T>; resolve: (v: T) => void } {- let resolve!: (v: T) => void;- const promise = new Promise<T>((res) => {- resolve = res;+/** A server answer held open until the test resolves it. */+function deferred(): {+ promise: Promise<Response>;+ resolve: (body: ProjectSchedulesResponse) => void;+} {+ let resolve!: (body: ProjectSchedulesResponse) => void;+ const promise = new Promise<Response>((res) => {+ resolve = (body) => res(json(body));});return { promise, resolve };}+const projectOf = (request: FetchRequest) =>+ decodeURIComponent(/^\/api\/projects\/([^/]+)\/schedules$/.exec(request.path)?.[1] ?? "");++/** Answers queued for the next requests; with none queued, a Project's list is one task named after it. */+const answers: Array<Response | Promise<Response>> = [];+let fetch: FakeFetch;+/** The Projects asked about, in request order. */+const asked = () => fetch.requests.map(projectOf);+beforeEach(() => {- listProjectSchedules.mockReset();+ answers.length = 0;+ fetch = stubFetch((request) => answers.shift() ?? json(response(projectOf(request))));});describe("refreshSchedules", () => {it("keeps a list per Project, so moving to another one never blanks the one already answered", async () => {- listProjectSchedules.mockImplementation(async (projectId) => response(projectId));-await refreshSchedules("p1");await refreshSchedules("p1-other");@@ -79,16 +90,16 @@ describe("refreshSchedules", () => {});it("issues a request for the Project it was asked for, mid-flight, and lands each answer in its own entry", async () => {- const first = deferred<ProjectSchedulesResponse>();- const second = deferred<ProjectSchedulesResponse>();- listProjectSchedules.mockReturnValueOnce(first.promise).mockReturnValueOnce(second.promise);+ const first = deferred();+ const second = deferred();+ answers.push(first.promise, second.promise);const one = refreshSchedules("p2");const other = refreshSchedules("p2-other");// The switch happened while p2's read was still out: p2-other must have been fetched too,// rather than handed p2's promise and left forever unread.- expect(listProjectSchedules.mock.calls.map((c) => c[0])).toEqual(["p2", "p2-other"]);+ expect(asked()).toEqual(["p2", "p2-other"]);second.resolve(response("nightly"));await other;@@ -103,27 +114,26 @@ describe("refreshSchedules", () => {});it("shares one request per Project while it is out, and refetches once it has settled", async () => {- const pending = deferred<ProjectSchedulesResponse>();- listProjectSchedules.mockReturnValueOnce(pending.promise);+ const pending = deferred();+ answers.push(pending.promise);const a = refreshSchedules("p3");const b = refreshSchedules("p3");expect(b).toBe(a);- expect(listProjectSchedules).toHaveBeenCalledTimes(1);+ expect(asked()).toEqual(["p3"]);pending.resolve(response("nightly"));await a;- listProjectSchedules.mockResolvedValueOnce(response("nightly", "weekly"));+ answers.push(json(response("nightly", "weekly")));await refreshSchedules("p3");- expect(listProjectSchedules).toHaveBeenCalledTimes(2);+ expect(asked()).toEqual(["p3", "p3"]);expect(names("p3")).toEqual(["nightly", "weekly"]);});it("confines a failure to the Project that failed", async () => {- listProjectSchedules.mockResolvedValueOnce(response("nightly"));+ answers.push(json(response("nightly")), apiError(500, "internal"));await refreshSchedules("p4");- listProjectSchedules.mockRejectedValueOnce(new Error("offline"));await refreshSchedules("p4-other");expect(scheduleError("p4-other")).not.toBeNull();@@ -145,30 +155,27 @@ describe("refreshSchedules", () => {*/describe("retainSchedules and noteScheduleEvent", () => {it("re-reads a Project a reader is mounted on, and leaves a cached one nobody shows alone", async () => {- listProjectSchedules.mockImplementation(async (projectId) => response(projectId));-await refreshSchedules("p5");// Loaded, but nothing on screen is reading it: the event costs nothing.noteScheduleEvent("p5");- expect(listProjectSchedules).toHaveBeenCalledTimes(1);+ expect(asked()).toHaveLength(1);const release = retainSchedules("p5");noteScheduleEvent("p5");- expect(listProjectSchedules).toHaveBeenCalledTimes(2);+ expect(asked()).toHaveLength(2);// Joins the request the event started rather than issuing a third.await refreshSchedules("p5");- expect(listProjectSchedules).toHaveBeenCalledTimes(2);+ expect(asked()).toHaveLength(2);// Releasing the last reader keeps the list — that is exactly what the reader draws again on// return — and stops the events nothing would display.release();noteScheduleEvent("p5");- expect(listProjectSchedules).toHaveBeenCalledTimes(2);+ expect(asked()).toHaveLength(2);expect(names("p5")).toEqual(["p5"]);});it("counts readers, so the panel unmounting does not silence the session list's refreshes", async () => {- listProjectSchedules.mockImplementation(async (projectId) => response(projectId));// Both surfaces on one Project, which is the only state there is now that they share a scope.// A flag rather than a count would let either release silence both.const sidebar = retainSchedules("p6");@@ -178,34 +185,36 @@ describe("retainSchedules and noteScheduleEvent", () => {noteScheduleEvent("p6");// Read before settling: the request goes out synchronously, so a count of 0 here is the// event having been dropped, not a request that has yet to be made.- expect(listProjectSchedules).toHaveBeenCalledTimes(1);+ expect(asked()).toEqual(["p6"]);// Joins the request the event started rather than issuing one of its own.await refreshSchedules("p6");- expect(listProjectSchedules).toHaveBeenCalledTimes(1);+ expect(asked()).toEqual(["p6"]);sidebar();noteScheduleEvent("p6");- expect(listProjectSchedules).toHaveBeenCalledTimes(1);+ expect(asked()).toEqual(["p6"]);});it("ignores an event for a Project no reader has ever asked about", () => {noteScheduleEvent("p7");- expect(listProjectSchedules).not.toHaveBeenCalled();+ expect(fetch.requests).toEqual([]);});});describe("the session list's marks", () => {it("marks the Sessions of every Agent out of one answer", async () => {const due = "2026-09-11T00:00:00.000Z";- listProjectSchedules.mockResolvedValueOnce({- schedules: [- task("nightly", { agentId: "writer", sessionId: "s1", nextFireAt: due }),- task("hourly", { agentId: "reviewer", sessionId: "s2", nextFireAt: due }),- // Agent-wide: it opens a new Session each run, so it marks no row.- task("fresh", { agentId: "reviewer", nextFireAt: due }),- ],- invalidFiles: [],- });+ answers.push(+ json({+ schedules: [+ task("nightly", { agentId: "writer", sessionId: "s1", nextFireAt: due }),+ task("hourly", { agentId: "reviewer", sessionId: "s2", nextFireAt: due }),+ // Agent-wide: it opens a new Session each run, so it marks no row.+ task("fresh", { agentId: "reviewer", nextFireAt: due }),+ ],+ invalidFiles: [],+ }),+ );await refreshSchedules("p8");diff --git a/packages/web/test/selection-menu.test.ts b/packages/web/test/selection-menu.test.tsindex 4b3e64fe..94cb8713 100644--- a/packages/web/test/selection-menu.test.ts+++ b/packages/web/test/selection-menu.test.ts@@ -1,18 +1,24 @@/**- * lib/selection-menu.ts: the rules behind the conversation's own menu, for selected text and- * for web links.+ * The rules behind the conversation's own menu for selected text and web links+ * (lib/selection-menu.ts). Everything the menu declines keeps the browser's own menu.*- * Which gestures it takes matters as much in the negative as in the positive: everything it- * declines keeps the browser's own menu, so a rule that took a touch press-and-hold, a- * right-click in a field, or a selection that runs into the composer would take a menu away- * from someone who needed it — and a link it took that is not a web page (a Workspace file, an- * anchor) would offer to open an App route as a page. The excerpt half pins what reaches the- * model: the blockquote the message carries, and the label the chip shows instead of it.+ * - The menu opens on a secondary click or the keyboard's request over a selection inside the+ * stream, and declines a touch or pen press-and-hold, an empty or whitespace selection, a+ * selection running out of the stream or made of several ranges, and a gesture in a field.+ * - A keyboard-opened menu hangs at the end of the selection's last line (or the bounding box+ * without line boxes), and at a link's first line.+ * - An excerpt is trimmed at both ends with normalized line endings, carried into the message+ * as a blockquote (blank lines inside kept), and labelled on its chip by its first characters,+ * cut by characters rather than UTF-16 units.+ * - Only an absolute web address counts as a link for the menu (normalized); a Workspace file,+ * an anchor, a relative href or another scheme does not. The built-in browser is offered+ * first only where it can open the link.+ * - On a link the menu shows the link's rows, adding the selection's after them when the+ * selection rules take it; off a link it opens exactly as the selection rules say.*/import { describe, expect, it } from "vitest";import {EXCERPT_LABEL_CHARS,- SELECTION_MENU_ITEMS,excerptBlockquote,excerptLabel,excerptReference,@@ -71,12 +77,6 @@ describe("opensSelectionMenu", () => {});});-describe("SELECTION_MENU_ITEMS", () => {- it("is Copy, then Add to conversation", () => {- expect(SELECTION_MENU_ITEMS).toEqual(["copy", "addToConversation"]);- });-});-describe("selectionEndAnchor", () => {const box = (top: number, left: number, right: number) => ({top,diff --git a/packages/web/test/session-activity.test.ts b/packages/web/test/session-activity.test.tsindex 2bf9f8dd..06fa03e4 100644--- a/packages/web/test/session-activity.test.ts+++ b/packages/web/test/session-activity.test.ts@@ -1,26 +1,21 @@+/**+ * The activity mark a Session row wears (lib/session-activity.ts) and the words the app gives+ * it.+ *+ * - A live run (compaction included) shows whatever the read state, even before its Trace+ * exists.+ * - A settled Session is marked only while its last reply is unread; once read, or if it+ * never ran, nothing is drawn.+ * - The background count is zero without the field and the sum of both counts with it.+ * - Each state has a label of its own, since the glyph carries no text.+ */import { describe, expect, it } from "vitest";-import { createElement } from "react";-import { renderToStaticMarkup } from "react-dom/server";-import { ActivityIcon, ICON_SIZE } from "@prismshadow/penguin-ui";import {sessionActivity,sessionActivityLabel,sessionBackgroundTasks,} from "../src/lib/session-activity";import type { SessionActivity } from "../src/lib/session-activity";-import { S } from "../src/lib/strings";-import { expectEveryRootScanned, expectSingleHome, scanSources, sourceFile } from "./helpers/roots";--const SCAN = scanSources();-/** The sidebar's conversation row: the package draws the marks, the sidebar hands it their words. */-const SESSION_ROW = "packages/ui/src/components/shell/session-row/session-row.tsx";--describe("the activity marks' sources", () => {- it("scan every source root, and find the icon module in one place", () => {- expectEveryRootScanned(SCAN);- expectSingleHome(SCAN, "packages/ui/src/components/icons/activity-icon/activity-icon.tsx");- });-});type Activity = Exclude<SessionActivity, null>;const ACTIVITIES: readonly Activity[] = ["running", "compacting", "completedUnread"];@@ -61,62 +56,12 @@ describe("sessionBackgroundTasks", () => {expect(sessionBackgroundTasks({ backgroundTasks: { processes: 2, subagents: 0 } })).toBe(2);expect(sessionBackgroundTasks({ backgroundTasks: { processes: 1, subagents: 3 } })).toBe(4);});-- it("is a facet beside the activity state, not a fourth state", () => {- // An idle, read Session can still own a dev server: the glyph says nothing and the- // background count says 1, and the row draws both.- expect(sessionActivity("idle", true, false)).toBeNull();- expect(sessionBackgroundTasks({ backgroundTasks: { processes: 1, subagents: 0 } })).toBe(1);- });});-/**- * The glyph carries no text, so the app's words are its only name: each state gets its own, and- * every place the app draws a mark hands it one. The marks' own drawing is the UI package's- * (`packages/ui/test/activity-icon.test.ts`); what is checked here is that the app supplies the- * words and the room the marks need.- */-describe("the app's words for the activity marks", () => {- it("labels each state distinctly, in the interface language", () => {- expect(sessionActivityLabel("running")).toBe(S.chat.statusRunning);- expect(sessionActivityLabel("compacting")).toBe(S.chat.statusCompacting);- expect(sessionActivityLabel("completedUnread")).toBe(S.chat.statusCompletedUnread);- expect(new Set(ACTIVITIES.map(sessionActivityLabel)).size).toBe(ACTIVITIES.length);- });-- it("names the background count where it stands for a count", () => {- expect(S.chat.backgroundTasks(3)).toContain("3");- });-- it("hands every mark its label wherever the app draws one", () => {- // The sidebar row is the package's SessionRow: the sidebar names each mark, the row draws- // the mark with the name it was handed.- const sidebar = sourceFile(SCAN, "packages/web/src/components/layout/sidebar.tsx").text;- expect(sidebar).toMatch(/\{ state: activity, label: sessionActivityLabel\(activity\) \}/);- expect(sidebar).toMatch(/scheduledLabel: S\.chat\.sessionScheduled/);- expect(sidebar).toMatch(/label: S\.chat\.backgroundTasks\(background\)/);- const row = sourceFile(SCAN, SESSION_ROW).text;- expect(row).toMatch(/<ActivityIcon activity=\{activity\.state\} label=\{activity\.label\}/);- expect(row).toMatch(/<ScheduleMark label=\{scheduledLabel\}/);- expect(row).toMatch(/<BackgroundTasksMark label=\{background\.label\}/);- const desks = sourceFile(SCAN, "packages/web/src/features/company/org-session-groups.tsx").text;- expect(desks).toMatch(- /<ActivityIcon activity=\{activity\} label=\{sessionActivityLabel\(activity\)\}/,- );- });-- it("reserves the glyph's box on a row with no glyph, so a row never shifts", () => {- // Every glyph renders into the same row-mark box, and the sidebar's row reserves that box- // when there is no glyph at all — otherwise the title would re-flow as a run starts, finishes- // and is read. The placeholder is read from the row itself so the two cannot drift apart.- expect(ICON_SIZE.rowMark).toBe(12);- for (const activity of ACTIVITIES) {- const markup = renderToStaticMarkup(- createElement(ActivityIcon, { activity, label: sessionActivityLabel(activity) }),- );- expect(markup).toContain("width:12px;height:12px");- }- const row = sourceFile(SCAN, SESSION_ROW).text;- expect(row).toMatch(/activity === null.*\n?.*className="block h-3 w-3 shrink-0"/);+describe("sessionActivityLabel", () => {+ it("labels each state distinctly, since the glyph carries no text", () => {+ const labels = ACTIVITIES.map(sessionActivityLabel);+ expect(labels.every((label) => label.length > 0)).toBe(true);+ expect(new Set(labels).size).toBe(ACTIVITIES.length);});});diff --git a/packages/web/test/session-aggregation.test.ts b/packages/web/test/session-aggregation.test.tsdeleted file mode 100644index 8b8400f6..00000000--- a/packages/web/test/session-aggregation.test.ts+++ /dev/null@@ -1,296 +0,0 @@-/**- * One list, several machines (state/sessions.tsx). Each server pages its own rows with its- * own cursor; counts are summed; and the line the whole list rests on — a source that COULD- * NOT answer is not a source that ANSWERED NOTHING: this server failing abandons the reload- * and leaves the rows standing, a machine going quiet keeps its cached rows, and only a 404- * (this server has not got that Agent) is an answer.- *- * Exercised against the store directly (node, no DOM), with the API module mocked and a- * memory `localStorage` for the per-machine cache.- */-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import type { ServerEvent, SessionInfo, SessionsResponse } from "@prismshadow/penguin-server/api";-import { ApiError } from "../src/api/client";--type Answer = SessionsResponse | Error;-/** What each (machine, agent) answers; a missing entry throws like an unreachable server. */-const answers = new Map<string, Answer>();-/** Which servers were asked, and for which Workspace group — what the fan-out tests read. */-const asked: { machineId: string | null; workspaceGroup?: string }[] = [];-const key = (machineId: string | null, agentId: string) => `${machineId ?? ""}|${agentId}`;--vi.mock("../src/api/endpoints", () => ({- listSessions: async (- _projectId: string,- agentId: string,- opts: { workspaceGroup?: string } | undefined,- machineId?: string | null,- ) => {- asked.push({- machineId: machineId ?? null,- ...(opts?.workspaceGroup === undefined ? {} : { workspaceGroup: opts.workspaceGroup }),- });- const answer = answers.get(key(machineId ?? null, agentId));- if (answer === undefined) throw new ApiError(0, "network_error", "no answer");- if (answer instanceof Error) throw answer;- return answer;- },-}));--import { applyUserEvent, createSessionsStore } from "../src/state/sessions";-import { machineForSession } from "../src/lib/session-machines";-import { cachedMachineSessions, rememberMachineSessions } from "../src/lib/machine-cache";--const row = (sessionId: string, createdAt: string, agentId = "a1"): SessionInfo =>- ({- sessionId,- projectId: "p",- agentId,- workspace: "/w",- createdAt,- lastActiveAt: createdAt,- status: "idle",- hasTrace: false,- }) as SessionInfo;--const page = (- sessions: SessionInfo[],- active: number,- workspaceCounts?: Record<string, { active: number }>,-): SessionsResponse =>- ({- sessions,- counts: { active, subagent: 0, schedule: 0, archived: 0 },- ...(workspaceCounts === undefined ? {} : { workspaceCounts }),- }) as SessionsResponse;--function memoryStorage(): Storage {- const map = new Map<string, string>();- return {- get length() {- return map.size;- },- clear: () => map.clear(),- getItem: (k) => map.get(k) ?? null,- key: (i) => [...map.keys()][i] ?? null,- removeItem: (k) => void map.delete(k),- setItem: (k, v) => void map.set(k, String(v)),- };-}--describe("the list across machines", () => {- const originalStorage = (globalThis as { localStorage?: Storage }).localStorage;- beforeEach(() => {- answers.clear();- asked.length = 0;- (globalThis as { localStorage?: Storage }).localStorage = memoryStorage();- });- afterEach(() => {- (globalThis as { localStorage?: Storage }).localStorage = originalStorage;- });-- const boot = (machineIds: string[], offlineMachineIds: string[] = []) => {- const store = createSessionsStore();- store.setState({ projectId: "p", agentIds: ["a1"], machineIds, offlineMachineIds });- return store;- };-- it("asks a machine about ITS Agents too — an Agent that exists only there", async () => {- // A new chat started from a machine's Agent card belongs to an Agent this server has- // never heard of. Asked only about this Project's Agents, the machine answers nothing- // about it: the row was listed once (add) and vanished on the next reload, taking with- // it the record of which machine holds it — after which a deep link asks THIS server,- // gets a 404, and the conversation cannot be reached at all.- answers.set(key(null, "a1"), page([row("here", "2026-01-02T00:00:00Z")], 1));- answers.set(key("M1", "a1"), new ApiError(404, "not_found", "no such agent"));- answers.set(- key("M1", "theirs"),- page([row("over-there", "2026-01-03T00:00:00Z", "theirs")], 1),- );- const store = boot(["M1"]);- store.setState({ agentIdsByMachine: { M1: ["theirs"] } });- await store.getState().reload();- expect(store.getState().sessions.map((s) => s.sessionId)).toEqual(["over-there", "here"]);- expect(machineForSession("over-there")).toBe("M1");- // And this server is never asked about an Agent that is not its own.- expect(asked.filter((a) => a.machineId === null)).toHaveLength(1);- });-- it("one Agent this server cannot answer about keeps its rows; the rest still refresh", async () => {- answers.set(key(null, "a1"), page([row("a1-row", "2026-01-02T00:00:00Z")], 1));- answers.set(key(null, "a2"), page([row("a2-row", "2026-01-01T00:00:00Z", "a2")], 1));- const store = createSessionsStore();- store.setState({- projectId: "p",- agentIds: ["a1", "a2"],- machineIds: [],- offlineMachineIds: [],- });- await store.getState().reload();- expect(store.getState().sessions.map((s) => s.sessionId)).toEqual(["a1-row", "a2-row"]);-- // a2's index is damaged and its list 500s, while a1 answers as before. Erasing a2 would- // read, on screen, as an Agent with no conversations; abandoning the whole reload would- // leave the page on a skeleton nothing clears.- answers.set(key(null, "a2"), new ApiError(500, "internal", "broken index"));- answers.set(- key(null, "a1"),- page([row("a1-row", "2026-01-02T00:00:00Z"), row("a1-new", "2026-01-04T00:00:00Z")], 2),- );- await store.getState().reload();- expect(store.getState().sessions.map((s) => s.sessionId)).toEqual([- "a1-new",- "a1-row",- "a2-row",- ]);- expect(store.getState().countsByAgent.get("a1")?.active).toBe(2);- // Kept as last read: a total without this server's share would contradict the row below it.- expect(store.getState().countsByAgent.get("a2")?.active).toBe(1);- expect(store.getState().loading).toBe(false);- });-- it("merges every source newest-first, records where each row lives, and sums the counts", async () => {- answers.set(key(null, "a1"), page([row("here", "2026-01-02T00:00:00Z")], 1));- answers.set(key("M1", "a1"), page([row("there", "2026-01-03T00:00:00Z")], 2));- const store = boot(["M1"]);- await store.getState().reload();- const { sessions, countsByAgent, loading } = store.getState();- expect(sessions.map((s) => s.sessionId)).toEqual(["there", "here"]);- expect(machineForSession("there")).toBe("M1");- expect(machineForSession("here")).toBeNull();- expect(countsByAgent.get("a1")?.active).toBe(3);- expect(loading).toBe(false);- // What the machine answered is remembered for the next restart.- expect(cachedMachineSessions("p", "M1").map((s) => s.sessionId)).toEqual(["there"]);- });-- it("a server that has not got the Agent answered — 404 is an answer, and its cache is cleared", async () => {- answers.set(key(null, "a1"), page([row("here", "2026-01-02T00:00:00Z")], 1));- answers.set(key("M1", "a1"), new ApiError(404, "not_found", "no such agent"));- rememberMachineSessions("p", "M1", [row("stale", "2026-01-01T00:00:00Z")]);- const store = boot(["M1"]);- await store.getState().reload();- expect(store.getState().sessions.map((s) => s.sessionId)).toEqual(["here"]);- expect(cachedMachineSessions("p", "M1")).toEqual([]);- });-- it("a machine that could not answer keeps its cached rows on screen and its cache intact", async () => {- answers.set(key(null, "a1"), page([row("here", "2026-01-02T00:00:00Z")], 1));- // M1 is held but its server did not answer (no entry → network error); M2 has no connection.- rememberMachineSessions("p", "M1", [row("m1-cached", "2026-01-01T00:00:00Z")]);- rememberMachineSessions("p", "M2", [row("m2-cached", "2026-01-04T00:00:00Z")]);- const store = boot(["M1"], ["M2"]);- await store.getState().reload();- expect(store.getState().sessions.map((s) => s.sessionId)).toEqual([- "m2-cached",- "here",- "m1-cached",- ]);- expect(machineForSession("m2-cached")).toBe("M2");- expect(cachedMachineSessions("p", "M1").map((s) => s.sessionId)).toEqual(["m1-cached"]);- // Counts come only from servers that answered: the cache makes no claim about now.- expect(store.getState().countsByAgent.get("a1")?.active).toBe(1);- });-- it("this server not answering abandons the reload: the rows stand and loading is left alone", async () => {- answers.set(key(null, "a1"), page([row("here", "2026-01-02T00:00:00Z")], 1));- const store = boot([]);- await store.getState().reload();- expect(store.getState().sessions).toHaveLength(1);- expect(store.getState().loading).toBe(false);-- answers.delete(key(null, "a1")); // mid-swap: nothing answers here- await store.getState().reload();- expect(store.getState().sessions.map((s) => s.sessionId)).toEqual(["here"]);- expect(store.getState().loading).toBe(false);- });-- it("keeps two machines' counts for one path apart — a badge is about a directory, not a string", async () => {- // `/w` on this server and `/w` on M1 are two different directories, and each folder's- // badge has to match the rows under it. Summed onto one key, both folders claimed 7.- answers.set(- key(null, "a1"),- page([row("here", "2026-01-02T00:00:00Z")], 1, { "/w": { active: 2 } }),- );- answers.set(- key("M1", "a1"),- page([row("there", "2026-01-03T00:00:00Z")], 1, { "/w": { active: 5 } }),- );- const store = boot(["M1"]);- await store.getState().reload();- const byGroup = store.getState().workspaceCountsByAgent.get("a1");- expect(byGroup?.["/w"]?.active).toBe(2);- expect(byGroup?.[`M1\u0000/w`]?.active).toBe(5);- });-- it("a group's page is asked only of the machine that group is on, by path", async () => {- answers.set(key(null, "a1"), page([row("here", "2026-01-02T00:00:00Z")], 1));- answers.set(key("M1", "a1"), page([row("there", "2026-01-03T00:00:00Z")], 1));- const store = boot(["M1"]);- await store.getState().reload();-- asked.length = 0;- await store.getState().loadMoreFor(["a1"], "active", `M1\u0000/w`);- // `/w` exists on this server too: asking it would page another directory's rows into- // this group, and leave the group's "load more" waiting on a machine it is not on. The- // machine half never travels in the query — the request already goes to that machine.- expect(asked).toEqual([{ machineId: "M1", workspaceGroup: "/w" }]);-- asked.length = 0;- await store.getState().loadMoreFor(["a1"], "active", "/w");- expect(asked).toEqual([{ machineId: null, workspaceGroup: "/w" }]);- });-- it("a refresh over rows already on screen does not raise loading", async () => {- answers.set(key(null, "a1"), page([row("here", "2026-01-02T00:00:00Z")], 1));- const store = boot([]);- await store.getState().reload();- let raised = false;- const unsubscribe = store.subscribe((state) => {- if (state.loading) raised = true;- });- await store.getState().reload();- unsubscribe();- expect(raised).toBe(false);- });-});--/**- * Which events from a machine concern this list (applyUserEvent in state/sessions.tsx).- *- * A machine's Projects carry THIS server's ids — installing one creates the same Project- * over there, and every list call names it — so the id in the event is as meaningful from a- * machine as from here.- */-describe("events arriving from a machine", () => {- const created = (projectId: string): ServerEvent =>- ({ type: "session_created", projectId, agentId: "a1", sessionId: "s1" }) as ServerEvent;-- const countingStore = () => {- const store = createSessionsStore();- store.setState({ projectId: "p", agentIds: ["a1"] });- let reloads = 0;- store.setState({- reload: async () => {- reloads += 1;- },- });- return { store, reloads: () => reloads };- };-- it("reloads for this Project, wherever the Session was created", () => {- const { store, reloads } = countingStore();- applyUserEvent(store, created("p"), () => undefined, "M1");- applyUserEvent(store, created("p"), () => undefined, null);- expect(reloads()).toBe(2);- });-- it("ignores another Project on a machine, as it does here", () => {- // Unconditional for machines, every Session and every subagent started in any other- // Project on any connected machine refetched this whole list, Agents x sources.- const { store, reloads } = countingStore();- applyUserEvent(store, created("other"), () => undefined, "M1");- applyUserEvent(store, created("other"), () => undefined, null);- expect(reloads()).toBe(0);- });-});diff --git a/packages/web/test/session-grouping.test.ts b/packages/web/test/session-grouping.test.tsindex c4830640..2480d3db 100644--- a/packages/web/test/session-grouping.test.ts+++ b/packages/web/test/session-grouping.test.ts@@ -1,19 +1,34 @@/**- * Workspace grouping and the time buckets for the chat sidebar (pure logic).+ * How the chat sidebar groups Sessions (lib/session-grouping.ts): by Workspace, by time+ * bucket, and into the folders under each group.*- * Workspace grouping:- * - named Workspaces group by exact path, labeled by basename (full path kept for- * tooltips), newest group first;- * - temporary Workspaces (`<agentDir>/workspaces/tmp-<8hex>`, the shape produced by- * core's createTempWorkspace) are all merged into ONE trailing temp group — an- * empty path (defensive; the server always backfills the resolved dir) counts too;- * - sessions inside every group are re-sorted newest first: the flat store list- * concatenates per-Agent server responses, so its order isn't globally chronological.+ * - A temporary Workspace (`…/workspaces/<dir>` of an Agent, or an empty path) is recognized+ * on either path separator; near misses and nested directories are not.+ * - A group key is the trimmed path, or one shared sentinel for every temporary Workspace; a+ * machine's directory keys under that machine and splits back into machine and path, while+ * the server query carries the path only. A label is the path's last segment.+ * - Grouping by Workspace merges Agents on one path (newest Session first, newest group first),+ * folds every temporary Workspace into one trailing group per machine, keeps one path on two+ * machines apart, and keeps archived rows in their group.+ * - A Session's folder is decided by archived first, then its source; partitioning keeps the+ * order inside each folder, and benchmark runs get a folder of their own.+ * - The auto-opened "last conversation" is the most recently active user or scheduled row+ * (ties by id), never an archived, subagent or benchmark one.+ * - A page fetched with one extra row reports whether the server has more, never showing it.+ * - Server counts sum per Workspace across Agents (recording which Agents hold each folder) and+ * stay apart per machine; the newest stamp per group survives aggregation.+ * - Pinned items come first, each partition keeping its order; unknown pins are ignored.+ * - Title search is a case-insensitive substring match; a blank query matches everything and+ * an untitled Session matches no non-blank query.+ * - Time buckets cut at 24 hours and 30 days on last activity, skewed stamps land newest and+ * unreadable ones oldest, empty buckets are dropped, and bucket keys never collide with a+ * path or an Agent id.+ * - Every counted Workspace becomes a group (empty when none of its rows loaded), placed by+ * the newer of its stamp and its loaded rows, the temp group last; a count of zero forms none.*/import { describe, expect, it } from "vitest";import type { SessionCategoryCounts, SessionInfo } from "@prismshadow/penguin-server/api";import {- FOLDER_CATEGORIES,SIDEBAR_PAGE_SIZE,TEMP_WORKSPACE_GROUP_KEY,TIME_BUCKETS,@@ -330,8 +345,6 @@ describe("benchmark Sessions (the Evaluation Center's runs)", () => {const parts = partitionSessions([run, user]);expect(parts.benchmark.map((s) => s.sessionId)).toEqual([run.sessionId]);expect(parts.active.map((s) => s.sessionId)).toEqual([user.sessionId]);- // Its own collapsed folder, rendered between Scheduled and Archived.- expect(FOLDER_CATEGORIES).toEqual(["subagent", "schedule", "benchmark", "archived"]);// The evaluator's run is not the conversation the user was last in.expect(latestConversation([run, user])).toBe(user);});diff --git a/packages/web/test/session-order.test.ts b/packages/web/test/session-order.test.tsindex d741b78c..a2327cfc 100644--- a/packages/web/test/session-order.test.ts+++ b/packages/web/test/session-order.test.ts@@ -1,13 +1,21 @@/**- * session-order.ts unit tests: the sidebar's row sort mode and manual drag order. The- * sort mode is one global preference defaulting to "recent" (a fresh profile looks- * unchanged); the manual order is one per-Project id array where only the relative- * order of ids co-rendered in a partition matters. Ordering composes with the row- * pins: the pinned cluster is always first, manual order applies within each pin- * partition independently, and a drop commits the partition's sequence to the front- * of the stored array without disturbing other groups' relative order. Newcomers- * (ids not stored) surface at the TOP of their partition in recency order; stale- * stored ids are inert; deletion prunes with a same-reference fast path.+ * The sidebar's row order (lib/session-order.ts): the global sort mode and the per-Project+ * manual drag order, composed with the row pins.+ *+ * - The sort mode defaults to recent (nothing stored, an unknown value, a throwing storage)+ * and round-trips manual and back.+ * - Given no Project or nothing stored, the manual order is empty and reading writes nothing;+ * an order saved per Project and grouping mode reads back for exactly that pair.+ * - A malformed stored order reads as empty, keeping the well-formed ids; a storage whose+ * getter throws degrades instead of escaping.+ * - Stored rows take their stored positions, unstored newcomers come first in recency order,+ * and stale stored ids are inert.+ * - Recent mode sorts by last activity (ties by id descending) without mutating the input.+ * - Manual mode applies the stored order inside each pin partition, newcomers on top of theirs.+ * - A drop moves one id before or after another, and a drop that moves nothing returns the+ * input so nothing is written; committing a partition fronts it and keeps the others'+ * relative order, including rows past the display cap.+ * - Deleting a Session prunes its id, returning the same array when it was not stored.*/import { describe, expect, it } from "vitest";import {@@ -24,41 +32,24 @@ import {storeSessionSortMode,} from "../src/lib/session-order";import type { SessionOrderStorage } from "../src/lib/session-order";--/** In-memory storage (vitest runs in a Node environment, no localStorage; draft-cache.test.ts convention). */-function memStorage(): SessionOrderStorage & { map: Map<string, string> } {- const map = new Map<string, string>();- return {- map,- getItem: (k) => map.get(k) ?? null,- setItem: (k, v) => void map.set(k, v),- };-}+import { blockedStorage, memoryStorage } from "./helpers/storage";const id = (x: string) => x;describe("sort-mode store (one global preference)", () => {it("default is recent: nothing stored, unrecognized values, and throwing storage all read as recent", () => {- const s = memStorage();+ const s = memoryStorage();expect(initialSessionSortMode(s)).toBe("recent");for (const raw of ["", "MANUAL", "drag", "true"]) {s.map.set(SESSION_SORT_MODE_KEY, raw);expect(initialSessionSortMode(s)).toBe("recent");}- const broken: SessionOrderStorage = {- getItem: () => {- throw new Error("denied");- },- setItem: () => {- throw new Error("denied");- },- };- expect(initialSessionSortMode(broken)).toBe("recent");- expect(() => storeSessionSortMode("manual", broken)).not.toThrow();+ expect(initialSessionSortMode(blockedStorage())).toBe("recent");+ expect(() => storeSessionSortMode("manual", blockedStorage())).not.toThrow();});it("round-trips manual and back", () => {- const s = memStorage();+ const s = memoryStorage();storeSessionSortMode("manual", s);expect(s.map.get(SESSION_SORT_MODE_KEY)).toBe("manual");expect(initialSessionSortMode(s)).toBe("manual");@@ -69,7 +60,7 @@ describe("sort-mode store (one global preference)", () => {describe("manual-order store (per-Project × grouping-mode localStorage)", () => {it("nothing stored — or no Project yet — is empty, reading never writes, saving without a Project is a no-op", () => {- const s = memStorage();+ const s = memoryStorage();expect(loadSessionOrder("p1", "workspace", s)).toEqual([]);expect(loadSessionOrder(null, "workspace", s)).toEqual([]);expect(s.map.size).toBe(0);@@ -78,7 +69,7 @@ describe("manual-order store (per-Project × grouping-mode localStorage)", () =>});it("save → load round-trips per Project; Projects are isolated", () => {- const s = memStorage();+ const s = memoryStorage();saveSessionOrder("p1", "workspace", ["b", "a"], s);saveSessionOrder("p2", "workspace", ["c"], s);expect(loadSessionOrder("p1", "workspace", s)).toEqual(["b", "a"]);@@ -87,7 +78,7 @@ describe("manual-order store (per-Project × grouping-mode localStorage)", () =>});it("the two grouping modes keep separate orders (their partitions differ, so one array would scramble the other)", () => {- const s = memStorage();+ const s = memoryStorage();saveSessionOrder("p1", "workspace", ["b", "a"], s);saveSessionOrder("p1", "agent", ["a", "b"], s);expect(loadSessionOrder("p1", "workspace", s)).toEqual(["b", "a"]);@@ -96,7 +87,7 @@ describe("manual-order store (per-Project × grouping-mode localStorage)", () =>});it("malformed JSON / non-array shapes degrade to empty; junk array elements are dropped", () => {- const s = memStorage();+ const s = memoryStorage();for (const raw of ["{not json", '"a"', "42", "null", "{}", ""]) {s.map.set(sessionOrderKey("p1", "workspace"), raw);expect(loadSessionOrder("p1", "workspace", s)).toEqual([]);diff --git a/packages/web/test/session-probe.test.ts b/packages/web/test/session-probe.test.tsindex 42557b13..39990610 100644--- a/packages/web/test/session-probe.test.ts+++ b/packages/web/test/session-probe.test.ts@@ -2,14 +2,16 @@* The session probe (`probeSession`): the one question a window asks when it suspects it is* no longer signed in — after its stream dies, or when it comes back to the foreground.*- * What it must get right is the asymmetry: a 401 signs the window out through the api- * client's global handler, and every other failure leaves the user exactly where they are,- * because an offline laptop is not a revoked session. Plus the cheapness the callers rely- * on — a burst of focus and stream-error events costs one request.+ * - A 401 signs the window out through the api client's global handler.+ * - A good session says nothing.+ * - An unreachable or broken server never signs the window out: an offline laptop is not a+ * revoked session.+ * - A burst of probes costs one request, and a probe after it settles asks again.*/-import { afterEach, describe, expect, it, vi } from "vitest";+import { afterEach, describe, expect, it } from "vitest";import { setUnauthorizedHandler } from "../src/api/client";import { probeSession } from "../src/api/session-probe";+import { apiError, json, stubFetch } from "./helpers/fetch";/** Counts the global sign-out the api client fires on a 401. */function countSignOuts(): { readonly count: number } {@@ -20,20 +22,13 @@ function countSignOuts(): { readonly count: number } {return seen;}-const json = (body: unknown, status: number): Response =>- new Response(JSON.stringify(body), {- status,- headers: { "content-type": "application/json" },- });-describe("probeSession", () => {afterEach(() => {- vi.unstubAllGlobals();setUnauthorizedHandler(null);});it("signs the window out when the server answers 401", async () => {- vi.stubGlobal("fetch", async () => json({ error: { code: "unauthorized" } }, 401));+ stubFetch(() => apiError(401, "unauthorized"));const signOuts = countSignOuts();await probeSession();@@ -42,7 +37,7 @@ describe("probeSession", () => {});it("says nothing when the session is still good", async () => {- vi.stubGlobal("fetch", async () => json({ user: { userId: "admin" } }, 200));+ stubFetch(() => json({ user: { userId: "admin" } }));const signOuts = countSignOuts();await probeSession();@@ -53,38 +48,36 @@ describe("probeSession", () => {it("never signs the window out over an unreachable or broken server", async () => {const signOuts = countSignOuts();- vi.stubGlobal("fetch", async () => {- throw new Error("connection refused");+ const fetch = stubFetch(() => {+ throw new TypeError("connection refused");});await expect(probeSession()).resolves.toBeUndefined();- vi.stubGlobal("fetch", async () => json({ error: { code: "internal" } }, 500));+ fetch.answer(() => apiError(500, "internal"));await expect(probeSession()).resolves.toBeUndefined();expect(signOuts.count).toBe(0);});it("collapses a burst into a single request, and asks again once it has settled", async () => {- let calls = 0;let answer: () => void = () => {};const pending = new Promise<void>((resolve) => {answer = resolve;});- vi.stubGlobal("fetch", async () => {- calls += 1;+ const fetch = stubFetch(async () => {await pending;- return json({ user: { userId: "admin" } }, 200);+ return json({ user: { userId: "admin" } });});const first = probeSession();const second = probeSession();- expect(calls).toBe(1);+ expect(fetch.requests).toHaveLength(1);answer();await Promise.all([first, second]);- expect(calls).toBe(1);+ expect(fetch.requests).toHaveLength(1);await probeSession();- expect(calls).toBe(2);+ expect(fetch.requests).toHaveLength(2);});});diff --git a/packages/web/test/session-row-menu.test.ts b/packages/web/test/session-row-menu.test.tsindex a057fc4e..b1c51af0 100644--- a/packages/web/test/session-row-menu.test.ts+++ b/packages/web/test/session-row-menu.test.ts@@ -1,81 +1,36 @@/**- * session-row-menu.tsx unit tests: which actions each of a Session row's two surfaces- * offers, and how each one labels itself.+ * A Session row's two action surfaces (components/ui/session-row-menu.tsx): the hover buttons+ * and the right-click menu, and how each action labels itself.*- * The split is the point and the thing most likely to be undone by accident, so it is- * pinned by value rather than by shape: **hover gives archive plus the ellipsis "more"- * button and nothing else** — the ellipsis opens the context menu anchored at itself, so- * every menu action (delete and the messaging binding included) is one visible click- * away — while the right-click menu carries the full set. Rename in particular must stay- * in the context menu: every Session must remain renamable, archivable and deletable, and- * the pared-back hover affordance alone would not satisfy that.- *- * vitest runs node-only here (`environment: "node"`, no jsdom), so these assert against- * the exported manifests and label helpers rather than a rendered DOM- * (title-reveal.test.ts convention).+ * - A pinnable row's menu carries pin, rename, messaging, archive, copy and delete; a folder+ * row's menu drops only pin, so every Session stays renamable, archivable and deletable.+ * - Every hover action is also in the menu, so nothing is reachable by hover alone.+ * - Every action has a label and a glyph of its own, and only delete is destructive.+ * - Archive flips its label and glyph on an archived row; pin flips its label on a pinned row+ * and keeps its glyph.+ * - In English no action falls back to a Chinese label (the hover buttons are icon-only, so+ * the label is their accessible name).*/import { afterEach, describe, expect, it } from "vitest";-import { ICONS } from "@prismshadow/penguin-ui";import {HOVER_ROW_ACTIONS,contextMenuActions,sessionRowMenuItem,} from "../src/components/ui/session-row-menu";import type { SessionRowAction } from "../src/components/ui/session-row-menu";-import { STAT_ICONS } from "../src/lib/stat-icons";import { setActiveStrings, zh } from "../src/lib/strings";import { en } from "../src/lib/strings-en";-import { expectEveryRootScanned, expectSingleHome, scanSources, sourceFile } from "./helpers/roots";--const SCAN = scanSources();-const ROW_MENU = "packages/web/src/components/ui/session-row-menu.tsx";-/** The package's row, which draws the hover buttons both the sidebar and the desk rows use. */-const SESSION_ROW = "packages/ui/src/components/shell/session-row/session-row.tsx";/** Every test that switches locale puts the default (zh) back. */afterEach(() => setActiveStrings(zh));const RESTING = { archived: false, pinned: false };--describe("the row menu's sources", () => {- it("scan every source root, and find the row menu in one place", () => {- expectEveryRootScanned(SCAN);- expectSingleHome(SCAN, ROW_MENU);- });-});--describe("HOVER_ROW_ACTIONS", () => {- it("is archive alone — the ellipsis beside it is the menu's pointer entry, not an action", () => {- expect([...HOVER_ROW_ACTIONS]).toEqual(["archive"]);- });-- it("does not carry rename, pin, delete or the messaging binding — those live in the menu", () => {- for (const action of ["rename", "pin", "delete", "messaging", "copy"]) {- expect(HOVER_ROW_ACTIONS as readonly string[]).not.toContain(action);- }- });-});+const ALL: SessionRowAction[] = ["pin", "rename", "messaging", "archive", "copy", "delete"];describe("contextMenuActions", () => {- it("carries the whole set when the row can be pinned, with the id copy between archive and delete", () => {- expect([...contextMenuActions(true)]).toEqual([- "pin",- "rename",- "messaging",- "archive",- "copy",- "delete",- ]);- });-- it("drops only pin on rows where pinning cannot reorder anything (folder rows)", () => {- expect([...contextMenuActions(false)]).toEqual([- "rename",- "messaging",- "archive",- "copy",- "delete",- ]);+ it("a pinnable row's menu carries the whole set; a folder row's drops only pin", () => {+ expect([...contextMenuActions(true)]).toEqual(ALL);+ expect([...contextMenuActions(false)]).toEqual(ALL.filter((action) => action !== "pin"));});it("is a superset of the hover actions, so nothing is reachable by hover alone", () => {@@ -85,54 +40,11 @@ describe("contextMenuActions", () => {}}});-- it("keeps rename reachable in every state", () => {- expect(contextMenuActions(true)).toContain("rename");- expect(contextMenuActions(false)).toContain("rename");- });-- it("offers the id copy on every row, including the folder rows that cannot pin", () => {- // The id is what a person carries out of the app — into the CLI, a bug report, a- // trace lookup — and an archived or scheduled Session is exactly when it is wanted.- expect(contextMenuActions(true)).toContain("copy");- expect(contextMenuActions(false)).toContain("copy");- });-});--describe("the hover buttons' CSS contract", () => {- // Node-only suite, so this is asserted against the source text (title-reveal.test.ts- // convention). It is worth pinning: an invisible button still takes taps, and these are- // invisible for the whole of every touch session, delete included. The buttons are the UI- // package's (`RowHoverActions`); this module hands them their actions.- const source = sourceFile(SCAN, SESSION_ROW).text;-- it("gates pointer events on the same conditions as visibility, leaving no phantom tap target", () => {- expect(source).toContain("pointer-events-none");- // Both reveal paths must re-arm the click, or the buttons would be visible and dead —- // and each reveal must pair with its own pointer-events grant, since either half alone- // yields a button that is visible-but-dead or invisible-but-tappable.- for (const on of ["group-hover", "focus"]) {- expect(source).toContain(`${on}:pointer-events-auto`);- expect(source).toContain(`${on}:opacity-100`);- }- // `focus`, not `focus-visible`: the time span it swaps with hides on plain- // focus-within, and the two conditions have to agree or the slot goes blank.- expect(source).not.toContain("focus-visible:opacity-100");- });-- it("renders the ellipsis as a labelled menu trigger anchored at its own box", () => {- // The menu's discoverable pointer entry: a real button that reports it opens a menu- // and anchors the panel at its own rect (not the pointer position).- expect(source).toContain('aria-haspopup="menu"');- expect(source).toContain("ICONS.ellipsis");- expect(source).toContain("getBoundingClientRect");- });});describe("sessionRowMenuItem", () => {it("gives every action a label, a glyph, and only delete the destructive treatment", () => {- const all: SessionRowAction[] = ["pin", "rename", "messaging", "archive", "copy", "delete"];- for (const action of all) {+ for (const action of ALL) {const item = sessionRowMenuItem(action, RESTING);expect(item.label).toBeTruthy();expect(item.icon).toBeTruthy();@@ -140,59 +52,31 @@ describe("sessionRowMenuItem", () => {}});- it("gives the actions distinct glyphs, so a row is not read by its label alone", () => {- const icons = (- ["pin", "rename", "messaging", "archive", "copy", "delete"] as SessionRowAction[]- ).map((a) => sessionRowMenuItem(a, RESTING).icon);- expect(new Set(icons).size).toBe(icons.length);- // Remote control wears the same paper plane the session row flies while it is relaying:- // the action and the mark it produces are one feature.- expect(icons).toEqual([- ICONS.pin,- ICONS.pencil,- ICONS.paperPlane,- ICONS.archive,- // The same glyph the details card's copy button shows, so one value has one mark.- STAT_ICONS.copy,- ICONS.trash,- ]);+ it("gives the actions distinct labels and glyphs, so a row is not read by its label alone", () => {+ const items = ALL.map((action) => sessionRowMenuItem(action, RESTING));+ expect(new Set(items.map((item) => item.icon)).size).toBe(ALL.length);+ expect(new Set(items.map((item) => item.label)).size).toBe(ALL.length);});it("flips archive's label and glyph on an archived row", () => {- expect(sessionRowMenuItem("archive", { archived: false, pinned: false })).toMatchObject({- label: zh.chat.archiveSession,- icon: ICONS.archive,- });- expect(sessionRowMenuItem("archive", { archived: true, pinned: false })).toMatchObject({- label: zh.chat.unarchiveSession,- icon: ICONS.archiveRestore,- });+ const archive = sessionRowMenuItem("archive", RESTING);+ const restore = sessionRowMenuItem("archive", { archived: true, pinned: false });+ expect(restore.label).not.toBe(archive.label);+ expect(restore.icon).not.toBe(archive.icon);});it("flips pin's label on a pinned row, keeping the one pin glyph", () => {- expect(sessionRowMenuItem("pin", { archived: false, pinned: false }).label).toBe(- zh.chat.pinSession,- );- expect(sessionRowMenuItem("pin", { archived: false, pinned: true }).label).toBe(- zh.chat.unpinSession,- );- expect(sessionRowMenuItem("pin", { archived: false, pinned: true }).icon).toBe(ICONS.pin);+ const pin = sessionRowMenuItem("pin", RESTING);+ const unpin = sessionRowMenuItem("pin", { archived: false, pinned: true });+ expect(unpin.label).not.toBe(pin.label);+ expect(unpin.icon).toBe(pin.icon);});- it("reads the active dictionary, so both locales name every action", () => {+ it("names every action in English once the locale is English", () => {setActiveStrings(en);- expect(sessionRowMenuItem("archive", RESTING).label).toBe(en.chat.archiveSession);- expect(sessionRowMenuItem("delete", RESTING).label).toBe(en.chat.deleteSession);- expect(sessionRowMenuItem("rename", RESTING).label).toBe(en.chat.renameSession);- expect(sessionRowMenuItem("copy", RESTING).label).toBe(en.chat.copySessionId);- expect(sessionRowMenuItem("messaging", RESTING).label).toBe(en.messaging.bindAction);- // The hover buttons are icon-only, so their label IS their accessible name: an English- // row must not fall back to the zh catalog and leave a Chinese name on the button.- for (const action of HOVER_ROW_ACTIONS) {- const label = sessionRowMenuItem(action, RESTING).label;- expect(label).toBeTruthy();- expect(label).not.toBe(sessionRowMenuItem(action, RESTING).icon);- expect(Object.values(zh.chat)).not.toContain(label);+ const zhLabels = new Set([...Object.values(zh.chat), ...Object.values(zh.messaging)]);+ for (const action of ALL) {+ expect(zhLabels.has(sessionRowMenuItem(action, RESTING).label)).toBe(false);}});});diff --git a/packages/web/test/session-seen.test.ts b/packages/web/test/session-seen.test.tsindex 64ce68f4..c91e5d89 100644--- a/packages/web/test/session-seen.test.ts+++ b/packages/web/test/session-seen.test.ts@@ -1,3 +1,20 @@+/**+ * Which Sessions the user has read (lib/session-seen.ts): a per-Project marker per Session in+ * localStorage, against which a row's last activity reads as unread or not.+ *+ * - Activity after a Session's marker is unread; at or before it, read.+ * - A Session with no marker falls back to the Project's seed, so conversations that existed+ * before this browser first looked do not all start unread; with no seed, all are unread.+ * - An unparseable activity stamp never raises an alert.+ * - Marking a Session seen stamps the later of the wall clock and its last activity (a lagging+ * local clock still marks it read), leaves other markers alone, and returns the same state+ * when nothing changes.+ * - Forgetting a Session drops its marker, or returns the state unchanged when it had none.+ * - Markers survive a serialize/parse cycle; junk parses to nothing remembered, malformed+ * markers are dropped, and the stored markers are capped, evicting the least recently seen.+ * - The first note in a Project seeds it; notes are scoped per Project, need a Project, and a+ * deleted Session's marker is pruned.+ */import { beforeEach, describe, expect, it } from "vitest";import {forgetSession,@@ -10,7 +27,8 @@ import {serializeSessionSeen,sessionSeenKey,} from "../src/lib/session-seen";-import type { SessionSeenState, SessionSeenStorage } from "../src/lib/session-seen";+import type { SessionSeenState } from "../src/lib/session-seen";+import { memoryStorage } from "./helpers/storage";const AT = (iso: string) => Date.parse(iso);// Fixtures sit safely in the past: noteSessionSeen seeds from the real clock, so a "future"@@ -24,16 +42,6 @@ const state = (seededAt: number, seen: Record<string, number> = {}): SessionSeenseen: new Map(Object.entries(seen)),});-/** In-memory localStorage stand-in (vitest runs in Node). */-function memoryStorage(initial: Record<string, string> = {}) {- const map = new Map(Object.entries(initial));- return {- getItem: (k: string) => map.get(k) ?? null,- setItem: (k: string, v: string) => void map.set(k, v),- read: (k: string) => map.get(k) ?? null,- } satisfies SessionSeenStorage & { read: (k: string) => string | null };-}-describe("isSessionUnread", () => {it("treats activity after the marker as unread and activity before it as read", () => {const s = state(0, { a: AT(T1) });@@ -133,7 +141,7 @@ describe("noteSessionSeen", () => {it("seeds on the first write so existing conversations start out read", () => {const storage = memoryStorage();noteSessionSeen("proj", "a", T1, storage);- const stored = parseSessionSeen(storage.read(sessionSeenKey("proj")));+ const stored = parseSessionSeen(storage.getItem(sessionSeenKey("proj")));expect(stored.seededAt).toBeGreaterThan(0);// A different Session that last ran before the seed reads as read.expect(isSessionUnread(stored, "other", T0)).toBe(false);@@ -143,20 +151,20 @@ describe("noteSessionSeen", () => {it("scopes markers per Project", () => {const storage = memoryStorage();noteSessionSeen("one", "a", T1, storage);- expect(storage.read(sessionSeenKey("one"))).not.toBeNull();- expect(storage.read(sessionSeenKey("two"))).toBeNull();+ expect(storage.getItem(sessionSeenKey("one"))).not.toBeNull();+ expect(storage.getItem(sessionSeenKey("two"))).toBeNull();});it("is a no-op without a Project", () => {const storage = memoryStorage();noteSessionSeen(null, "a", T1, storage);- expect(storage.read(sessionSeenKey("proj"))).toBeNull();+ expect(storage.getItem(sessionSeenKey("proj"))).toBeNull();});it("prunes a deleted Session's marker", () => {const storage = memoryStorage();noteSessionSeen("proj", "a", T1, storage);forgetSession("proj", "a", storage);- expect(parseSessionSeen(storage.read(sessionSeenKey("proj"))).seen.has("a")).toBe(false);+ expect(parseSessionSeen(storage.getItem(sessionSeenKey("proj"))).seen.has("a")).toBe(false);});});diff --git a/packages/web/test/session-status-events.test.ts b/packages/web/test/session-status-events.test.tsindex 042b1c4d..c2da82f9 100644--- a/packages/web/test/session-status-events.test.ts+++ b/packages/web/test/session-status-events.test.ts@@ -1,15 +1,26 @@/**- * Live Session status over the user-level event stream (state/sessions.tsx).+ * Live Session status over the user-level event stream (state/sessions.tsx, applyUserEvent),+ * and the glyph a sidebar row ends up drawing across a whole run (sessionRowActivity, the+ * function the row itself calls). A tab subscribes only to the conversation it has open, so+ * every other row depends on the user channel.*- * A tab subscribes to the one conversation it has open, so the Session channel's `task_state`- * can only ever move that row's badge; every other row would sit on whatever status its last- * list fetch returned. The user channel's `session_state` closes that gap, and these tests pin- * both halves of it: what the store does with the event, and the glyph the row ends up drawing- * across a whole run — which is the case the feature exists for.- *- * The store is exercised directly (createSessionsStore / applyUserEvent): vitest runs this- * package in Node with no DOM, so there is no React tree to mount. `sessionRowActivity` is the- * same function the sidebar row calls, so the glyph assertions are the real rule, not a copy.+ * - session_state moves the named row (state and stamp, compaction as its own state) and+ * leaves every other row alone; a stamp change alone still lands.+ * - session_background sets or clears the named row's counts, and moves neither the glyph nor+ * the status.+ * - session_title renames the named row in place.+ * - An event for a Session no loaded page holds changes nothing, and one that matches the row+ * already is a no-op (the same array, so nothing re-renders).+ * - A first run settles into the unread dot, not a blank: the run itself proves the Session+ * has a Trace, from the server's flag or a live status, and a Session that ran never goes+ * back to blank; a brand-new or genuinely never-run Session stays blank.+ * - For a Session the user is not looking at: nothing, hourglass, unread dot, and nothing+ * again once opened — also for one opened earlier, for compaction, and in a tab that did not+ * start the task.+ * - The open Session finishes as read; its own stream and the user channel converge on one+ * row; a status before its row is loaded is dropped.+ * - web_updated reloads the window, resync_required and this Project's schedule_fired refetch+ * the list, and anything else is ignored.*/import { describe, expect, it } from "vitest";import type { ServerEvent, SessionInfo, SessionStatus } from "@prismshadow/penguin-server/api";@@ -104,22 +115,6 @@ describe("session_state on the user channel", () => {expect(rowOf(store, "a").lastActiveAt).toBe(LOOKED);});- it("ignores a Session no loaded page holds instead of inventing a row", () => {- const store = storeWith(session("a"));- const before = store.getState().sessions;- applyUserEvent(store, stateEvent("not-loaded", "running", STARTED), neverReload);- // Same array reference: nothing was appended and nothing re-rendered.- expect(store.getState().sessions).toBe(before);- expect(store.getState().sessions.map((s) => s.sessionId)).toEqual(["a"]);- });-- it("a repeated event is a no-op (state, stamp and trace flag all already match)", () => {- const store = storeWith(session("a", { status: "running", lastActiveAt: STARTED }));- const before = store.getState().sessions;- applyUserEvent(store, stateEvent("a", "running", STARTED), neverReload);- expect(store.getState().sessions).toBe(before);- });-it("carries a stamp change through even when the state itself did not change", () => {// Run start and run end both stamp the row; a goal loop's rounds keep it "running".const store = storeWith(session("a", { status: "running" }));@@ -157,25 +152,6 @@ describe("session_background on the user channel", () => {expect(sessionBackgroundTasks(rowOf(store, "a"))).toBe(0);});- it("ignores a Session no loaded page holds instead of inventing a row", () => {- const store = storeWith(session("a"));- const before = store.getState().sessions;- applyUserEvent(store, backgroundEvent("not-loaded", 1, 0), neverReload);- expect(store.getState().sessions).toBe(before);- });-- it("is a no-op when the counts already match", () => {- const store = storeWith(session("a", { backgroundTasks: { processes: 2, subagents: 1 } }));- const before = store.getState().sessions;- applyUserEvent(store, backgroundEvent("a", 2, 1), neverReload);- expect(store.getState().sessions).toBe(before);- // Zero onto an already-clear row is the same non-event.- const clear = storeWith(session("b"));- const beforeClear = clear.getState().sessions;- applyUserEvent(clear, backgroundEvent("b", 0, 0), neverReload);- expect(clear.getState().sessions).toBe(beforeClear);- });-it("moves neither the glyph nor the status: an idle, read row keeps its blank glyph and gains the mark", () => {const store = storeWith(session("a"));const seen = seenAt("a", LOOKED);@@ -205,23 +181,53 @@ describe("session_title on the user channel", () => {expect(rowOf(store, "b").title).toBe("Login page bug");expect(rowOf(store, "a").title).toBeUndefined();});+});++describe("events that need no change", () => {+ const events: ServerEvent[] = [+ stateEvent("not-loaded", "running", STARTED),+ { type: "session_background", sessionId: "not-loaded", processes: 1, subagents: 0 },+ { type: "session_title", sessionId: "not-loaded", title: "whatever" },+ ];- it("ignores a Session no loaded page holds instead of inventing a row", () => {+ it("an event for a Session no loaded page holds invents no row and re-renders nothing", () => {+ // The user channel carries every Session this user can see, most of them absent from+ // this list: an unlisted id must not churn the array and re-render every row.const store = storeWith(session("a"));const before = store.getState().sessions;- applyUserEvent(store, titleEvent("not-loaded", "whatever"), neverReload);- expect(store.getState().sessions.map((s) => s.sessionId)).toEqual(["a"]);- // The user channel carries every Session this user can see, most of them absent from this- // list: an unlisted id must not churn the array and re-render every row.+ for (const event of events) applyUserEvent(store, event, neverReload);expect(store.getState().sessions).toBe(before);});- it("is a no-op when the row already carries that title (both channels deliver it)", () => {- const store = storeWith(session("a"));- applyUserEvent(store, titleEvent("a", "Login page bug"), neverReload);- const after = store.getState().sessions;- applyUserEvent(store, titleEvent("a", "Login page bug"), neverReload);- expect(store.getState().sessions).toBe(after);+ it("an event the row already matches is a no-op (both channels deliver the same facts)", () => {+ const store = storeWith(+ session("a", {+ status: "running",+ lastActiveAt: STARTED,+ title: "Login page bug",+ backgroundTasks: { processes: 2, subagents: 1 },+ }),+ session("b"),+ );+ const before = store.getState().sessions;+ applyUserEvent(store, stateEvent("a", "running", STARTED), neverReload);+ applyUserEvent(+ store,+ { type: "session_background", sessionId: "a", processes: 2, subagents: 1 },+ neverReload,+ );+ applyUserEvent(+ store,+ { type: "session_title", sessionId: "a", title: "Login page bug" },+ neverReload,+ );+ // Zero onto an already-clear row is the same non-event.+ applyUserEvent(+ store,+ { type: "session_background", sessionId: "b", processes: 0, subagents: 0 },+ neverReload,+ );+ expect(store.getState().sessions).toBe(before);});});diff --git a/packages/web/test/sessions-loading.test.ts b/packages/web/test/sessions-loading.test.tsdeleted file mode 100644index b6076825..00000000--- a/packages/web/test/sessions-loading.test.ts+++ /dev/null@@ -1,26 +0,0 @@-/**- * The store's `loading` flag never lies "done" (state/sessions.tsx).- *- * The flag is what every "no Sessions yet" empty state gates on, so its one hard rule is- * that it must not read false while nothing has been fetched. The store is exercised- * directly (node, no DOM): the Provider's reset step owns *raising* the flag on a- * fetch-context change, which a store test cannot see — what it can pin is that the store- * itself never clears the flag without having loaded anything.- */-import { describe, expect, it } from "vitest";-import { createSessionsStore } from "../src/state/sessions";--describe("sessions store loading", () => {- it("starts loading — a fresh store has fetched nothing", () => {- expect(createSessionsStore().getState().loading).toBe(true);- });-- it("reload() without an Agent set returns without claiming to be done", async () => {- const store = createSessionsStore();- store.setState({ projectId: "proj", agentIds: [] });- await store.getState().reload();- // Nothing was fetched, so nothing may report "loaded" — clearing here is what painted- // an empty state over a list that was merely not known yet.- expect(store.getState().loading).toBe(true);- });-});diff --git a/packages/web/test/sessions-own-rows.test.ts b/packages/web/test/sessions-own-rows.test.tsdeleted file mode 100644index 26d6250d..00000000--- a/packages/web/test/sessions-own-rows.test.ts+++ /dev/null@@ -1,185 +0,0 @@-/**- * The development list holds the user's own conversations, end to end (state/sessions.tsx).- *- * An organization's desk and ticket Sessions (and the sub-sessions they spawn) must never- * reach development mode's list — not as rows, and not as the totals and Workspace stamps- * the sidebar builds groups from. The store therefore asks the server for its own rows only- * on every fetch, keeps the server's totals as they are when an organization row still- * enters by another door (a deep link's self-heal) and carries that row across reloads, and- * remembers every live status the user channel reports whether or not a loaded page holds the- * row — which is what company mode's surfaces read, now that the rows themselves are no longer- * fetched here — until a resync says flips were lost.- *- * The store is exercised directly (node, no DOM); the API module is mocked at the seam.- */-import { beforeEach, describe, expect, it, vi } from "vitest";-import type { ServerEvent, SessionInfo, SessionsResponse } from "@prismshadow/penguin-server/api";--vi.mock("../src/api/endpoints", () => ({ listSessions: vi.fn() }));--import * as api from "../src/api/endpoints";-import { applyUserEvent, createSessionsStore, liveSessionStatuses } from "../src/state/sessions";--const listSessions = vi.mocked(api.listSessions);--const NO_ROWS: SessionsResponse = { sessions: [] };-const COUNTS = { active: 1, subagent: 1, schedule: 0, benchmark: 0, archived: 0 };--function session(sessionId: string, over: Partial<SessionInfo> = {}): SessionInfo {- return {- sessionId,- projectId: "proj",- agentId: "default_agent",- provider: "anthropic",- modelId: "claude-sonnet-4",- workspace: "/w",- approvalMode: "allow-all",- sandbox: { mode: "danger-full-access", network: "open" },- createdAt: "2026-09-16T09:00:00.000Z",- lastActiveAt: "2026-09-16T09:00:00.000Z",- status: "idle",- pendingApprovalCount: 0,- pendingFollowUpCount: 0,- hasTrace: true,- archived: false,- ...over,- };-}--const stateEvent = (sessionId: string, state: "running" | "idle"): ServerEvent => ({- type: "session_state",- sessionId,- state,- lastActiveAt: "2026-09-16T09:05:00.000Z",- hasTrace: true,-});--beforeEach(() => {- listSessions.mockReset();-});--describe("the list fetches the user's own rows only", () => {- it("reload() asks the server to leave the organizations' rows out of the page and the totals", async () => {- listSessions.mockResolvedValue({ ...NO_ROWS, counts: COUNTS });- const store = createSessionsStore();- store.setState({ projectId: "proj", agentIds: ["default_agent", "acme_dev"] });- await store.getState().reload();- expect(listSessions).toHaveBeenCalledTimes(2);- for (const call of listSessions.mock.calls) {- expect(call[0]).toBe("proj");- expect(call[2]).toMatchObject({ category: "active", withCounts: true, excludeOrg: true });- }- });-- it("loadMoreFor() pages a folder down the same own-rows stream", async () => {- listSessions.mockResolvedValue({ ...NO_ROWS, counts: COUNTS });- const store = createSessionsStore();- store.setState({ projectId: "proj", agentIds: ["default_agent"] });- await store.getState().reload();- listSessions.mockClear();- listSessions.mockResolvedValue(NO_ROWS);- await store.getState().loadMoreFor(["default_agent"], "subagent");- expect(listSessions).toHaveBeenCalledTimes(1);- expect(listSessions.mock.calls[0]![2]).toMatchObject({- category: "subagent",- excludeOrg: true,- });- });-});--describe("an organization row that enters by another door", () => {- /** A store whose one loaded pair is complete, so an added own row would count. */- async function loadedStore() {- listSessions.mockResolvedValue({- sessions: [session("own")],- counts: COUNTS,- workspaceCounts: { "/w": COUNTS },- workspaceLatest: { "/w": "2026-09-16T09:00:00.000Z" },- });- const store = createSessionsStore();- store.setState({ projectId: "proj", agentIds: ["default_agent"] });- await store.getState().reload();- return store;- }-- it("is held for the page that asked for it but never moves the server's own-only totals", async () => {- const store = await loadedStore();- const desk = session("s-desk", { client: "org", orgId: "acme" });- store.getState().add(desk);- expect(store.getState().sessions.map((s) => s.sessionId)).toEqual(["s-desk", "own"]);- expect(store.getState().countsByAgent.get("default_agent")?.active).toBe(1);- expect(store.getState().workspaceCountsByAgent.get("default_agent")?.["/w"]?.active).toBe(1);- store.getState().remove("s-desk");- expect(store.getState().countsByAgent.get("default_agent")?.active).toBe(1);- });-- it("an own row added under the same conditions still counts (the rule is about organization rows)", async () => {- const store = await loadedStore();- store.getState().add(session("own-2"));- expect(store.getState().countsByAgent.get("default_agent")?.active).toBe(2);- });-- it("survives a reload, which can never fetch it back for the page showing it", async () => {- const store = await loadedStore();- store.getState().add(session("s-desk", { client: "org", orgId: "acme" }));- await store.getState().reload();- expect(store.getState().sessions.map((s) => s.sessionId)).toEqual(["own", "s-desk"]);- expect(store.getState().countsByAgent.get("default_agent")?.active).toBe(1);- });-});--describe("live statuses outlive the rows", () => {- it("remembers a session_state for a Session no loaded page holds, without inventing a row", () => {- const store = createSessionsStore();- store.setState({ projectId: "proj", agentIds: ["default_agent"], sessions: [session("own")] });- applyUserEvent(store, stateEvent("s-desk", "running"), () => undefined);- const state = store.getState();- expect(state.sessions.map((s) => s.sessionId)).toEqual(["own"]);- expect(liveSessionStatuses(state.sessions, state.liveStatuses).get("s-desk")).toBe("running");- // The run ending is the fact no other channel reports: it must be kept, not dropped as- // "nothing to draw".- applyUserEvent(store, stateEvent("s-desk", "idle"), () => undefined);- const after = store.getState();- expect(liveSessionStatuses(after.sessions, after.liveStatuses).get("s-desk")).toBe("idle");- });-- it("a loaded row's own status wins over an older remembered one", () => {- const store = createSessionsStore();- store.setState({ projectId: "proj", agentIds: ["default_agent"], sessions: [] });- applyUserEvent(store, stateEvent("own", "running"), () => undefined);- // A list fetch that landed after the event carries the row as it stands now.- store.setState({ sessions: [session("own", { status: "idle" })] });- const state = store.getState();- expect(liveSessionStatuses(state.sessions, state.liveStatuses).get("own")).toBe("idle");- });-- it("a resync forgets them: the flip that ended a run may be among the ones it lost", () => {- const store = createSessionsStore();- store.setState({- projectId: "proj",- agentIds: ["default_agent"],- reload: vi.fn(() => Promise.resolve()),- });- applyUserEvent(store, stateEvent("s-desk", "running"), () => undefined);- applyUserEvent(store, { type: "resync_required" }, () => undefined);- const state = store.getState();- expect(state.liveStatuses.has("s-desk")).toBe(false);- expect(liveSessionStatuses(state.sessions, state.liveStatuses).has("s-desk")).toBe(false);- });-- it("an organization row held for its page does not stand in for them", () => {- const store = createSessionsStore();- store.setState({- projectId: "proj",- agentIds: ["default_agent"],- reload: vi.fn(() => Promise.resolve()),- });- // The desk the chat page opened while it ran: no list fetch ever refreshes this row, so- // after a resync its status is as stale as the forgotten entry.- store.getState().add(session("s-desk", { client: "org", orgId: "acme", status: "running" }));- applyUserEvent(store, { type: "resync_required" }, () => undefined);- const state = store.getState();- expect(state.sessions.map((s) => s.sessionId)).toEqual(["s-desk"]);- expect(liveSessionStatuses(state.sessions, state.liveStatuses).has("s-desk")).toBe(false);- });-});diff --git a/packages/web/test/sessions-store.test.ts b/packages/web/test/sessions-store.test.tsnew file mode 100644index 00000000..76656d2e--- /dev/null+++ b/packages/web/test/sessions-store.test.ts@@ -0,0 +1,421 @@+/**+ * The sessions store's list (state/sessions.tsx), driven through the real `listSessions`+ * wrapper against the fetch fake: each server pages its own rows, counts are summed, and a+ * source that could not answer is never read as a source that answered nothing.+ *+ * Loading:+ * - A fresh store is loading, and a reload with no Agent set does not claim to be done.+ * - A refresh over rows already on screen does not raise loading.+ *+ * Several machines:+ * - Every source is merged newest first, each row remembers the machine it lives on, the+ * counts are summed, and what a machine answered is cached for the next restart.+ * - A machine is asked about its own Agents too, and this server only about its own.+ * - One Agent this server cannot answer about keeps its rows and counts; the rest refresh.+ * - A 404 from a machine is an answer: its rows go and its cache is cleared.+ * - A machine that could not answer keeps its cached rows and its cache; counts come only+ * from servers that answered.+ * - This server not answering abandons the reload: the rows stand and loading stays clear.+ * - Two machines' counts for one path stay apart.+ * - A group's next page is asked only of the machine the group is on, by path.+ *+ * The user's own rows only:+ * - Every fetch, a reload or a folder's next page, asks the server to leave the+ * organizations' rows out of the page and the totals.+ * - An organization row that enters by another door is held for its page, survives reloads,+ * and never moves the own-only totals; an own row added the same way still counts.+ *+ * Live statuses:+ * - A session_state for a Session no loaded page holds is remembered without inventing a+ * row, the run's end included; a loaded row's own status wins over an older remembered one.+ * - A resync forgets the remembered statuses, and a held organization row does not stand in+ * for them.+ *+ * Events from a machine:+ * - A session_created for this Project reloads wherever it happened; another Project's never.+ */+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { ServerEvent, SessionInfo, SessionsResponse } from "@prismshadow/penguin-server/api";+import { applyUserEvent, createSessionsStore, liveSessionStatuses } from "../src/state/sessions";+import { forgetSessionMachines, machineForSession } from "../src/lib/session-machines";+import { cachedMachineSessions, rememberMachineSessions } from "../src/lib/machine-cache";+import { apiError, json, stubFetch } from "./helpers/fetch";+import type { FakeFetch } from "./helpers/fetch";+import { stubLocalStorage } from "./helpers/storage";++/** A server's answer for one Agent: its list, or an HTTP failure. */+type Answer = SessionsResponse | { status: number; code: string };+/** What each (machine, Agent) answers; a missing entry is a server that cannot be reached. */+const answers = new Map<string, Answer>();+const key = (machineId: string | null, agentId: string) => `${machineId ?? ""}|${agentId}`;+let fetch: FakeFetch;++beforeEach(() => {+ answers.clear();+ stubLocalStorage();+ fetch = stubFetch((request) => {+ const agentId = /\/agents\/([^/]+)\/sessions$/.exec(request.path)?.[1] ?? "";+ const answer = answers.get(key(request.machine, decodeURIComponent(agentId)));+ if (answer === undefined) throw new TypeError("fetch failed");+ return "status" in answer ? apiError(answer.status, answer.code) : json(answer);+ });+});++afterEach(() => forgetSessionMachines());++/** Which servers were asked, and for which Workspace group. */+const asked = () =>+ fetch.requests.map((r) => ({+ machineId: r.machine,+ ...(r.query.has("workspaceGroup") ? { workspaceGroup: r.query.get("workspaceGroup") } : {}),+ }));++function session(sessionId: string, over: Partial<SessionInfo> = {}): SessionInfo {+ return {+ sessionId,+ projectId: "p",+ agentId: "a1",+ provider: "anthropic",+ modelId: "claude-sonnet-4",+ workspace: "/w",+ approvalMode: "allow-all",+ sandbox: { mode: "danger-full-access", network: "open" },+ createdAt: "2026-09-16T09:00:00.000Z",+ lastActiveAt: "2026-09-16T09:00:00.000Z",+ status: "idle",+ pendingApprovalCount: 0,+ pendingFollowUpCount: 0,+ hasTrace: true,+ archived: false,+ ...over,+ };+}++const row = (sessionId: string, createdAt: string, agentId = "a1") =>+ session(sessionId, { agentId, createdAt, lastActiveAt: createdAt });++const COUNTS = { active: 1, subagent: 1, schedule: 0, benchmark: 0, archived: 0 };++const page = (+ sessions: SessionInfo[],+ active: number,+ workspaceCounts?: Record<string, { active: number }>,+): SessionsResponse =>+ ({+ sessions,+ counts: { active, subagent: 0, schedule: 0, benchmark: 0, archived: 0 },+ ...(workspaceCounts === undefined ? {} : { workspaceCounts }),+ }) as SessionsResponse;++function boot(machineIds: string[] = [], offlineMachineIds: string[] = [], agentIds = ["a1"]) {+ const store = createSessionsStore();+ store.setState({ projectId: "p", agentIds, machineIds, offlineMachineIds });+ return store;+}++const ids = (store: ReturnType<typeof boot>) => store.getState().sessions.map((s) => s.sessionId);++describe("loading", () => {+ it("a fresh store is loading, and a reload with no Agent set does not claim to be done", async () => {+ const store = createSessionsStore();+ expect(store.getState().loading).toBe(true);+ store.setState({ projectId: "p", agentIds: [] });+ await store.getState().reload();+ // Nothing was fetched, so nothing may report "loaded": clearing here painted an empty+ // state over a list that was merely not known yet.+ expect(store.getState().loading).toBe(true);+ expect(fetch.requests).toEqual([]);+ });++ it("a refresh over rows already on screen does not raise loading", async () => {+ answers.set(key(null, "a1"), page([row("here", "2026-01-02T00:00:00Z")], 1));+ const store = boot();+ await store.getState().reload();+ let raised = false;+ const unsubscribe = store.subscribe((state) => {+ if (state.loading) raised = true;+ });+ await store.getState().reload();+ unsubscribe();+ expect(raised).toBe(false);+ });+});++describe("the list across machines", () => {+ it("merges every source newest-first, records where each row lives, and sums the counts", async () => {+ answers.set(key(null, "a1"), page([row("here", "2026-01-02T00:00:00Z")], 1));+ answers.set(key("M1", "a1"), page([row("there", "2026-01-03T00:00:00Z")], 2));+ const store = boot(["M1"]);+ await store.getState().reload();+ const { countsByAgent, loading } = store.getState();+ expect(ids(store)).toEqual(["there", "here"]);+ expect(machineForSession("there")).toBe("M1");+ expect(machineForSession("here")).toBeNull();+ expect(countsByAgent.get("a1")?.active).toBe(3);+ expect(loading).toBe(false);+ // What the machine answered is remembered for the next restart.+ expect(cachedMachineSessions("p", "M1").map((s) => s.sessionId)).toEqual(["there"]);+ });++ it("asks a machine about ITS Agents too — an Agent that exists only there", async () => {+ // A new chat started from a machine's Agent card belongs to an Agent this server has+ // never heard of: asked only about this Project's Agents, the machine answers nothing+ // about it, the row vanishes on the next reload, and with it the record of where it lives.+ answers.set(key(null, "a1"), page([row("here", "2026-01-02T00:00:00Z")], 1));+ answers.set(key("M1", "a1"), { status: 404, code: "not_found" });+ answers.set(+ key("M1", "theirs"),+ page([row("over-there", "2026-01-03T00:00:00Z", "theirs")], 1),+ );+ const store = boot(["M1"]);+ store.setState({ agentIdsByMachine: { M1: ["theirs"] } });+ await store.getState().reload();+ expect(ids(store)).toEqual(["over-there", "here"]);+ expect(machineForSession("over-there")).toBe("M1");+ // And this server is never asked about an Agent that is not its own.+ expect(asked().filter((a) => a.machineId === null)).toHaveLength(1);+ });++ it("one Agent this server cannot answer about keeps its rows; the rest still refresh", async () => {+ answers.set(key(null, "a1"), page([row("a1-row", "2026-01-02T00:00:00Z")], 1));+ answers.set(key(null, "a2"), page([row("a2-row", "2026-01-01T00:00:00Z", "a2")], 1));+ const store = boot([], [], ["a1", "a2"]);+ await store.getState().reload();+ expect(ids(store)).toEqual(["a1-row", "a2-row"]);++ // a2's index is damaged and its list 500s, while a1 answers as before. Erasing a2 would+ // read as an Agent with no conversations; abandoning the whole reload would leave the+ // page on a skeleton nothing clears.+ answers.set(key(null, "a2"), { status: 500, code: "internal" });+ answers.set(+ key(null, "a1"),+ page([row("a1-row", "2026-01-02T00:00:00Z"), row("a1-new", "2026-01-04T00:00:00Z")], 2),+ );+ await store.getState().reload();+ expect(ids(store)).toEqual(["a1-new", "a1-row", "a2-row"]);+ expect(store.getState().countsByAgent.get("a1")?.active).toBe(2);+ // Kept as last read: a total without this server's share would contradict the row below it.+ expect(store.getState().countsByAgent.get("a2")?.active).toBe(1);+ expect(store.getState().loading).toBe(false);+ });++ it("a server that has not got the Agent answered — 404 is an answer, and its cache is cleared", async () => {+ answers.set(key(null, "a1"), page([row("here", "2026-01-02T00:00:00Z")], 1));+ answers.set(key("M1", "a1"), { status: 404, code: "not_found" });+ rememberMachineSessions("p", "M1", [row("stale", "2026-01-01T00:00:00Z")]);+ const store = boot(["M1"]);+ await store.getState().reload();+ expect(ids(store)).toEqual(["here"]);+ expect(cachedMachineSessions("p", "M1")).toEqual([]);+ });++ it("a machine that could not answer keeps its cached rows on screen and its cache intact", async () => {+ answers.set(key(null, "a1"), page([row("here", "2026-01-02T00:00:00Z")], 1));+ // M1 is held but its server does not answer; M2 has no connection at all.+ rememberMachineSessions("p", "M1", [row("m1-cached", "2026-01-01T00:00:00Z")]);+ rememberMachineSessions("p", "M2", [row("m2-cached", "2026-01-04T00:00:00Z")]);+ const store = boot(["M1"], ["M2"]);+ await store.getState().reload();+ expect(ids(store)).toEqual(["m2-cached", "here", "m1-cached"]);+ expect(machineForSession("m2-cached")).toBe("M2");+ expect(cachedMachineSessions("p", "M1").map((s) => s.sessionId)).toEqual(["m1-cached"]);+ // Counts come only from servers that answered: the cache makes no claim about now.+ expect(store.getState().countsByAgent.get("a1")?.active).toBe(1);+ });++ it("this server not answering abandons the reload: the rows stand and loading is left alone", async () => {+ answers.set(key(null, "a1"), page([row("here", "2026-01-02T00:00:00Z")], 1));+ const store = boot();+ await store.getState().reload();+ expect(ids(store)).toEqual(["here"]);+ expect(store.getState().loading).toBe(false);++ answers.delete(key(null, "a1")); // mid-swap: nothing answers here+ await store.getState().reload();+ expect(ids(store)).toEqual(["here"]);+ expect(store.getState().loading).toBe(false);+ });++ it("keeps two machines' counts for one path apart — a badge is about a directory, not a string", async () => {+ // `/w` on this server and `/w` on M1 are two different directories, and each folder's+ // badge has to match the rows under it.+ answers.set(+ key(null, "a1"),+ page([row("here", "2026-01-02T00:00:00Z")], 1, { "/w": { active: 2 } }),+ );+ answers.set(+ key("M1", "a1"),+ page([row("there", "2026-01-03T00:00:00Z")], 1, { "/w": { active: 5 } }),+ );+ const store = boot(["M1"]);+ await store.getState().reload();+ const byGroup = store.getState().workspaceCountsByAgent.get("a1");+ expect(byGroup?.["/w"]?.active).toBe(2);+ expect(byGroup?.[`M1\u0000/w`]?.active).toBe(5);+ });++ it("a group's page is asked only of the machine that group is on, by path", async () => {+ answers.set(key(null, "a1"), page([row("here", "2026-01-02T00:00:00Z")], 1));+ answers.set(key("M1", "a1"), page([row("there", "2026-01-03T00:00:00Z")], 1));+ const store = boot(["M1"]);+ await store.getState().reload();++ fetch.requests.length = 0;+ await store.getState().loadMoreFor(["a1"], "active", `M1\u0000/w`);+ // `/w` exists on this server too: asking it would page another directory's rows into+ // this group. The machine half never travels in the query.+ expect(asked()).toEqual([{ machineId: "M1", workspaceGroup: "/w" }]);++ fetch.requests.length = 0;+ await store.getState().loadMoreFor(["a1"], "active", "/w");+ expect(asked()).toEqual([{ machineId: null, workspaceGroup: "/w" }]);+ });+});++describe("the list fetches the user's own rows only", () => {+ it("reload() asks the server to leave the organizations' rows out of the page and the totals", async () => {+ answers.set(key(null, "default_agent"), { sessions: [], counts: COUNTS });+ answers.set(key(null, "acme_dev"), { sessions: [], counts: COUNTS });+ await boot([], [], ["default_agent", "acme_dev"]).getState().reload();+ expect(fetch.requests.map((r) => r.path)).toEqual([+ "/api/projects/p/agents/default_agent/sessions",+ "/api/projects/p/agents/acme_dev/sessions",+ ]);+ for (const { query } of fetch.requests) {+ expect(query.get("category")).toBe("active");+ expect(query.get("counts")).toBe("1");+ expect(query.get("excludeOrg")).toBe("1");+ }+ });++ it("loadMoreFor() pages a folder down the same own-rows stream", async () => {+ answers.set(key(null, "a1"), { sessions: [], counts: COUNTS });+ const store = boot();+ await store.getState().reload();+ fetch.requests.length = 0;+ await store.getState().loadMoreFor(["a1"], "subagent");+ expect(fetch.requests).toHaveLength(1);+ expect(fetch.requests[0]!.query.get("category")).toBe("subagent");+ expect(fetch.requests[0]!.query.get("excludeOrg")).toBe("1");+ });+});++describe("an organization row that enters by another door", () => {+ /** A store whose one loaded pair is complete, so an added own row would count. */+ async function loadedStore() {+ answers.set(key(null, "a1"), {+ sessions: [session("own")],+ counts: COUNTS,+ workspaceCounts: { "/w": COUNTS },+ workspaceLatest: { "/w": "2026-09-16T09:00:00.000Z" },+ });+ const store = boot();+ await store.getState().reload();+ return store;+ }++ it("is held for the page that asked for it but never moves the server's own-only totals", async () => {+ const store = await loadedStore();+ store.getState().add(session("s-desk", { client: "org", orgId: "acme" }));+ expect(ids(store)).toEqual(["s-desk", "own"]);+ expect(store.getState().countsByAgent.get("a1")?.active).toBe(1);+ expect(store.getState().workspaceCountsByAgent.get("a1")?.["/w"]?.active).toBe(1);+ store.getState().remove("s-desk");+ expect(store.getState().countsByAgent.get("a1")?.active).toBe(1);+ });++ it("an own row added under the same conditions still counts (the rule is about organization rows)", async () => {+ const store = await loadedStore();+ store.getState().add(session("own-2"));+ expect(store.getState().countsByAgent.get("a1")?.active).toBe(2);+ });++ it("survives a reload, which can never fetch it back for the page showing it", async () => {+ const store = await loadedStore();+ store.getState().add(session("s-desk", { client: "org", orgId: "acme" }));+ await store.getState().reload();+ expect(ids(store)).toEqual(["own", "s-desk"]);+ expect(store.getState().countsByAgent.get("a1")?.active).toBe(1);+ });+});++describe("live statuses outlive the rows", () => {+ const stateEvent = (sessionId: string, state: "running" | "idle"): ServerEvent => ({+ type: "session_state",+ sessionId,+ state,+ lastActiveAt: "2026-09-16T09:05:00.000Z",+ hasTrace: true,+ });+ const live = (store: ReturnType<typeof boot>) =>+ liveSessionStatuses(store.getState().sessions, store.getState().liveStatuses);++ it("remembers a session_state for a Session no loaded page holds, without inventing a row", () => {+ const store = boot();+ store.setState({ sessions: [session("own")] });+ applyUserEvent(store, stateEvent("s-desk", "running"), () => undefined);+ expect(ids(store)).toEqual(["own"]);+ expect(live(store).get("s-desk")).toBe("running");+ // The run ending is the fact no other channel reports: it must be kept, not dropped as+ // "nothing to draw".+ applyUserEvent(store, stateEvent("s-desk", "idle"), () => undefined);+ expect(live(store).get("s-desk")).toBe("idle");+ });++ it("a loaded row's own status wins over an older remembered one", () => {+ const store = boot();+ store.setState({ sessions: [] });+ applyUserEvent(store, stateEvent("own", "running"), () => undefined);+ // A list fetch that landed after the event carries the row as it stands now.+ store.setState({ sessions: [session("own", { status: "idle" })] });+ expect(live(store).get("own")).toBe("idle");+ });++ it("a resync forgets them: the flip that ended a run may be among the ones it lost", () => {+ const store = boot();+ store.setState({ reload: vi.fn(() => Promise.resolve()) });+ applyUserEvent(store, stateEvent("s-desk", "running"), () => undefined);+ applyUserEvent(store, { type: "resync_required" }, () => undefined);+ expect(store.getState().liveStatuses.has("s-desk")).toBe(false);+ expect(live(store).has("s-desk")).toBe(false);+ });++ it("an organization row held for its page does not stand in for them", () => {+ const store = boot();+ store.setState({ reload: vi.fn(() => Promise.resolve()) });+ // The desk the chat page opened while it ran: no list fetch ever refreshes this row, so+ // after a resync its status is as stale as the forgotten entry.+ store.getState().add(session("s-desk", { client: "org", orgId: "acme", status: "running" }));+ applyUserEvent(store, { type: "resync_required" }, () => undefined);+ expect(ids(store)).toEqual(["s-desk"]);+ expect(live(store).has("s-desk")).toBe(false);+ });+});++/**+ * A machine's Projects carry THIS server's ids (installing one creates the same Project over+ * there), so the id in an event is as meaningful from a machine as from here.+ */+describe("events arriving from a machine", () => {+ const created = (projectId: string): ServerEvent =>+ ({ type: "session_created", projectId, agentId: "a1", sessionId: "s1" }) as ServerEvent;++ it.each([+ ["p", 2],+ ["other", 0],+ ])(+ "a session_created in Project %s reloads the list %i times, from a machine or here",+ (projectId, reloads) => {+ const store = boot();+ let count = 0;+ store.setState({+ reload: async () => {+ count += 1;+ },+ });+ applyUserEvent(store, created(projectId), () => undefined, "M1");+ applyUserEvent(store, created(projectId), () => undefined, null);+ expect(count).toBe(reloads);+ },+ );+});diff --git a/packages/web/test/settings-sections.test.ts b/packages/web/test/settings-sections.test.tsindex 29ef809f..4ed0153f 100644--- a/packages/web/test/settings-sections.test.ts+++ b/packages/web/test/settings-sections.test.ts@@ -1,22 +1,17 @@/**- * settings-sections.ts unit tests: which Settings pages each viewer gets.+ * Which Settings pages each viewer gets (lib/settings-sections.ts), pinned by value: a rail+ * showing a forbidden entry leaks that the setting exists, and a page rendered without the same+ * filter hands a non-admin the form. The admin APIs answer a non-admin with 403 either way; this+ * filter is convenience, not the boundary.*- * The rule is pinned by value rather than by shape because both halves of it can fail- * silently and separately: a rail that shows a forbidden entry leaks that the setting- * exists, and an active page rendered without the same filter hands a non-admin the form- * itself. Both go through these functions, so both are covered here.- *- * The client filter is convenience, not the boundary — the admin APIs answer a non-admin- * with 403 either way (server/test/admin-settings.test.ts, "non-admin access is always- * 403").- *- * vitest runs node-only here (`environment: "node"`, no jsdom), so this asserts against- * the exported functions and, for the dialog's use of them, its source- * (account-menu.test.ts convention).+ * - A web admin gets every page in rail order; a non-admin only their own pages, nothing+ * server-global; the desktop shell's window drops the account page and user management; a+ * password session against a desktop-mode server keeps the account page.+ * - The rail lists an admin's groups once each, in page order, and a single group when only+ * one remains (its cue to draw no heading).+ * - A requested page passes through when the viewer may open it; a forbidden or unknown page,+ * or none, falls back to the first visible page; nothing visible resolves to nothing.*/-import { readFileSync } from "node:fs";-import { dirname, resolve } from "node:path";-import { fileURLToPath } from "node:url";import { describe, expect, it } from "vitest";import {resolveSettingsSection,@@ -152,42 +147,3 @@ describe("resolveSettingsSection", () => {expect(resolveSettingsSection("general", [])).toBe(null);});});--describe("the Settings dialog", () => {- const source = readFileSync(- resolve(- dirname(fileURLToPath(import.meta.url)),- "../src/features/settings/settings-dialog.tsx",- ),- "utf8",- );-- it("builds its rail from the filtered list rather than the full one", () => {- // Without this the functions above could pass every test while the dialog mapped over- // the raw registry and rendered the admin rows to everyone.- expect(source).toContain("visibleSettingsSections({");- expect(source).not.toContain("SECTION_RULES");- });-- it("renders the credits page, which lists the bundled fonts and nothing before them", () => {- // MiSans's licence asks the app to credit it wherever it runs, so the page is visible to- // every viewer (pinned above); the list is the whole page.- expect(source).toContain('{current === "credits" && <CreditsSection />}');- const credits = readFileSync(- resolve(- dirname(fileURLToPath(import.meta.url)),- "../src/features/settings/credits-section.tsx",- ),- "utf8",- );- expect(credits).not.toContain("S.settings.fontCredit");- expect(credits).toContain("FONT_CREDITS.map");- expect(credits).toContain("aria-controls={panelId}");- });-- it("resolves the page it renders through the same gate on every render", () => {- // The active page is a state value, not a right: a viewer who loses admin mid-dialog- // must fall back to their own first page rather than keep rendering the admin form.- expect(source).toContain("resolveSettingsSection(active, sections)");- });-});diff --git a/packages/web/test/shell-org-status.test.ts b/packages/web/test/shell-org-status.test.tsindex a9877965..9ec4006c 100644--- a/packages/web/test/shell-org-status.test.ts+++ b/packages/web/test/shell-org-status.test.ts@@ -1,14 +1,13 @@/**- * The shell's organization status marks (features/company/shell-org-status.ts): which state- * an organization headlines and its tone, and what a session-list group renders so a failed- * fetch never leaves a skeleton behind.+ * The shell's organization status marks (features/company/shell-org-status.ts).+ *+ * - An organization headlines invalid configuration above paused, and paused above active.+ * - A session-list group shows its skeleton only until a fetch completes, then the error line+ * when the fetch completed without it, else its list or its empty line, so a failed fetch+ * never leaves a skeleton behind.*/import { describe, expect, it } from "vitest";-import {- ORG_STATUS_TONE,- groupRender,- orgStatusKind,-} from "../src/features/company/shell-org-status";+import { groupRender, orgStatusKind } from "../src/features/company/shell-org-status";describe("orgStatusKind", () => {it("ranks invalid configuration above paused, and paused above active", () => {@@ -17,10 +16,6 @@ describe("orgStatusKind", () => {expect(orgStatusKind({ status: "paused", invalid: "bad chart" })).toBe("invalid");expect(orgStatusKind({ status: "active", invalid: "bad chart" })).toBe("invalid");});-- it("maps the three states to danger, attention and success", () => {- expect(ORG_STATUS_TONE).toEqual({ invalid: "danger", paused: "attention", active: "success" });- });});describe("groupRender", () => {diff --git a/packages/web/test/shortcuts-section.test.ts b/packages/web/test/shortcuts-section.test.tsindex 8c9e204e..f61e87a0 100644--- a/packages/web/test/shortcuts-section.test.ts+++ b/packages/web/test/shortcuts-section.test.ts@@ -1,10 +1,15 @@/**- * The Shortcuts settings page (src/features/settings/shortcuts-section.tsx) rendered to static- * markup against an injected keymap: groups and rows in both dictionaries with no rule between- * rows, the chord text per platform, the reset affordance only on an overridden row, the- * browser's notes on either host (a reserved chord in the attention tone, a shared one muted),- * the desktop menu's note in the desktop app, a note that follows a new binding at once, and a- * conflict hint in the attention tone.+ * The Shortcuts settings page (features/settings/shortcuts-section.tsx), rendered to static+ * markup against an injected keymap.+ *+ * - Every command is listed under its group, in either language.+ * - A chord is drawn the way the platform writes it.+ * - A row can be reset only when overridden, and "Reset all" is enabled only when something is.+ * - No default sits on a chord the browser keeps; a binding on one is marked in the attention+ * tone on either host. A chord the browser also uses gets a muted note, and in the desktop+ * app the desktop menu's claim is named first. A note follows a new binding at once.+ * - A command shadowing a global one is named in the attention tone, and a same-scope clash+ * is reported on both rows.*/import { afterEach, beforeEach, describe, expect, it } from "vitest";import { createElement } from "react";@@ -19,19 +24,13 @@ import {KEYBINDINGS_KEY,configureKeybindingsStoreForTests,setBinding,- type KeybindingsStorage,} from "../src/lib/shortcuts/store";import { toneInk } from "../src/lib/tone";+import { memoryStorage } from "./helpers/storage";-function memStorage(doc?: object): KeybindingsStorage {- const map = new Map<string, string>();- if (doc !== undefined) map.set(KEYBINDINGS_KEY, JSON.stringify(doc));- return {- getItem: (k) => map.get(k) ?? null,- setItem: (k, v) => void map.set(k, v),- removeItem: (k) => void map.delete(k),- };-}+/** A keybindings mirror holding `doc`, or nothing. */+const keybindings = (doc?: object) =>+ memoryStorage(doc === undefined ? {} : { [KEYBINDINGS_KEY]: JSON.stringify(doc) });const render = (): string => renderToStaticMarkup(createElement(ShortcutsSection));const count = (html: string, needle: string): number => html.split(needle).length - 1;@@ -39,7 +38,7 @@ const count = (html: string, needle: string): number => html.split(needle).lengtbeforeEach(() => {setPlatformForTests("linux");setHostForTests("browser");- configureKeybindingsStoreForTests({ storage: memStorage(), layout: null });+ configureKeybindingsStoreForTests({ storage: keybindings(), layout: null });});afterEach(() => {@@ -61,10 +60,6 @@ describe("ShortcutsSection", () => {}});- it("lists the rows without a rule between them", () => {- expect(render()).not.toContain("divide-y");- });-it("draws the chord the platform writes", () => {const linux = render();expect(linux).toContain("<kbd>Ctrl</kbd>");@@ -82,21 +77,22 @@ describe("ShortcutsSection", () => {it("offers the per-row reset only on an overridden row, and Reset all only when something is", () => {const clean = render();expect(count(clean, `data-tooltip="${S.shortcuts.resetRow}"`)).toBe(0);- expect(clean).toMatch(/<button[^>]* disabled=""[^>]*>[^<]*全部恢复默认/);+ const resetAll = new RegExp(`<button[^>]* disabled=""[^>]*>[^<]*${S.shortcuts.resetAll}`);+ expect(clean).toMatch(resetAll);configureKeybindingsStoreForTests({- storage: memStorage({ v: 1, linux: { "editor.save": null } }),+ storage: keybindings({ v: 1, linux: { "editor.save": null } }),});const one = render();expect(count(one, `data-tooltip="${S.shortcuts.resetRow}"`)).toBe(1);expect(one).toContain(S.shortcuts.unbound);- expect(one).not.toMatch(/<button[^>]* disabled=""[^>]*>[^<]*全部恢复默认/);+ expect(one).not.toMatch(resetAll);});it("puts no default on a chord the browser keeps, and marks a binding on one in the attention tone on either host", () => {expect(render()).not.toContain(S.shortcuts.browserReserved);configureKeybindingsStoreForTests({- storage: memStorage({ v: 1, linux: { "terminal.close": "Mod+KeyW" } }),+ storage: keybindings({ v: 1, linux: { "terminal.close": "Mod+KeyW" } }),});for (const host of ["browser", "desktop"] as const) {setHostForTests(host);@@ -110,7 +106,7 @@ describe("ShortcutsSection", () => {// Save's default takes over the browser's Save Page; no other default touches the browser.expect(count(render(), S.shortcuts.browserCommon)).toBe(1);configureKeybindingsStoreForTests({- storage: memStorage({ v: 1, linux: { "palette.toggle": "Mod+KeyR" } }),+ storage: keybindings({ v: 1, linux: { "palette.toggle": "Mod+KeyR" } }),});const browser = render();expect(count(browser, S.shortcuts.browserCommon)).toBe(2);@@ -130,7 +126,7 @@ describe("ShortcutsSection", () => {it("says which command shadows a global one, in the attention tone", () => {configureKeybindingsStoreForTests({- storage: memStorage({ v: 1, linux: { "palette.toggle": "Ctrl+Alt+Backquote" } }),+ storage: keybindings({ v: 1, linux: { "palette.toggle": "Ctrl+Alt+Backquote" } }),});const html = render();expect(@@ -147,7 +143,7 @@ describe("ShortcutsSection", () => {it("reports a same-scope clash on both rows", () => {configureKeybindingsStoreForTests({- storage: memStorage({ v: 1, linux: { "palette.toggle": "Ctrl+Backquote" } }),+ storage: keybindings({ v: 1, linux: { "palette.toggle": "Ctrl+Backquote" } }),});const html = render();expect(html).toContain(S.shortcuts.conflictSame(S.shortcuts.commands["terminal.toggle"]));diff --git a/packages/web/test/shortcuts-store.test.ts b/packages/web/test/shortcuts-store.test.tsindex 4fd05e37..23bd1875 100644--- a/packages/web/test/shortcuts-store.test.ts+++ b/packages/web/test/shortcuts-store.test.ts@@ -1,7 +1,21 @@/**- * The keymap store (src/lib/shortcuts/store.ts) over an in-memory mirror: overrides resolve- * over the defaults, an explicit null unbinds, unknown ids ride along, malformed input reads as- * defaults, a row set back to its default disappears, and an external change re-reads.+ * The keymap store (lib/shortcuts/store.ts) over an in-memory localStorage mirror.+ *+ * - The keymap starts from the platform's registry defaults; the platform's stored section+ * overlays them, an explicit null unbinds, and an unknown id or unparseable chord keeps the+ * default.+ * - Malformed JSON, a foreign shape or a wrong version reads as no overrides; the document is+ * sanitized to the three platform sections of string-or-null values.+ * - A write stores the override in the platform's section and notifies subscribers; an unbind+ * is stored as null; a row set back to its default is removed (an emptied section with it);+ * unknown ids and other platforms' sections survive; a literal Ctrl chord is Mod on Linux;+ * Reset all clears the current platform only.+ * - Another tab's write to the mirror is re-read (only for its own key); defaults move to the+ * keys the keyboard layout types.+ * - The account's copy: every edit goes to the persister as the compact document; the server's+ * document wins over the mirror; a mirror edited here is kept when the server has none;+ * one account's edit never reaches the next account on the tab; a mirror the server does not+ * know and this session did not write is cleared.*/import { afterEach, beforeEach, describe, expect, it } from "vitest";import { parseChord } from "../src/lib/shortcuts/chord";@@ -22,26 +36,14 @@ import {setBinding,setKeybindingsPersister,subscribeKeymap,- type KeybindingsStorage,} from "../src/lib/shortcuts/store";import type { StoredKeybindings } from "../src/lib/shortcuts/types";+import { memoryStorage } from "./helpers/storage";-function memStorage(- initial: Record<string, string> = {},-): KeybindingsStorage & { map: Map<string, string> } {- const map = new Map(Object.entries(initial));- return {- map,- getItem: (k) => map.get(k) ?? null,- setItem: (k, v) => void map.set(k, v),- removeItem: (k) => void map.delete(k),- };-}--let storage = memStorage();+let storage = memoryStorage();beforeEach(() => {- storage = memStorage();+ storage = memoryStorage();setPlatformForTests("linux");configureKeybindingsStoreForTests({ storage, layout: null });});diff --git a/packages/web/test/skill-slash.test.ts b/packages/web/test/skill-slash.test.tsindex f42656b4..2d57c66d 100644--- a/packages/web/test/skill-slash.test.ts+++ b/packages/web/test/skill-slash.test.ts@@ -1,16 +1,16 @@/**- * Skill UI-language text and slash command assembly (pure functions shared by- * chat-input and the skill library page):- * - localizedText: uses the Chinese value when locale is zh and it's non-empty, otherwise- * falls back to English (an empty-string Chinese value counts as missing);- * - localizedShortText: prefers the short description (language takes priority over- * length), falling back to the full description when missing;- * - skillSlashItems: installed skills -> `/<skill_name>` command items, preferring the- * short description in the UI language;- * - filterSkills: search filter for the skill dropdown (matches name and localized- * description, case-insensitive);- * - skillsAutoMessage / quickInvokeText: auto-invoke text and quick-invoke prefill text- * (zh/en dictionaries).+ * Skills in the composer and the skill library (features/chat/skill-use.ts and the+ * dictionaries' skill messages).+ *+ * - A skill's text follows the UI language: zh uses the Chinese value when it is non-empty,+ * otherwise English; en always English. The short description wins over the full one, the+ * language over the length.+ * - Every installed skill becomes a `/<name>` command described in the UI language; no skills,+ * no commands.+ * - The skill dropdown's search matches the name and the localized description,+ * case-insensitively; an empty query lists everything and no match lists nothing.+ * - The skill library's quick invoke prefills exactly the auto-invoke text an empty-body send+ * uses, which names the picked skills in the UI language.*/import { describe, expect, it } from "vitest";import type { SkillMetadataItem } from "@prismshadow/penguin-server/api";@@ -104,14 +104,6 @@ describe("skillSlashItems (slash skill command item assembly)", () => {expect(skillSlashItems([], "zh")).toEqual([]);});- it("cmd prefix matching (slash filter convention): /agent-opt hits /agent-optimization", () => {- const items = skillSlashItems(- [{ name: "agent-optimization", description: "Optimize agents", version: "" }],- "en",- );- expect(items[0]!.cmd.startsWith("/agent-opt")).toBe(true);- });-it("desc prefers the short description (falling back to the full one when missing)", () => {const withShort: SkillMetadataItem[] = [{diff --git a/packages/web/test/skill-use.test.ts b/packages/web/test/skill-use.test.tsdeleted file mode 100644index fc813014..00000000--- a/packages/web/test/skill-use.test.ts+++ /dev/null@@ -1,24 +0,0 @@-/**- * skill-use.ts unit test: the feature module re-exports the `[use_skills]` marker producer- * and parser from core's marker module — the block's own semantics (both forms, anchoring,- * legacy compat) are covered by packages/core/test/markers.test.ts. What matters here is- * that the wiring is intact for the components importing them from this module.- */-import { describe, expect, it } from "vitest";-import { buildSkillsMessage, parseSkillsMessage } from "../src/features/chat/skill-use";--describe("skill-use re-exports the core [use_skills] marker helpers", () => {- it("builds the square-bracket block and parses it back (round-trip through the feature module)", () => {- const text = buildSkillsMessage(["agent-initialization", "penguin-cli"], "use them\nline2");- expect(text.startsWith("[use_skills]\n")).toBe(true);- expect(parseSkillsMessage(text)).toEqual({- skills: ["agent-initialization", "penguin-cli"],- rest: "use them\nline2",- });- });-- it("an empty selection leaves the body untouched; a non-block message does not parse", () => {- expect(buildSkillsMessage([], "hello")).toBe("hello");- expect(parseSkillsMessage("plain text mentioning [use_skills] only")).toBeNull();- });-});diff --git a/packages/web/test/stream-follow.test.ts b/packages/web/test/stream-follow.test.tsindex 8f2e12b1..cd393508 100644--- a/packages/web/test/stream-follow.test.ts+++ b/packages/web/test/stream-follow.test.ts@@ -1,17 +1,18 @@/**- * Unit tests for stream-follow.ts (issue #75): in a short scroll area (scrollable- * slack < 80px), scrolling up immediately exits auto-stick-to-bottom; staying at- * a historical position, streaming increments don't override that intent; the- * user can scroll back down to resume; content-shrink clamping isn't- * misread as an upward scroll. Plus stickToBottom: programmatic snaps report the- * landed position synchronously, so content growth racing the snap's async scroll- * event can't make entering a conversation land off-bottom. Plus the hold: while the- * selection menu is open the view does not snap, the user's own scrolling still decides- * the intent, and a release catches a following view up with what arrived meanwhile.+ * Following the bottom of a streaming transcript (features/chat/stream-follow.ts, issue #75).+ *+ * - In a short scroll area, any upward move (wheel, scrollbar, keyboard, a touch pull-down)+ * exits following at once; pushing up with a finger does not.+ * - At a historical position, streaming growth never overrides the user's intent; scrolling+ * back near the bottom resumes following, and content shrinking under the view is not read+ * as scrolling up. A first scroll event already far from the bottom starts not following.+ * - The back-to-bottom button re-enters follow, and its jump keeps it stuck.+ * - A programmatic snap reports where it landed at once, so growth racing its scroll event+ * (entering a conversation, back-to-bottom) keeps follow; content that fits clamps to 0; a+ * real upward scroll right after still exits.+ * - While held (the selection menu is open) the view does not snap, the user's own scrolling+ * still decides the intent, and the release catches a following view up.*/-import { readFileSync } from "node:fs";-import { dirname, resolve } from "node:path";-import { fileURLToPath } from "node:url";import { describe, expect, it } from "vitest";import { createStreamFollow, stickToBottom } from "../src/features/chat/stream-follow";@@ -234,18 +235,4 @@ describe("hold", () => {expect(f.stick).toBe(false);expect(f.snaps).toBe(false);});-- it("is what the message stream snaps by, held while its selection menu is open", () => {- // The rules above bind the stream only while every snap it makes asks `snaps` rather than- // `stick`, and the hold follows the menu's open state.- const stream = readFileSync(- resolve(dirname(fileURLToPath(import.meta.url)), "../src/features/chat/message-stream.tsx"),- "utf8",- );- expect(stream).toContain("const menuOpen = selectionMenu.open;");- expect(stream).toContain("follow.hold(menuOpen);");- const snaps = stream.match(/if \(([^)]*?)\) stickToBottom\(el, follow\);/g) ?? [];- expect(snaps.length).toBeGreaterThanOrEqual(3);- for (const snap of snaps) expect(snap).toContain("follow.snaps");- });});diff --git a/packages/web/test/stream-model.test.ts b/packages/web/test/stream-model.test.tsindex a8e2dfdf..661dc2fe 100644--- a/packages/web/test/stream-model.test.ts+++ b/packages/web/test/stream-model.test.ts@@ -1,7 +1,40 @@/**- * stream-model.ts unit tests: partial aggregation, full-message- * convergence/replacement, orphan delta handling, overlap dedup, origin nested routing,- * approval/abort/compaction events, Task segmentation and stats triggering.+ * The chat stream's model (lib/omni/stream-model.ts): OmniMessages in, the items the chat+ * renders out, and the same items whether a conversation arrives live or is rebuilt from+ * history.+ *+ * - Streaming fragments accumulate into one item that the complete message then replaces;+ * an orphan fragment (joined mid-stream) is ignored; a late streaming copy never duplicates+ * a card history already built; tool-output images show as soon as a delta carries them.+ * - A live-tail start carrying an accumulated prefix seeds its item on top of history, and a+ * start for an already complete call or output changes nothing.+ * - Approval decisions annotate their card (manual when registered here, even across a resync+ * rebuild; remote otherwise), including decisions that arrive before the card; fatal errors+ * and aborts render their own items.+ * - A compaction renders one banner: its summary and thinking stream onto it, each body+ * section is timed over the window it shows itself running (retries included), history+ * replay rebuilds the same banner, and a quit or aborted compaction settles as failed.+ * - The MCP connect row sums tools, keeps per-server outcomes and its wall time.+ * - Retries render one ladder line per streak, with their countdown inputs, settling as+ * gave-up on abort, exhaustion or a new Task; request events inside a compaction do not.+ * - Subagent output routes into the nearest approved, unfinished run_subagent card, one hop+ * per level, else a standalone card; a child's tokens count toward the parent's stats.+ * - Messages carry their time; a Task starts at a user message or image and closes with a+ * stats row (tokens, output speed, elapsed from Trace timestamps, the copy target, the+ * fork position), compaction and approval waits attributed by position.+ * - Compaction-internal messages and steering never start a Task; background notices ride+ * inside the running Task unless they arrived idle.+ * - Elapsed time survives a reload mid-run and never leaks the local clock.+ * - Tool cards are found at any depth by origin chain, and an approval key tells apart the+ * same call id under different origins.+ * - Overlap dedup matches identical envelopes in its window (Trace positions ignored) and+ * discards the matching in-flight fragment, nested ones included.+ * - Thinking and tool durations cover generation and execution, minus approval waits; aborts+ * and idle close running cards.+ * - A repeated tool_call_id opens a new card and closes the superseded one.+ * - Empty or blank fidelity-only messages render nothing, live or rebuilt.+ * - A Task's stats row lists the memory files it changed (completed writes and edits under+ * the memory root only).*/import { describe, expect, it } from "vitest";import {@@ -2179,11 +2212,14 @@ describe("elapsed comes from Trace timestamps (#5/#20: settled spans, reload-stadescribe("approval keys and tool-card lookup (#7/#19)", () => {it("approvalKey distinguishes identical toolCallIds by origin chain", () => {- expect(approvalKey(undefined, "t1")).toBe(" t1");- expect(approvalKey([], "t1")).toBe(" t1");- expect(approvalKey(["c1"], "t1")).toBe("c1 t1");- expect(approvalKey(["c1", "c2"], "t1")).toBe("c1/c2 t1");- expect(approvalKey(["c1"], "t1")).not.toBe(approvalKey(undefined, "t1"));+ expect(approvalKey([], "t1")).toBe(approvalKey(undefined, "t1"));+ const keys = [+ approvalKey(undefined, "t1"),+ approvalKey(["c1"], "t1"),+ approvalKey(["c1", "c2"], "t1"),+ approvalKey(["c1"], "t2"),+ ];+ expect(new Set(keys).size).toBe(keys.length);});it("findToolCard locates tool cards at any depth by origin chain", () => {diff --git a/packages/web/test/temp-session.test.ts b/packages/web/test/temp-session.test.tsindex e821c8e7..a34f1e82 100644--- a/packages/web/test/temp-session.test.ts+++ b/packages/web/test/temp-session.test.ts@@ -1,13 +1,20 @@/**- * temp-session.ts unit tests: the company sidebar's Temporary group of ticket sessions. Opening- * a session adds it at the top or moves it there; ✕ removes one entry and "Close all" every- * entry, and nothing else removes any: going elsewhere only moves the on-screen mark, a reload- * reads the list back from storage, and the list has no cap. It never holds a desk session, and- * is kept per user, Project and organization.+ * The company sidebar's Temporary group of ticket sessions (features/company/temp-session.ts).+ *+ * - Opening a session adds it at the top, or moves it there under the title it was opened+ * with; the list has no cap and never holds a desk session.+ * - ✕ removes one entry (the rest keep their order; an unknown one changes nothing), and+ * "Close all" every entry of that organization, telling subscribers once; nothing else+ * removes any: going elsewhere only moves the on-screen mark.+ * - A missing or malformed stored value reads as an empty list.+ * - A reload reads the list back from storage, and the stored key goes once the last entry does.+ * - Each user, Project and organization has its own list.+ * - Subscribers hear of changes and nothing else, and the same array is handed out until one.+ * - A list another tab changed is reread, so an entry removed there is not written back.+ * - A storage that throws lists nothing stored and keeps what this tab opened.*/import { describe, expect, it } from "vitest";import {- chatPath,createTempSessionStore,parseTempSessions,tempSessionRows,@@ -15,18 +22,8 @@ import {withDismissed,withOpened,} from "../src/features/company/temp-session";-import type { TempSessionEntry, TempSessionStorage } from "../src/features/company/temp-session";--/** In-memory storage (vitest runs in a Node environment, no localStorage). */-function memStorage(): TempSessionStorage & { map: Map<string, string> } {- const map = new Map<string, string>();- return {- map,- getItem: (k) => map.get(k) ?? null,- setItem: (k, v) => void map.set(k, v),- removeItem: (k) => void map.delete(k),- };-}+import type { TempSessionEntry } from "../src/features/company/temp-session";+import { memoryStorage } from "./helpers/storage";function entry(n: number | string, over: Partial<TempSessionEntry> = {}): TempSessionEntry {return { sessionId: `sess_${n}`, agentId: "acme_dev", title: `Ticket session ${n}`, ...over };@@ -37,10 +34,6 @@ const ids = (list: readonly { sessionId: string }[]): string[] => list.map((e) =const KEY = tempSessionsKey("admin", "proj", "acme");describe("temporary session list", () => {- it("opens a conversation at its own route", () => {- expect(chatPath("sess_a")).toBe("/chat/sess_a");- });-it("adds an opened session at the top", () => {const one = withOpened([], entry("a"));expect(one).toEqual([entry("a")]);@@ -109,7 +102,7 @@ describe("stored temporary session list", () => {describe("temporary session store", () => {it("survives a reload: a new store over the same storage reads the list back", () => {- const storage = memStorage();+ const storage = memoryStorage();const before = createTempSessionStore(() => storage);before.open(KEY, entry("a"));before.open(KEY, entry("b"));@@ -121,7 +114,7 @@ describe("temporary session store", () => {});it("removes the stored key once the last entry is dismissed", () => {- const storage = memStorage();+ const storage = memoryStorage();const store = createTempSessionStore(() => storage);store.open(KEY, entry("a"));expect(storage.map.has(KEY)).toBe(true);@@ -131,7 +124,7 @@ describe("temporary session store", () => {});it("closes every entry at once with Close all, and says so once", () => {- const storage = memStorage();+ const storage = memoryStorage();const store = createTempSessionStore(() => storage);const other = tempSessionsKey("admin", "proj", "globex");store.open(KEY, entry("a"));@@ -165,9 +158,8 @@ describe("temporary session store", () => {tempSessionsKey(null, "proj", "acme"),];expect(new Set(keys).size).toBe(keys.length);- for (const key of keys) expect(key.startsWith("penguin.orgTempSessions.")).toBe(true);- const storage = memStorage();+ const storage = memoryStorage();const store = createTempSessionStore(() => storage);store.open(keys[0]!, entry("a"));store.open(keys[1]!, entry("b"));@@ -181,7 +173,7 @@ describe("temporary session store", () => {});it("leaves a desk session out of the stored list", () => {- const storage = memStorage();+ const storage = memoryStorage();const store = createTempSessionStore(() => storage);store.open(KEY, entry("a"));store.open(KEY, entry("desk"), ["sess_desk"]);@@ -189,7 +181,7 @@ describe("temporary session store", () => {});it("tells subscribers about a change and nothing else, and hands out the same array until one", () => {- const storage = memStorage();+ const storage = memoryStorage();const store = createTempSessionStore(() => storage);let notified = 0;const unsubscribe = store.subscribe(() => {@@ -217,7 +209,7 @@ describe("temporary session store", () => {});it("rereads a list another tab changed, so an entry removed there is not written back", () => {- const storage = memStorage();+ const storage = memoryStorage();const here = createTempSessionStore(() => storage);const there = createTempSessionStore(() => storage);here.open(KEY, entry("a"));diff --git a/packages/web/test/theme-prefs.test.ts b/packages/web/test/theme-prefs.test.tsindex c8e199e7..071e096e 100644--- a/packages/web/test/theme-prefs.test.ts+++ b/packages/web/test/theme-prefs.test.ts@@ -1,11 +1,19 @@/**- * The appearance preferences: what a stored value reads back as (theme, accent, text size with- * the legacy migration, font pairing), what they put on <html>, and the Appearance section's- * shape. The web suite runs in node with no DOM, so the root is a small fake that answers both- * the `dataset` and the attribute API, and the section is checked as source.+ * The appearance preferences (state/theme-prefs.ts, the UI package's boot attributes, and the+ * Appearance section's font choices). The root is a small fake answering both the `dataset`+ * and the attribute API.+ *+ * - An empty store reads as Primer, its own accent, 16px and its own faces.+ * - The legacy three-step font scale migrates by pixels once and its key is dropped; a stored+ * text size is kept and anything unknown reads as the default.+ * - The theme and font faces are validated against the package's lists; another theme's accent+ * is kept as stored while the theme's own accent is the one in effect.+ * - A chosen face is named on <html>, the theme's own face leaves no attribute, and the text+ * size sets the root font size.+ * - Every theme, text size and accent preset of the UI package is named in both languages.+ * - The font choices put the theme's own face first, once, and word the non-names from the+ * dictionary.*/-import fs from "node:fs";-import { fileURLToPath } from "node:url";import { afterEach, describe, expect, it } from "vitest";import { ACCENT_PRESET_IDS, THEME_IDS } from "@prismshadow/penguin-ui";import {@@ -16,28 +24,16 @@ import {applyThemeAttributes,} from "@prismshadow/penguin-ui/boot";import { effectiveAccent, readThemePrefs } from "../src/state/theme-prefs";-import type { PrefStorage } from "../src/state/theme-prefs";import { fontChoices } from "../src/features/settings/appearance-section";import { setActiveStrings, zh } from "../src/lib/strings";import { en } from "../src/lib/strings-en";+import { memoryStorage } from "./helpers/storage";afterEach(() => setActiveStrings(zh));/** The three-step size of earlier releases, spelled out: it is on disk whatever the code calls it. */const LEGACY_TEXT_SIZE_KEY = "penguin.fontScale";-function memStorage(entries: Record<string, string> = {}): PrefStorage & {- map: Map<string, string>;-} {- const map = new Map(Object.entries(entries));- return {- map,- getItem: (key) => map.get(key) ?? null,- setItem: (key, value) => void map.set(key, value),- removeItem: (key) => void map.delete(key),- };-}-/** An <html> stand-in: attributes behind both `dataset` and get/set/removeAttribute. */function fakeRoot() {const attrs = new Map<string, string>();@@ -84,7 +80,7 @@ function fakeRoot() {describe("reading the stored appearance", () => {it("falls back to the defaults on an empty store: Primer, its own accent, 16px, its own faces", () => {- expect(readThemePrefs(memStorage())).toEqual({+ expect(readThemePrefs(memoryStorage())).toEqual({themeId: "github",accent: "neutral",textSize: "m",@@ -99,7 +95,7 @@ describe("reading the stored appearance", () => {["md", "l"],["lg", "xl"],] as const) {- const storage = memStorage({ [LEGACY_TEXT_SIZE_KEY]: legacy });+ const storage = memoryStorage({ [LEGACY_TEXT_SIZE_KEY]: legacy });expect(readThemePrefs(storage).textSize).toBe(size);expect(storage.map.get(THEME_STORAGE_KEYS.textSize)).toBe(size);expect(storage.map.has(LEGACY_TEXT_SIZE_KEY)).toBe(false);@@ -110,17 +106,17 @@ describe("reading the stored appearance", () => {it("keeps a stored text size and reads anything unknown as the default", () => {for (const size of TEXT_SIZES) {- expect(readThemePrefs(memStorage({ [THEME_STORAGE_KEYS.textSize]: size })).textSize).toBe(+ expect(readThemePrefs(memoryStorage({ [THEME_STORAGE_KEYS.textSize]: size })).textSize).toBe(size,);}- expect(readThemePrefs(memStorage({ [THEME_STORAGE_KEYS.textSize]: "huge" })).textSize).toBe(+ expect(readThemePrefs(memoryStorage({ [THEME_STORAGE_KEYS.textSize]: "huge" })).textSize).toBe("m",);});it("validates the theme and the font faces against the package's lists", () => {- const storage = memStorage({+ const storage = memoryStorage({[THEME_STORAGE_KEYS.themeId]: "geek",[THEME_STORAGE_KEYS.fontLatin]: FONT_LATIN_OPTIONS.at(-1)!.id,[THEME_STORAGE_KEYS.fontCjk]: "comic-sans",@@ -129,13 +125,13 @@ describe("reading the stored appearance", () => {expect(prefs.themeId).toBe("geek");expect(prefs.fontLatin).toBe(FONT_LATIN_OPTIONS.at(-1)!.id);expect(prefs.fontCjk).toBe("theme");- expect(readThemePrefs(memStorage({ [THEME_STORAGE_KEYS.themeId]: "neon" })).themeId).toBe(+ expect(readThemePrefs(memoryStorage({ [THEME_STORAGE_KEYS.themeId]: "neon" })).themeId).toBe("github",);});it("keeps another theme's accent as stored, and marks the theme's own in effect", () => {- const prefs = readThemePrefs(memStorage({ [THEME_STORAGE_KEYS.accent]: "ocean" }));+ const prefs = readThemePrefs(memoryStorage({ [THEME_STORAGE_KEYS.accent]: "ocean" }));expect(prefs.accent).toBe("ocean");expect(effectiveAccent("modern", prefs.accent)).toBe("ocean");expect(effectiveAccent("github", prefs.accent)).toBe("neutral");@@ -149,7 +145,7 @@ describe("the attributes the preferences put on <html>", () => {const latin = FONT_LATIN_OPTIONS.find((option) => option.id !== "theme")!.id;const cjk = FONT_CJK_OPTIONS.find((option) => option.id !== "theme")!.id;applyThemeAttributes(root, {- ...readThemePrefs(memStorage()),+ ...readThemePrefs(memoryStorage()),fontLatin: latin,fontCjk: cjk,textSize: "xl",@@ -167,33 +163,6 @@ describe("the attributes the preferences put on <html>", () => {});describe("the Appearance section", () => {- const source = fs.readFileSync(- fileURLToPath(new URL("../src/features/settings/appearance-section.tsx", import.meta.url)),- "utf8",- );-- it("offers theme, mode, accent, text size and fonts first, in that order", () => {- const order = [- "S.settings.theme}",- "S.settings.colorMode}",- "S.settings.accent}",- "S.settings.fontSize}",- "S.settings.fonts}",- "S.settings.terminalTheme}",- ].map((label) => source.indexOf(`label={${label}`));- expect(order.every((at) => at > 0)).toBe(true);- expect([...order].sort((a, b) => a - b)).toEqual(order);- });-- it("builds every choice from the package's lists, and the swatches from the active theme", () => {- expect(source).toContain("THEME_IDS.map");- expect(source).toContain("TEXT_SIZES.map");- expect(source).toContain("cols={5}");- expect(source).toContain("fontChoices(FONT_LATIN_OPTIONS)");- expect(source).toContain("fontChoices(FONT_CJK_OPTIONS)");- expect(source).toContain("effectiveAccent(themeId, accent)");- });-it("names every theme, text size and accent preset in both languages", () => {for (const dict of [zh, en]) {for (const id of THEME_IDS) expect(dict.settings.themeNames[id]).toBeTruthy();diff --git a/packages/web/test/thinking-level.test.ts b/packages/web/test/thinking-level.test.tsindex 7160ed34..d2ee2b75 100644--- a/packages/web/test/thinking-level.test.ts+++ b/packages/web/test/thinking-level.test.ts@@ -1,20 +1,25 @@/**- * thinking-level.ts unit tests: the conversation-time pickers' short-name lookup and the- * selectable list — both pickers offer only low/medium/high/xhigh/max (many models cannot disable- * thinking; there is no "follow config" row — the session picker auto-follows the Agent- * config by initializing its display to it), while "none" stays a displayable stored value;- * "" (internally "untouched"/no override) and a legacy meta's "default" resolve to null so- * callers substitute the config level or a placeholder.+ * The thinking-level pickers (features/chat/thinking-level.ts) and the tier names in both+ * dictionaries.*- * Plus the mid-chat switch guard (#310): when a pick has to be confirmed, and how the- * dialog's "compact, then switch" choice decides — from the transcript alone — whether the- * compaction it started completed (apply the pick), settled without completing (keep the- * level and say so), or is still in flight.- *- * Plus a drift guard over the REAL dictionaries (the rest of this file works against the- * local NAMES stub): every tier core accepts has to be named in both locales, and the- * trigger/menu split has to hold — no tier can go unlabelled, and no wire value can leak- * back onto a trigger, without a test failing here.+ * - The pickers offer exactly the tiers core accepts as a chat default; every stored level,+ * a legacy "none" included, is named in both locales.+ * - The zh trigger shows a Chinese name with no wire value, while every menu row, in either+ * language, shows the wire value once.+ * - A non-level ("" for no override, a legacy "default", an unknown value, nothing) has no+ * label; a level missing from the name table shows its raw value.+ * - The draft picker resolves the Agent's explicit level, then the Project's chat default, then+ * medium, the chain core applies.+ * - The Agent settings dropdown lists the dictionary's tiers without the inherit row, adding a+ * display-only "none" row when the stored config holds one.+ * - The provider's prefix cache is at risk once there is history, unless the transcript ends in+ * a successful compaction.+ * - A mid-chat pick asks for confirmation only when history exists and the pick differs from+ * the displayed level (or that level is unknown), never right after a successful compaction.+ * - After "compact, then switch", the wait settles on the compaction started by that choice+ * (completed, failed or still running), and the pick is applied once it settles, even when+ * the compaction failed or never started.+ * - The in-session picker follows the Agent config until a level is pinned on the Session.*/import { describe, expect, it } from "vitest";import { DEFAULT_CHAT_THINKING_LEVELS } from "@prismshadow/penguin-core";@@ -45,25 +50,6 @@ const NAMES: Readonly<Record<string, string>> = {max: "max",};-describe("thinking level lists", () => {- it("offers only low/medium/high/xhigh/max — no 'none' (many models cannot disable thinking)", () => {- expect(SELECTABLE_THINKING_LEVELS).toEqual(["low", "medium", "high", "xhigh", "max"]);- expect(SELECTABLE_THINKING_LEVELS).not.toContain("none");- });-- it("keeps every stored level displayable (a legacy 'none' is shown, never offered)", () => {- expect(THINKING_LEVELS).toEqual(["none", "low", "medium", "high", "xhigh", "max"]);- expect(THINKING_LEVELS.map((l) => thinkingLevelLabel(NAMES, l))).toEqual([- "none",- "low",- "medium",- "high",- "xhigh",- "max",- ]);- });-});-describe("tier names track core, and the trigger/menu split holds", () => {const dictionaries: ReadonlyArray<readonly [string, typeof zh]> = [["zh", zh],@@ -85,21 +71,16 @@ describe("tier names track core, and the trigger/menu split holds", () => {}});- it("keeps the wire value off the zh trigger name and puts it on the zh menu row", () => {+ it("keeps the wire value off the zh trigger, and shows it once on every menu row", () => {for (const level of THINKING_LEVELS) {- const name = zh.chat.thinkingLevelNames[level] ?? "";+ const zhName = zh.chat.thinkingLevelNames[level] ?? "";// The maintainer's rule for the trigger: Chinese only — no latin letters, no parens.- expect(name, `zh ${level} must not carry the wire value`).not.toMatch(/[A-Za-z()]/);- // ...and the menu row is where that value belongs.- expect(zh.chat.thinkingLevelMenuName(name, level)).toBe(`${name} (${level})`);- }- });-- it("leaves en unsplit: its name already is the wire value, so the menu adds nothing", () => {- for (const level of THINKING_LEVELS) {- const name = en.chat.thinkingLevelNames[level] ?? "";- expect(name).toBe(level);- expect(en.chat.thinkingLevelMenuName(name, level)).toBe(name);+ expect(zhName, `zh ${level} must not carry the wire value`).not.toMatch(/[A-Za-z()]/);+ for (const [locale, dict] of dictionaries) {+ const name = dict.chat.thinkingLevelNames[level] ?? "";+ const row = dict.chat.thinkingLevelMenuName(name, level);+ expect(row.split(level).length - 1, `${locale} ${level} menu row`).toBe(1);+ }}});});diff --git a/packages/web/test/ticket-board.test.ts b/packages/web/test/ticket-board.test.tsindex a391b0d2..357781d0 100644--- a/packages/web/test/ticket-board.test.ts+++ b/packages/web/test/ticket-board.test.ts@@ -1,13 +1,20 @@/**- * ticket-board.ts unit tests: the five columns in lifecycle order, card sorting (priority,- * then due, then id), the blocked-only filter and the search box, the counts the overview- * shows, which moves need a reason, the "blocked on me" selection, the shape of an id slug,- * the overdue test, the day read off a ticket id, and the invalid-ticket list.+ * The ticket board (features/company/ticket-board.ts).+ *+ * - Only the five lifecycle statuses are ticket statuses.+ * - Cards sort by priority, then the earlier due date, then id.+ * - The board renders every column, narrowed to blocked cards and by the search box (title,+ * id, owner and parent, case-insensitively, and the owner's name through the chart), both+ * narrowings at once.+ * - Only a move into rejected needs a reason, and a same-column drop is no move; an empty+ * blocked string is not blocked.+ * - A new id's slug is lowercase words joined by hyphens.+ * - A due date is overdue once today has passed it; the creation day is read off the id.+ * - The tickets the server flagged invalid are listed in column order.*/import { describe, expect, it } from "vitest";import type { OrgTicketItem, OrgTicketsResponse } from "@prismshadow/penguin-server/api";import {- TICKET_COLUMNS,allTickets,boardColumns,canMove,@@ -44,8 +51,7 @@ function board(over: Partial<OrgTicketsResponse["columns"]> = {}): OrgTicketsRes}describe("columns", () => {- it("are the five statuses in lifecycle order", () => {- expect([...TICKET_COLUMNS]).toEqual(["proposed", "in_progress", "review", "done", "rejected"]);+ it("knows the lifecycle statuses and nothing else", () => {expect(isTicketStatus("review")).toBe(true);expect(isTicketStatus("blocked")).toBe(false);expect(isTicketStatus(null)).toBe(false);diff --git a/packages/web/test/ticket-detail-load.test.ts b/packages/web/test/ticket-detail-load.test.tsdeleted file mode 100644index b4e82497..00000000--- a/packages/web/test/ticket-detail-load.test.ts+++ /dev/null@@ -1,85 +0,0 @@-/**- * The ticket detail is revealed only once the names it reads are in.- *- * The dialog fetches three things: the ticket itself, the organization's board and its roster.- * The owner, the parent, the children and every history line render an id until the last two- * land and a name afterwards — and an id and a name are different lengths, so revealing the- * ticket on its own reflows the whole panel a moment later, under a reader who has already- * started reading it. The skeleton therefore waits for both, and the roster's arrival is- * counted as settled whether it resolved or failed, so a failed fetch opens the dialog on the- * ids rather than holding the skeleton open for names that are never coming.- *- * Gating on the ticket alone is the state this came from and the obvious thing to simplify back- * to: the extra term looks redundant next to a fetch the code calls best effort. So the shape is- * parsed rather than trusted to the comment beside it — with the TypeScript parser, since which- * branch a condition guards is not a question a regex over the file can answer.- */-import { describe, expect, it } from "vitest";-import { readFileSync } from "node:fs";-import { fileURLToPath } from "node:url";-import ts from "typescript";--const FILE = fileURLToPath(new URL("../src/features/company/ticket-dialog.tsx", import.meta.url));--/** Parse once; both checks ask a question about shape, not about text. */-function parse(source: string): ts.SourceFile {- return ts.createSourceFile(FILE, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);-}--/** Whether `name` is called anywhere under `node`. */-function calls(node: ts.Node, name: string): boolean {- if (ts.isCallExpression(node) && node.expression.getText() === name) return true;- return node.getChildren().some((child) => calls(child, name));-}--/** Every conditional whose "then" branch renders a `<Skeleton>`, as its condition's source text. */-function skeletonGuards(source: string): string[] {- const tree = parse(source);- const guards: string[] = [];- const rendersSkeleton = (node: ts.Node): boolean => {- if (ts.isJsxSelfClosingElement(node) || ts.isJsxOpeningElement(node)) {- if (node.tagName.getText() === "Skeleton") return true;- }- return node.getChildren().some(rendersSkeleton);- };- const walk = (node: ts.Node): void => {- if (ts.isConditionalExpression(node) && rendersSkeleton(node.whenTrue)) {- guards.push(node.condition.getText());- }- ts.forEachChild(node, walk);- };- walk(tree);- return guards;-}--describe("the ticket detail's loading gate", () => {- const guards = skeletonGuards(readFileSync(FILE, "utf8"));-- it("guards the skeleton on the ticket and on the roster it reads", () => {- expect(guards).toHaveLength(1);- const [guard] = guards as [string];- // The ticket, because there is nothing to show without it.- expect(guard).toMatch(/detail/);- // And the roster, because showing the ticket without it is what makes the panel jump.- expect(guard).toMatch(/contextReady/);- });-- it("counts the roster as settled even when its fetch fails", () => {- // The marker belongs in a `finally`, not beside the successful assignment: a failed board or- // chart fetch has to open the dialog on the ids rather than leave the skeleton pulsing. Asked- // of the try/finally itself, so moving the call into the `try` fails here even though the- // word `finally` is still in the file a line above it.- const tries: ts.TryStatement[] = [];- const walk = (node: ts.Node): void => {- if (ts.isTryStatement(node)) tries.push(node);- ts.forEachChild(node, walk);- };- walk(parse(readFileSync(FILE, "utf8")));-- const settling = tries.filter((t) => calls(t, "setContextOrg"));- expect(settling).toHaveLength(1);- const [statement] = settling as [ts.TryStatement];- expect(statement.finallyBlock && calls(statement.finallyBlock, "setContextOrg")).toBe(true);- expect(calls(statement.tryBlock, "setContextOrg")).toBe(false);- });-});diff --git a/packages/web/test/ticket-history.test.ts b/packages/web/test/ticket-history.test.tsindex 89880075..45ae7fea 100644--- a/packages/web/test/ticket-history.test.ts+++ b/packages/web/test/ticket-history.test.ts@@ -1,7 +1,12 @@/**- * ticket-history.ts unit tests: the order and keys of the history rows the drawer lists, that- * a row carries only what happened and never the note the action wrote, and the per-list- * counts the two folded sections report.+ * A ticket's history and folded sections in the ticket drawer (features/company/+ * ticket-history.ts).+ *+ * - History rows list newest first, each with a key of its own.+ * - A row keeps who acted and when, and never the note the action wrote.+ * - An entry older than the history's timestamps is kept; no history lists nothing.+ * - The folded sections count the children and the ticket's sessions, and report each list's+ * emptiness on its own.*/import { describe, expect, it } from "vitest";import type { OrgTicketDetail, OrgTicketHistoryEntry } from "@prismshadow/penguin-server/api";@@ -29,14 +34,13 @@ describe("ticketHistoryRows", () => {const rows = ticketHistoryRows([entry({ by: "agent:mk_dev", action: "progress", note: "drafted the schema" }),]);- expect(rows).toEqual([- {- key: "0-2026-09-08T10:00:00.000Z-progress",- at: "2026-09-08T10:00:00.000Z",- by: "agent:mk_dev",- action: "progress",- },- ]);+ expect(rows).toHaveLength(1);+ expect(rows[0]).toMatchObject({+ at: "2026-09-08T10:00:00.000Z",+ by: "agent:mk_dev",+ action: "progress",+ });+ expect(JSON.stringify(rows[0])).not.toContain("drafted the schema");});it("keeps an entry that predates the history's timestamps", () => {diff --git a/packages/web/test/title-reveal.test.ts b/packages/web/test/title-reveal.test.tsindex aa665bfe..0157aa0c 100644--- a/packages/web/test/title-reveal.test.ts+++ b/packages/web/test/title-reveal.test.ts@@ -1,19 +1,13 @@/**- * title-reveal.ts unit tests: the pure math behind the sidebar's truncated-title- * scroll reveal (#309). Distance: only a real overflow (beyond the 1px subpixel- * tolerance) counts — it drives both the `title` tooltip and the scroll, so "fits"- * must be exactly 0. Duration: proportional to the distance (constant reading- * speed), clamped between a floor (a sub-350ms hop reads as a glitch) and a- * ceiling (a huge title speeds up instead of holding the hover hostage), and 0- * when there is nothing to scroll. Disclosure: which of the scroll and the `title`- * tooltip reaches the tail (#570) — a rule rather than a number, but pure in the- * same way, so it is tested the same way.+ * The sidebar's truncated-title reveal (lib/title-reveal.ts): how far and how long a title+ * that does not fit scrolls, and which of the scroll and the tooltip reaches its tail.*- * The rest pins the CSS contract. The arithmetic was never the fragile- * part: the reveal only works while three files agree on four names, and nothing- * else in the suite notices if one side is renamed. vitest runs node-only here- * (`environment: "node"`, no jsdom), so these assert against the source text- * rather than a rendered DOM.+ * - A title that fits, or overflows by no more than the 1px subpixel tolerance, has nothing+ * to reveal; past the tolerance the whole overflow is revealed.+ * - The scroll runs at a constant reading speed, clamped between a floor and a ceiling, in+ * whole milliseconds, and takes no time when there is nothing to scroll.+ * - A title that fits discloses nothing; an overflowing one scrolls where the scroll is+ * offered and motion is allowed, and falls back to the tooltip otherwise.*/import { describe, expect, it } from "vitest";import {@@ -25,7 +19,6 @@ import {revealDurationMs,titleDisclosure,} from "../src/lib/title-reveal";-import { expectEveryRootScanned, expectSingleHome, scanSources, sourceFile } from "./helpers/roots";describe("revealDistancePx", () => {it("reports 0 when the text fits", () => {@@ -72,82 +65,6 @@ describe("revealDurationMs", () => {});});-const SCAN = scanSources();-const TRUNCATED = "packages/web/src/components/ui/truncated.tsx";-const truncated = sourceFile(SCAN, TRUNCATED).text;-const sidebar = sourceFile(SCAN, "packages/web/src/components/layout/sidebar.tsx").text;-/**- * Every stylesheet under the scanned roots — styles.css, and the shared package's CSS once the- * reveal's rules move there — with comments stripped and whitespace collapsed, so the assertions- * survive reformatting.- */-const css = SCAN.files- .filter((file) => file.name.endsWith(".css"))- .map((file) => file.text)- .join("\n")- .replace(/\/\*[\s\S]*?\*\//g, "")- .replace(/\s+/g, " ");-/** The keyframes that carry the whole reveal. */-const keyframes = css.match(/@keyframes title-scroll-reveal \{.*?\} \}/)?.[0] ?? "";-/** The hover/focus rule that starts them. */-const trigger = css.match(/\[data-title-reveal\][^{]*\{[^}]*\}/)?.[0] ?? "";--describe("the truncated-title reveal's CSS contract", () => {- it("is read from every source root, with the reveal component in one place", () => {- expectEveryRootScanned(SCAN);- expectSingleHome(SCAN, TRUNCATED);- expectSingleHome(SCAN, "packages/web/src/lib/title-reveal.ts");- });-- it("triggers on the row attribute the sidebar rows actually render", () => {- expect(sidebar).toContain("data-title-reveal");- expect(trigger).toContain("[data-title-reveal]:is(:hover, :has(:focus-visible))");- // Scoped to the inner span, so a title that fits (no class, no variables) matches nothing.- expect(trigger).toContain(".title-scroll > .title-scroll-text");- });-- it("selects the class names truncated.tsx emits", () => {- expect(truncated).toContain('" title-scroll"');- expect(truncated).toContain('className="title-scroll-text"');- });-- it("reads the custom properties truncated.tsx writes", () => {- for (const prop of ["--title-scroll-shift", "--title-scroll-ms"]) {- expect(truncated).toContain(prop);- expect(`${keyframes}${trigger}`).toContain(`var(${prop},`);- }- });-- it("moves the text with an animation, which is what reduced motion disables", () => {- // The reduced-motion guarantee is the global `animation: none !important` block, and- // it only reaches animations: rewriting this as a transition would keep the visuals and- // silently lose reduced-motion support. JS reads the same preference, but only to decide- // which disclosure is live (titleDisclosure below) — never to start or stop the motion.- expect(trigger).toMatch(/animation: title-scroll-reveal var\(--title-scroll-ms/);- expect(trigger).not.toContain("transition:");- expect(css).toMatch(- /@media \(prefers-reduced-motion: reduce\) \{[^@]*animation: none !important/,- );- });-- it("makes the text transformable inside the keyframes, never on the trigger rule", () => {- // `transform` is inert on a non-replaced inline box, so the reveal needs the inner- // span to become inline-block. It has to happen in the keyframes: as a declaration- // on the trigger it would apply the moment the pointer touches the row, and Blink- // paints no ellipsis for an overflowing atomic inline — so every long title would- // drop its "…" 0.3s before anything moved, which is the flicker the delay exists- // to prevent.- expect(keyframes).toContain("display: inline-block");- expect(keyframes).toContain("transform: translateX(var(--title-scroll-shift");- expect(trigger).not.toContain("display:");- expect(trigger).not.toContain("transform:");- });-- it("holds the revealed tail with a forwards fill after a start delay", () => {- expect(trigger).toMatch(/animation:[^;}]*\blinear\b[^;}]*\b0\.3s\b[^;}]*\bforwards\b/);- });-});-describe("titleDisclosure", () => {it("discloses nothing for a title that fits", () => {for (const scrollReveal of [false, true]) {@@ -180,10 +97,4 @@ describe("titleDisclosure", () => {);}});-- it("is the one rule the component asks", () => {- // The cases above only bind the rendering while truncated.tsx routes through this rule- // instead of re-deriving it inline, where the two could drift apart.- expect(truncated).toContain("titleDisclosure({");- });});diff --git a/packages/web/test/todo-notice.test.ts b/packages/web/test/todo-notice.test.tsindex 7dd3af77..e8033c9b 100644--- a/packages/web/test/todo-notice.test.ts+++ b/packages/web/test/todo-notice.test.ts@@ -1,20 +1,20 @@/*** The shared page notice (the UI package's `TodoNotice`, todo-notice.tsx) and the decisions- * behind its bulk-update button (src/lib/bulk-update.ts).+ * behind its bulk-update button (lib/bulk-update.ts).*- * Three rules are defended here, and each is a rule rather than a preference because breaking it- * produces a screen the user cannot reason about:+ * Guard, over every `<TodoNotice>` call site in the source roots (discovered, not listed):+ * - The notice is defined in one place.+ * - A bulk action is never offered without a label, nor a label without an action.+ * - The bulk button never writes on click: its handler opens the batch's own confirmation by+ * setting the state that ConfirmModal is rendered behind.*- * 1. **The counts come off the raised to-do**, never a second calculation. A block claiming three- * updates under a dot raised for four is unresolvable from the outside.- * 2. **The button opens a confirmation; it does not write.** A bulk overwrite is consented to- * before it runs, and every one of these pages already asks before overwriting a single- * object.- * 3. **A partial failure names the targets that failed.** On a control whose entire point is- * "all of them at once", a count with no names leaves the user re-checking every row by hand.- *- * Rules 2 and 3's first half are source scans over the real JSX rather than render assertions —- * vitest runs node-only here, so the thing that decays is a call site, not a component's output.+ * Behaviour:+ * - The counts come off the raised to-do: the whole count is upgradable where the trail has no+ * honest split, added and upgradable are split where it can tell them apart, and the block+ * never claims more than the dot was raised for.+ * - A batch outcome is clean when every target took the write (an empty batch included), and+ * otherwise names the failed targets by position, never as a blank; a long list reports its+ * overflow as a count; the first rejection is surfaced for the error text.*/import { describe, expect, it } from "vitest";import ts from "typescript";@@ -69,15 +69,6 @@ describe("the notice block is the one shape on every page that has one", () => {expectSingleHome(SCAN, TODO_NOTICE);});- it("is placed on all four dismissible trails and nowhere else", () => {- expect(sites.map((s) => s.file).sort()).toEqual([- "packages/web/src/features/agents/agents-page.tsx",- "packages/web/src/features/models/models-page.tsx",- "packages/web/src/features/plugins/plugins-page.tsx",- "packages/web/src/features/usage/usage-page.tsx",- ]);- });-it("never offers a bulk action without labelling it, or a label without an action", () => {for (const { file, attrs } of sites) {expect(attrs.has("actionLabel"), `${file} action label and handler must agree`).toBe(@@ -85,15 +76,6 @@ describe("the notice block is the one shape on every page that has one", () => {);}});-- it("only the cost center omits the bulk action — nothing there can be updated", () => {- const withAction = sites.filter((s) => s.attrs.has("onAction")).map((s) => s.file);- expect(withAction.sort()).toEqual([- "packages/web/src/features/agents/agents-page.tsx",- "packages/web/src/features/models/models-page.tsx",- "packages/web/src/features/plugins/plugins-page.tsx",- ]);- });});describe("the bulk button confirms before it writes", () => {diff --git a/packages/web/test/tone.test.ts b/packages/web/test/tone.test.tsindex 4affc538..8d1f7c84 100644--- a/packages/web/test/tone.test.ts+++ b/packages/web/test/tone.test.ts@@ -1,16 +1,15 @@/**- * The semantic status tones (src/lib/tone.ts) and the call sites that must not spell a status- * colour themselves. What these assert is the *single spelling* rule: one meaning, one pair of- * classes, written in one module — the drift these replaced was amber appearing as `amber-600`- * in one file and `amber-500` in the next for the same "waiting" state.+ * Guard: the status files take their colours from the semantic tones (lib/tone.ts and the UI+ * package's tone tokens) and never spell a status colour themselves — one meaning, one spelling;+ * the drift this replaced was amber appearing as `amber-600` in one file and `amber-500` in the+ * next for the same "waiting" state.+ *+ * - The tone module and each status file live in one place.+ * - No status file spells an amber, emerald, red or green palette class of its own.*/import { describe, expect, it } from "vitest";-import { toneDot, toneInk, toneSurface } from "../src/lib/tone";-import type { Tone } from "../src/lib/tone";import { expectEveryRootScanned, expectSingleHome, scanSources, sourceFile } from "./helpers/roots";-const TONES: Tone[] = ["busy", "attention", "success", "link", "danger", "muted"];-const SCAN = scanSources();/** A source file's text by its repo-relative id; fails when no scanned root holds it. */@@ -48,50 +47,9 @@ describe("tone tokens", () => {else expectSingleHome(SCAN, id);}});-- it("covers every tone in every map", () => {- for (const map of [toneInk, toneSurface, toneDot]) {- for (const tone of TONES) expect(map[tone]).toBeTruthy();- expect(Object.keys(map).sort()).toEqual([...TONES].sort());- }- });-- it("gives each ink a light and a dark class", () => {- for (const tone of TONES) {- const classes = toneInk[tone].split(" ");- expect(classes.filter((c) => c.startsWith("text-"))).toHaveLength(1);- expect(classes.filter((c) => c.startsWith("dark:text-"))).toHaveLength(1);- }- });-- it("keeps busy and success on one ink, and every other pair distinct", () => {- // Busy and success share a hue because the app has never told them apart by colour; a- // separate hue would invent a difference nobody is being asked to read.- expect(toneInk.busy).toBe(toneInk.success);- expect(new Set([toneInk.attention, toneInk.danger, toneInk.muted, toneInk.busy]).size).toBe(4);- });-- it("fills a state dot with one value across both themes", () => {- // A 6px dot has no interior to read: one vivid mid-scale hue works on white and on black,- // where an ink pair tuned for a stroke does not. Muted is the exception — it must recede.- for (const tone of ["busy", "attention", "success", "link", "danger"] as const) {- expect(toneDot[tone]).toMatch(/^bg-[a-z]+-500$/);- }- });});describe("status marks take their colour from the tokens", () => {- it("inks the two hourglass states with the same attention tone", () => {- // The session list's running glyph and the stream's waiting-for-approval glyph are the same- // state to a reader — unfinished, waiting — so they are the same colour.- expect(read("packages/ui/src/components/icons/status-icon/status-icon.tsx")).toContain(- 'waiting: "text-tone-attention-fg"',- );- expect(read("packages/ui/src/components/icons/activity-icon/activity-icon.tsx")).toContain(- "text-tone-attention-fg",- );- });-it("leaves no status file spelling a palette class of its own", () => {// Categorical palettes (charts, per-skill tints, the terminal's own theme) are deliberately// out of scope and are not listed here.diff --git a/packages/web/test/tool-alias.test.ts b/packages/web/test/tool-alias.test.tsindex 39736453..dd4a596c 100644--- a/packages/web/test/tool-alias.test.ts+++ b/packages/web/test/tool-alias.test.ts@@ -1,13 +1,12 @@/**- * tool-alias.ts unit tests: resolving a tool call's display name.+ * A tool call's display name (lib/tool-alias.ts).*- * The table covers the built-in tools and nothing else — an MCP tool and the names only- * older Traces still carry must survive both switch positions untouched, and turning the- * switch off must hand back every name exactly as it came in.- *- * Which tools those are is taken from core's own registry rather than from a list repeated- * here, so registering an eighth built-in tool without giving it a short name fails this- * file instead of silently shipping one card that still reads as the model's wire name.+ * - With the switch on, every built-in tool of core's registry reads as a short name of its+ * own, in either language.+ * - An MCP tool and the names only older Traces carry pass through untouched.+ * - With the switch off, every name comes back exactly as it came in.+ * - Both dictionaries alias exactly core's built-in tools, so registering a new built-in tool+ * without a short name fails here instead of shipping a card that reads as the wire name.*/import { afterEach, describe, expect, it } from "vitest";import { BUILTIN_TOOL_FACTORIES } from "@prismshadow/penguin-core";@@ -15,26 +14,8 @@ import { setActiveStrings, zh } from "../src/lib/strings";import { en } from "../src/lib/strings-en";import { toolDisplayName } from "../src/lib/tool-alias";-/** Wire name -> alias, in the active language. */-const EN_ALIASES: Record<string, string> = {- read_file: "read",- write_file: "write",- edit_file: "edit",- exec_command: "exec",- input_command: "follow",- run_subagent: "subagent",- input_subagent: "communicate",-};--const ZH_ALIASES: Record<string, string> = {- read_file: "读取",- write_file: "写入",- edit_file: "编辑",- exec_command: "执行命令",- input_command: "跟进命令",- run_subagent: "子智能体",- input_subagent: "交流",-};+/** Core's built-in tools, by wire name. */+const BUILTINS = Object.keys(BUILTIN_TOOL_FACTORIES).sort();/** Names that must pass through: an MCP tool, and tools no longer assembled but still in old Traces. */const PASSTHROUGH = [@@ -49,14 +30,12 @@ const PASSTHROUGH = [afterEach(() => setActiveStrings(zh));describe("toolDisplayName", () => {- it("names each built-in tool by its alias, in either language", () => {- setActiveStrings(en);- for (const [name, alias] of Object.entries(EN_ALIASES)) {- expect(toolDisplayName(name, true)).toBe(alias);- }- setActiveStrings(zh);- for (const [name, alias] of Object.entries(ZH_ALIASES)) {- expect(toolDisplayName(name, true)).toBe(alias);+ it("names each built-in tool by a short name of its own, in either language", () => {+ for (const strings of [en, zh]) {+ setActiveStrings(strings);+ const names = BUILTINS.map((name) => toolDisplayName(name, true));+ for (const [i, name] of names.entries()) expect(name).not.toBe(BUILTINS[i]);+ expect(new Set(names).size).toBe(BUILTINS.length);}});@@ -71,15 +50,13 @@ describe("toolDisplayName", () => {});it("returns every name unchanged with the switch off", () => {- for (const name of [...Object.keys(ZH_ALIASES), ...PASSTHROUGH, ""]) {+ for (const name of [...BUILTINS, ...PASSTHROUGH, ""]) {expect(toolDisplayName(name, false)).toBe(name);}});it("aliases exactly core's built-in tools, in both dictionaries", () => {- const builtins = Object.keys(BUILTIN_TOOL_FACTORIES).sort();- expect(builtins).toEqual(Object.keys(EN_ALIASES).sort());- expect(Object.keys(zh.chat.toolAliases).sort()).toEqual(builtins);- expect(Object.keys(en.chat.toolAliases).sort()).toEqual(builtins);+ expect(Object.keys(zh.chat.toolAliases).sort()).toEqual(BUILTINS);+ expect(Object.keys(en.chat.toolAliases).sort()).toEqual(BUILTINS);});});diff --git a/packages/web/test/tool-call-preview.test.ts b/packages/web/test/tool-call-preview.test.tsindex 7d40e22a..c1b99b3d 100644--- a/packages/web/test/tool-call-preview.test.ts+++ b/packages/web/test/tool-call-preview.test.ts@@ -1,12 +1,19 @@/**- * tool-call-card.tsx preview helpers: previewArguments keeps the real arguments (what heads- * the approval row), headerSubtitle surfaces the model-written `description` argument for- * the command/subagent tools and the shortened file path for the file tools, and- * pendingFilePayload decodes the file-tool arguments so a pending approval shows the actual- * rewrite. All must tolerate incomplete mid-stream JSON; headerSubtitle additionally holds a- * still-streaming field back until its closing quote so the header never jitters (#137).- * isDetachedCall and showsBackgroundAction decide the background mark and the "move to- * background" button from the same row's facts.+ * A tool call card's preview helpers (features/chat/tool-call-card.tsx). All of them tolerate+ * incomplete mid-stream JSON.+ *+ * - The approval row shows the real arguments: `$ <cmd>` for exec_command (its `command` alias+ * too, `cmd` winning), the shortened path for file tools and old image tools, and the raw+ * single line otherwise; a description argument never replaces the command.+ * - A path is shortened to at most one parent directory plus the file name.+ * - The header subtitle shows the model's description for command and subagent tools and the+ * file path for file tools, on one line, holding a still-streaming field back until it+ * closes (#137) and showing whatever is there once the arguments settle.+ * - A pending file-tool approval decodes the rewrite, the content or the read window.+ * - A call launched with the background flag is marked; one moved to the background later is+ * marked from the note its output carries.+ * - "Move to background" is offered only while exec_command or run_subagent executes on a+ * main-session card past the delay, and never for a call already in the background.*/import { describe, expect, it } from "vitest";import {@@ -17,9 +24,7 @@ import {previewArguments,shortenPath,showsBackgroundAction,- BACKGROUND_ACTION_DELAY_MS,} from "../src/features/chat/tool-call-card";-import { S } from "../src/lib/strings";describe("previewArguments", () => {it("renders exec_command as $ <cmd>", () => {@@ -227,8 +232,7 @@ describe("showsBackgroundAction", () => {});it("waits for the delay: a call that returns sooner never flashes it", () => {- // Ten seconds, measured by useElapsedPast on the card; this function only reads its answer.- expect(BACKGROUND_ACTION_DELAY_MS).toBe(10_000);+ // The delay is measured by useElapsedPast on the card; this function only reads its answer.expect(showsBackgroundAction("exec_command", EXEC, true, [], false)).toBe(false);expect(showsBackgroundAction("exec_command", EXEC, true, [], PAST)).toBe(true);});@@ -263,12 +267,3 @@ describe("showsBackgroundAction", () => {).toBe(false);});});--describe("the tool row's background marker", () => {- it("marks one call rather than a count of one", () => {- // The row marks a single call whose work went to the background; "1 background task"- // would be a count the row is not making, and would read as the conversation's total.- expect(S.chat.backgroundCall).not.toBe(S.chat.backgroundTasks(1));- expect(S.chat.backgroundCall).not.toMatch(/\d/);- });-});diff --git a/packages/web/test/trace-events-loader.test.ts b/packages/web/test/trace-events-loader.test.tsindex 35fa7adc..40bf0350 100644--- a/packages/web/test/trace-events-loader.test.ts+++ b/packages/web/test/trace-events-loader.test.ts@@ -1,18 +1,21 @@/**- * The Trace file view's event pager (features/traces/trace-events-loader.ts).+ * The Trace file view's event pager (features/traces/trace-events-loader.ts). The walk must+ * cover the WHOLE file: the analysis attributes messages to rounds by index range, so an event+ * never fetched is a round that renders an empty message list.*- * What matters here is that the walk covers the WHOLE file: the analysis beside it attributes- * messages to rounds by index range, so an event the walk never fetched is a round that renders- * an empty message list. The cases below are the four ways a walk ends — the file is covered,- * the file cannot be paged any further, the reader left, and the page cap — plus the one that- * moves the finish line, a file appended to while the walk is running.+ * - A 2500-event file is paged in three requests, every page reported in file order; the walk+ * advances by what a page delivered, not by what it asked for.+ * - A file appended to while the walk runs is followed to its new end.+ * - The walk ends on a page with no events, however long the file claims to be; it reports and+ * requests nothing more once cancelled (a page arriving after the cancel is dropped); a walk+ * that never finishes is capped.+ * - It resolves with the last page's total, the walk's final word on the file's length.*/import { describe, expect, it } from "vitest";import type { OmniMessage } from "@prismshadow/penguin-core/omnimessage";import type { TraceEventsResponse } from "@prismshadow/penguin-server/api";import {MAX_TRACE_EVENT_PAGES,- TRACE_EVENT_PAGE_SIZE,loadTraceEventPages,} from "../src/features/traces/trace-events-loader";@@ -209,9 +212,4 @@ describe("loadTraceEventPages", () => {).resolves.toBe(0);expect(gone.calls).toEqual([]);});-- it("asks for the largest page the events endpoint accepts", () => {- // The route parses `limit` as 1-1000 (server/src/http/validate.ts); a larger ask is a 400.- expect(TRACE_EVENT_PAGE_SIZE).toBe(1000);- });});diff --git a/packages/web/test/trace-refresh.test.ts b/packages/web/test/trace-refresh.test.tsindex 1f718650..895f2ea4 100644--- a/packages/web/test/trace-refresh.test.ts+++ b/packages/web/test/trace-refresh.test.ts@@ -1,18 +1,16 @@/**- * The Trace panel's refresh rules (features/traces/trace-refresh.ts): the tab re-fetches when- * it becomes visible and when a turn settles WHILE it is visible, never for a hidden tab, and- * a re-fetch leaves the user's selected file where they put it — including the default they- * never picked, and including a re-fetch that fails while they are reading.+ * The Trace panel's refresh rules (features/traces/trace-refresh.ts), decided by a pure tracker+ * the panel's effect applies.*- * The panel's edges are decided by a pure tracker for the same reason the subagents panel's- * auto-open is (panel-task-scope.test.ts): the Web suite runs in a node environment and renders- * no React, so the rule is unit-testable only where it is separable from the effect that applies- * it. The wiring that carries the decision into the two components is pinned at the bottom,- * against their source.+ * - The panel's own first render is no edge (the fetch effect already loads on mount).+ * - It re-fetches on the hidden→visible edge (not on the way back) and when a turn settles while+ * it shows; a hidden tab fetches nothing and the re-show brings it current; a settle arriving+ * with the re-show is one fetch; any change of the counter is a bump.+ * - The pill row orders files newest first without sorting the response in place; a re-fetch+ * keeps the selected file (grown, or with newer files beside it), falls back to the newest+ * when the selection vanished, and to nothing when the Session has no Trace.*/import { describe, expect, it } from "vitest";-import { readFileSync } from "node:fs";-import { fileURLToPath } from "node:url";import {activeTraceFile,advanceTraceRefresh,@@ -22,15 +20,6 @@ import {const obs = (active: boolean, signal: number) => ({ active, signal });-/**- * Source of the two components the rules are wired into. The suite renders no React, so a rule- * that lives inside an effect or a render guard is pinned against the text that implements it.- */-const read = (p: string) => readFileSync(fileURLToPath(new URL(p, import.meta.url)), "utf8");-const chatPage = read("../src/features/chat/chat-page.tsx");-const panel = read("../src/features/traces/trace-panel.tsx");-const fileView = read("../src/features/traces/trace-file-view.tsx");-describe("advanceTraceRefresh (when the Trace panel re-fetches)", () => {it("treats the panel's own first render as no edge — the fetch effect already loads on mount", () => {const shown = createTraceRefresh(obs(true, 3));@@ -113,96 +102,3 @@ describe("the Trace file list across a re-fetch", () => {expect(activeTraceFile([], 2)).toBeNull();});});--/**- * The decision has to reach both halves of the panel: the listing AND the file it is showing.- * A Trace file is appended to while the Session runs, so re-listing alone would refresh the- * sizes on the pills while the timeline below them stayed as it was read minutes ago.- */-describe("the settled-turn signal's wiring", () => {- /** The identifier a mounted component is handed as its reloadSignal, or null. */- const signalOf = (tag: string) =>- new RegExp(`<${tag}[^>]*reloadSignal=\\{(\\w+)\\}`).exec(chatPage)?.[1] ?? null;-- it("hands the Trace panel the very counter the Files panel refreshes on", () => {- expect(signalOf("WorkspaceBrowser")).not.toBeNull();- expect(signalOf("TracePanel")).toBe(signalOf("WorkspaceBrowser"));- });-- it("carries it one level further, into the view that reads the selected file", () => {- expect(panel).toMatch(/<TraceFileView[^>]*reloadSignal=\{listTick\}/);- expect(panel).toMatch(- /advanceTraceRefresh\(refresh\.current, \{ active, signal: reloadSignal \}\)/,- );- });-- it("re-runs the file's load on that signal, and clears no view state doing it", () => {- const load = fileView.slice(- fileView.indexOf("useEffect(() => {", fileView.indexOf("const fileKey")),- );- const body = load.slice(0, load.indexOf("\n }, ["));- const deps = /\n {2}\}, \[([^\]]*)\]/.exec(load)?.[1] ?? "";- expect(deps).toContain("reloadSignal");- // The collapsed rounds and the pinned row are cleared where a DIFFERENT file is adopted,- // never on a refresh of the one on screen.- expect(body).not.toContain("setCollapsed");- expect(body).not.toContain("setPinnedRow");- expect(fileView).toMatch(/renderedFileKey !== fileKey[\s\S]{0,320}setCollapsed\(new Set\(\)\)/);- });-});--/**- * What a refresh is allowed to move, now that one fires on every settled turn rather than only- * when the user brings the tab up. Both rules below are about the same reader: someone part-way- * through a Trace while the Session keeps working, who did nothing to ask for any of this.- */-describe("what a settled-turn refresh must leave alone", () => {- /** The panel's listing effect, and the failure branch inside it. */- const listing = panel.slice(- panel.indexOf("getSessionTraces"),- panel.indexOf("}, [active, listTick"),- );- const listingFailure = listing.slice(listing.indexOf(".catch("));-- it("pins the default selection to the first listing instead of re-resolving it each time", () => {- // activeTraceFile resolves a null pick to the newest file EVERY time it is called, so the- // panel has to commit to an index once rather than leave the default to that fallback.- expect(listing).toMatch(/setFileIndex\(\(cur\) => cur \?\?/);- // And the pin is one-way: the only other write is the user's own pill click.- expect(panel.match(/setFileIndex\(/g)).toHaveLength(2);- expect(panel).toMatch(/onClick=\{\(\) => setFileIndex\(f\.index\)\}/);- });-- it("keeps the listing on screen when a re-list fails, reporting it beside the pills", () => {- // Emptying the list here would unmount the pills, the header, the download link and the- // whole file view below them — collapsed rounds, pinned row and scroll position included.- expect(listingFailure).not.toContain("setFiles");- expect(listingFailure).toContain("setError(");- expect(panel).toMatch(/\{error !== null && \([\s\S]{0,200}<NoticeStrip tone="danger"/);- });-- it("gives the panel over to the failure only when there is nothing to keep", () => {- // The two whole-panel failure states: no listing yet, and a listing with no file in it.- expect(panel).toMatch(- /if \(files === null\) \{\s*if \(error !== null\) return <EmptyState title=\{S\.tracePanel\.loadFailed\}/,- );- expect(panel).toMatch(- /if \(activeFile === null\) \{\s*if \(error !== null\) return <EmptyState title=\{S\.tracePanel\.loadFailed\}/,- );- });-- it("keeps the file on screen when its re-read fails, reporting it above the summary", () => {- expect(fileView).toMatch(/if \(error !== null && analysis === null\)/);- expect(fileView).toMatch(/\{error !== null && <p /);- });-- it("prices nothing itself: cost is read off the analysis, and no model catalog is fetched", () => {- // The server prices each round with the cost center's rule (the Project's rates, at the- // tier the request's own timestamp fell in); a client-side price table would be a second- // rule that disagrees with the toolbar as soon as a schedule applies.- expect(fileView).not.toContain("getModels");- expect(fileView).not.toContain("pricing.cacheRead");- expect(fileView).toContain("formatMoney(analysis.cost ?? null, currency)");- expect(fileView).toContain("formatMoney(st?.cost ?? null, currency)");- });-});diff --git a/packages/web/test/trace-routing.test.ts b/packages/web/test/trace-routing.test.tsindex 17b8efb4..bc6192e7 100644--- a/packages/web/test/trace-routing.test.ts+++ b/packages/web/test/trace-routing.test.ts@@ -1,38 +1,38 @@/**- * Every call that names a Session reaches the machine the Session lives on.+ * Calls that name a Session without declaring it in the path still reach the machine the+ * Session lives on. The routing rule reads `/api/sessions/<id>/…` (lib/session-machines.ts);+ * the Agent-level Trace endpoints bury the id deeper, and a bare URL for `<img>`, `<iframe>` or+ * a download never passes through the fetch wrapper, so each carries the machine itself.*- * The routing rule reads `/api/sessions/<id>/…` off the path (lib/session-machines.ts). Two- * kinds of call escape it and have to carry the machine by hand: an endpoint that buries a- * Session id in an Agent-level path (the Trace endpoints), and a bare URL used in `<img>`,- * `<iframe>`, `fetch` or a download link, which never passes through the fetch wrapper. Both- * failed the same way — asked of this server about a Session on a machine, which truthfully- * had no such file — and both are pinned here by scanning the source, so the next endpoint of- * either shape is caught the moment it is written.+ * - Reading a Trace's events or its analysis through the Agent-level endpoints goes to the+ * Session's machine, and to this server for a Session that lives here.+ * - A Workspace file's address follows its Session to the machine.+ * - A Trace download link does too.*/-import fs from "node:fs";-import path from "node:path";-import { fileURLToPath } from "node:url";import { afterEach, describe, expect, it } from "vitest";-import { agentTraceDownloadUrl, workspaceFileUrl } from "../src/api/endpoints";+import {+ agentTraceDownloadUrl,+ getAgentTraceAnalysis,+ getAgentTraceEvents,+ workspaceFileUrl,+} from "../src/api/endpoints";import { forgetSessionMachines, rememberSessionMachine } from "../src/lib/session-machines";--const SOURCE = fs.readFileSync(- path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "src", "api", "endpoints.ts"),- "utf8",-);+import { json, stubFetch } from "./helpers/fetch";afterEach(() => forgetSessionMachines());describe("Session ids buried in Agent-level paths", () => {- it("every /traces/<sessionId> endpoint passes the Session's machine explicitly", () => {- // Each `export const … =` block that builds a `/traces/${…sessionId…}` path must mention- // machineForSession: the rule cannot read the id out of that path.- const blocks = SOURCE.split(/\nexport const /).slice(1);- const offenders = blocks- .filter((block) => /\/traces\/\$\{encodeURIComponent\(sessionId\)\}/.test(block))- .filter((block) => !block.includes("machineForSession(sessionId)"))- .map((block) => block.split(/[\s=(]/)[0]);- expect(offenders).toEqual([]);+ it("the Agent-level Trace reads go to the machine the Session lives on", async () => {+ const fetch = stubFetch(() => json({}));+ rememberSessionMachine("s1", "M1");+ await getAgentTraceEvents("p", "a", "s1", 3, 0, 50);+ await getAgentTraceAnalysis("p", "a", "s1", 3);+ await getAgentTraceEvents("p", "a", "here", 0, 0, 50);+ expect(fetch.requests.map((r) => [r.machine, r.path])).toEqual([+ ["M1", "/api/projects/p/agents/a/traces/s1/3"],+ ["M1", "/api/projects/p/agents/a/traces/s1/3/analysis"],+ [null, "/api/projects/p/agents/a/traces/here/0"],+ ]);});});diff --git a/packages/web/test/ui-strings.test.ts b/packages/web/test/ui-strings.test.tsindex e23c11bb..69a2cb3a 100644--- a/packages/web/test/ui-strings.test.ts+++ b/packages/web/test/ui-strings.test.ts@@ -1,16 +1,14 @@/**- * The shared UI package's accessibility fallbacks in the app's words (src/lib/ui-strings.ts): every- * `UiStrings` key is mapped from both dictionaries, and the language provider hands them over.+ * The shared UI package's accessibility fallbacks in the app's words (lib/ui-strings.ts).*- * vitest runs node-only here, and `LocaleProvider` reads localStorage and the browser's language- * as it mounts, so the mounting is pinned by its source rather than by a render.+ * - Every key the package asks for is mapped in both languages, each with real words (a+ * formatter naming its subject).+ * - Each language hands over one stable object, so the provider's value does not change between+ * renders.*/-import { readFileSync } from "node:fs";import { describe, expect, it } from "vitest";import { DEFAULT_UI_STRINGS } from "@prismshadow/penguin-ui";-import { zh } from "../src/lib/strings";-import { en } from "../src/lib/strings-en";-import { uiStringsFor, uiStringsOf } from "../src/lib/ui-strings";+import { uiStringsFor } from "../src/lib/ui-strings";const KEYS = Object.keys(DEFAULT_UI_STRINGS).sort();@@ -28,22 +26,7 @@ describe("uiStringsFor", () => {}});- it("speaks each dictionary's words", () => {- expect(uiStringsFor("zh")).toEqual(uiStringsOf(zh));- expect(uiStringsFor("en")).toEqual(uiStringsOf(en));- expect(uiStringsFor("zh").close).toBe(zh.common.close);- expect(uiStringsFor("en").copied).toBe(en.common.copied);- expect(uiStringsFor("zh").close).not.toBe(uiStringsFor("en").close);- });-it("keeps one object per language, so the provider's value does not change between renders", () => {expect(uiStringsFor("en")).toBe(uiStringsFor("en"));});});--describe("LocaleProvider", () => {- it("hands the package the words of the language it resolved", () => {- const source = readFileSync(new URL("../src/state/locale.tsx", import.meta.url), "utf8");- expect(source).toContain("<UiStringsProvider strings={uiStringsFor(locale)}>");- });-});diff --git a/packages/web/test/usage-controls.test.ts b/packages/web/test/usage-controls.test.tsindex dd971dfb..9c317587 100644--- a/packages/web/test/usage-controls.test.ts+++ b/packages/web/test/usage-controls.test.ts@@ -1,14 +1,18 @@/**- * Cost center control + series-shaping helper tests (usage-controls.ts): range- * presets (calendar and trailing timestamp windows), the precision each range- * derives (there is no precision control) and the bucket counts that keeps- * inside the server's cap, bucket-key labels, entity- * folding for the requests chart's stacked bars (top entities + a neutral- * counted tail), the per-bucket success / cache-hit rates (a bucket with- * nothing to rate has no rate, and is only given a height when a line has to- * cross it), and the empty-bucket compaction every chart on the page draws- * over — including that the per-entity counts stay aligned with the buckets- * after it.+ * The cost center's controls and series shaping (features/usage/usage-controls.ts).+ *+ * - A calendar preset ends today and spans its day count inclusively; a trailing preset yields+ * instant bounds plus the local dates they span; a range counts both ends.+ * - The range picks the precision: one per preset, a custom range scaling day → week → month,+ * never more buckets than the server returns, timestamp precisions only for trailing presets.+ * - A bucket key reads short on the axis and in full in the bubble.+ * - The requests chart keeps its top entities and folds a tail of two or more into one summed,+ * counted tail (success counts included); a tail of one keeps its name; by default every named+ * series fits the palette.+ * - Series sum column by column; a bucket with nothing to rate has no rate (neither 0 nor a+ * number), and is drawn at the top of the percent axis only so a line can cross it.+ * - Empty buckets are dropped (a request with no tokens still counts), shortening the axis and+ * marking breaks where buckets were skipped; per-entity counts stay with their buckets.*/import { describe, expect, it } from "vitest";import type { UsageSeriesPoint } from "@prismshadow/penguin-server/api";@@ -21,8 +25,6 @@ import {foldEntitySeries,hitRateValues,isoDate,- MAX_NAMED_SERIES,- NO_RATE_PLOT,plotRates,presetDefaultGranularity,presetRange,@@ -222,11 +224,10 @@ describe("foldEntitySeries", () => {expect(foldEntitySeries([], (n) => `other:${n}`, 4)).toEqual([]);});- it("the default cap is the palette's length: every named series gets a color of its own", () => {- expect(MAX_NAMED_SERIES).toBe(SERIES_COLORS.length);- const many = Array.from({ length: MAX_NAMED_SERIES + 3 }, (_, i) => e(`e${i}`, [1]));+ it("by default keeps as many named series as the palette has colours, and folds the rest", () => {+ const many = Array.from({ length: SERIES_COLORS.length + 3 }, (_, i) => e(`e${i}`, [1]));const folded = foldEntitySeries(many, (n) => `other:${n}`);- expect(folded).toHaveLength(MAX_NAMED_SERIES + 1);+ expect(folded.filter((series) => !series.other)).toHaveLength(SERIES_COLORS.length);expect(folded.at(-1)).toMatchObject({ label: "other:3", other: true });});});@@ -268,13 +269,9 @@ describe("rate values", () => {});it("plotRates gives every bucket a height so the stroke stays continuous, absent rates at the top of the axis", () => {- expect(NO_RATE_PLOT).toBe(100);- expect(plotRates([75, null, 0])).toEqual([75, NO_RATE_PLOT, 0]);+ expect(plotRates([75, null, 0])).toEqual([75, 100, 0]);// Drawing at 100 and reading 0 are different questions: a rated 0 is not lifted.- expect(plotRates(rateSeries({ completed: [0, 0], denominator: [0, 4] }))).toEqual([- NO_RATE_PLOT,- 0,- ]);+ expect(plotRates(rateSeries({ completed: [0, 0], denominator: [0, 4] }))).toEqual([100, 0]);});});diff --git a/packages/web/test/user-shortcuts.test.ts b/packages/web/test/user-shortcuts.test.tsindex 626f2bc5..cea13590 100644--- a/packages/web/test/user-shortcuts.test.ts+++ b/packages/web/test/user-shortcuts.test.ts@@ -1,24 +1,24 @@/**- * The draft screen's user-defined shortcuts: the rules the editor enforces, the shape that comes- * back out of free-form storage, and the two invariants the feature had to keep.+ * The draft screen's user-defined shortcuts (features/chat/user-shortcuts.ts).*- * Three groups worth naming.- *- * - **The caps are duplicated across packages on purpose** — the Web App's copy drives the- * counters, the server's copy is the enforcement — so the parity check reads the server module- * as text rather than importing it: `@prismshadow/penguin-server` is a type-only dependency- * here, and making it a runtime one to check three numbers would be a worse trade than a regex.- * - **The examples block's height must not move** when folders are switched. The built-in folders- * keep that by staying within a row of each other; the user's folder cannot, so it is pinned to- * the tallest built-in folder's height and scrolls. Both halves are asserted.- * - **A click on a shortcut is a fill, not a send**, and it pins no Skills — checked through- * buildExampleFill and against the real handler in draft-view.tsx, the way- * test/example-fill.test.ts checks the built-in rows.+ * - A stored list reads back unchanged; anything else reads as no shortcuts, entries that+ * cannot be a row are dropped, fields are trimmed and over-long ones truncated, duplicate ids+ * dropped, and the list stops at the count cap.+ * - The editor refuses a missing title or prompt (whitespace is not content) and either field+ * over its cap.+ * - Saving appends a new shortcut with an id of its own (distinct every time), edits in place,+ * trims, re-appends a draft whose shortcut was deleted elsewhere, and never grows past the+ * cap; removing closes the gap and ignores unknown ids.+ * - The suggested title is the first non-empty line, one line, capped; nothing for an empty+ * composer.+ * - The user folder's tallest state stays within one row of the tallest built-in folder, so the+ * examples block does not move as folders are switched.+ * - The caps match the server's copy, which enforces them (read from the server module's+ * source: the server package is a type-only dependency of the Web App).*/import { describe, expect, it } from "vitest";import { readFileSync } from "node:fs";import { fileURLToPath } from "node:url";-import { buildExampleFill } from "../src/features/chat/example-fill";import { EXAMPLE_FOLDERS } from "../src/features/chat/example-tasks";import {SHORTCUT_MAX_COUNT,@@ -199,13 +199,6 @@ describe("defaultShortcutTitle — the name suggested when saving what was typed});describe("the examples block keeps its height", () => {- it("keeps the built-in folders within one row of each other", () => {- // The draft page reserves no scroll area for this block, so a folder much longer than its- // siblings is what makes the height jump as folders are switched.- const lengths = EXAMPLE_FOLDERS.map((folder) => folder.tasks.length);- expect(Math.max(...lengths) - Math.min(...lengths)).toBeLessThanOrEqual(1);- });-it("keeps the user folder within one row of the built-in ones", () => {// Its tallest state is either the cap with no add row, or one below the cap plus the add// row — both SHORTCUT_MAX_COUNT rows. The cap is what holds this, not a pinned height with@@ -214,51 +207,6 @@ describe("the examples block keeps its height", () => {const tallestUser = Math.max(SHORTCUT_MAX_COUNT, SHORTCUT_MAX_COUNT - 1 + 1);expect(tallestUser - tallestBuiltIn).toBeLessThanOrEqual(1);});-- it("drops the add row at the cap instead of disabling it", () => {- // The header already reads 3/3; a disabled row explaining the same thing is the second- // telling, and it is the row that would otherwise make the folder one taller than its cap.- const source = read("../src/features/chat/shortcuts-folder.tsx");- expect(source).toContain("canAddShortcut(shortcuts) && (");- expect(source).not.toContain("disabled={!canAddShortcut");- });-- it("labels the folder used/limit rather than a bare count", () => {- const source = read("../src/features/chat/shortcuts-folder.tsx");- expect(source).toContain("count={`${shortcuts.length}/${SHORTCUT_MAX_COUNT}`}");- });-- it("gives the user folder no scroll box of its own", () => {- // A scrollbar inside a folder of at most a few rows reads as a defect; the cap removes the- // need for one, so the markup must not reintroduce it.- const source = read("../src/features/chat/shortcuts-folder.tsx");- expect(source).not.toContain("overflow-y-auto");- expect(source).not.toContain("bodyHeight");- });-});--describe("clicking a shortcut", () => {- it("hands the composer the saved prompt and leaves the Skill selection alone", () => {- // A saved prompt is not authored against the shipped Skill catalog, so it pins nothing —- // and an empty pin list is exactly what leaves a selection the user made by hand intact.- const fill = buildExampleFill({- prompt: "Summarize the week.",- exampleSkills: [],- installedSkills: ["web-design", "memory"],- selectedSkills: ["memory"],- });- expect(fill.text).toBe("Summarize the week.");- expect(fill.skills).toEqual(["memory"]);- });-- it("routes the click through the composer handle and never sends", () => {- const source = read("../src/features/chat/draft-view.tsx");- const handler = /const fillShortcut = useCallback\(([\s\S]*?)\n \}, \[\]\);/.exec(source);- expect(handler, "the fillShortcut handler").not.toBeNull();- expect(handler?.[1]).toContain("composerRef.current?.fillPrompt(prompt, [])");- expect(handler?.[1]).not.toContain("onSend");- expect(handler?.[1]).not.toContain("api.");- });});describe("the caps the server enforces", () => {diff --git a/packages/web/test/vite-config.test.ts b/packages/web/test/vite-config.test.tsnew file mode 100644index 00000000..f5e515e2--- /dev/null+++ b/packages/web/test/vite-config.test.ts@@ -0,0 +1,52 @@+/**+ * The helpers vite.config.ts is built from.+ *+ * - The dev server's `/api` proxy defaults to the development backend (7368, not the installed+ * server's 7364), follows PORT, treats an empty PORT as unset rather than as port 80, and is+ * replaced outright by PENGUIN_API_PROXY unless that is empty.+ * - KaTeX's stylesheet ships woff2 only: the woff and truetype fallbacks are dropped, and a+ * stylesheet without them is left untouched.+ */+import { describe, expect, it } from "vitest";+import { apiProxyTarget, dropNonWoff2FontSources } from "../vite.config.js";++describe("apiProxyTarget", () => {+ it("defaults to the development backend, not the installed server's 7364", () => {+ expect(apiProxyTarget({})).toBe("http://127.0.0.1:7368");+ });++ it("treats an empty PORT as unset rather than as port 80", () => {+ expect(apiProxyTarget({ PORT: "" })).toBe("http://127.0.0.1:7368");+ });++ it("follows PORT so moving the backend moves the proxy with it", () => {+ expect(apiProxyTarget({ PORT: "9999" })).toBe("http://127.0.0.1:9999");+ });++ it("PENGUIN_API_PROXY replaces the whole target, PORT and all", () => {+ expect(apiProxyTarget({ PORT: "9999", PENGUIN_API_PROXY: "http://10.0.0.2:8080" })).toBe(+ "http://10.0.0.2:8080",+ );+ });++ it("an empty PENGUIN_API_PROXY falls back instead of proxying to nowhere", () => {+ expect(apiProxyTarget({ PENGUIN_API_PROXY: "" })).toBe("http://127.0.0.1:7368");+ });+});++describe("KaTeX fonts ship locally, woff2 only", () => {+ const SRC = `@font-face{font-display:block;font-family:KaTeX_Main;src:url(fonts/KaTeX_Main-Regular.woff2) format("woff2"),url(fonts/KaTeX_Main-Regular.woff) format("woff"),url(fonts/KaTeX_Main-Regular.ttf) format("truetype")}`;++ it("keeps the woff2 source and drops the woff and truetype ones", () => {+ const stripped = dropNonWoff2FontSources(SRC);+ expect(stripped).toContain('url(fonts/KaTeX_Main-Regular.woff2) format("woff2")');+ expect(stripped).not.toContain(".woff)");+ expect(stripped).not.toContain(".ttf)");+ expect(stripped).toContain("font-family:KaTeX_Main");+ });++ it("leaves a stylesheet that has no fallbacks untouched", () => {+ const only = `@font-face{src:url(fonts/A.woff2) format("woff2")}`;+ expect(dropNonWoff2FontSources(only)).toBe(only);+ });+});diff --git a/packages/web/test/wechat-scan-connect.test.ts b/packages/web/test/wechat-scan-connect.test.tsindex eb2cf750..0ffb6f43 100644--- a/packages/web/test/wechat-scan-connect.test.ts+++ b/packages/web/test/wechat-scan-connect.test.ts@@ -1,20 +1,15 @@/**- * The WeChat scan-to-connect block: what it renders, and the decision its poll loop makes on- * each answer.+ * The WeChat scan-to-connect block (features/messaging/wechat-scan-connect.tsx): what it+ * renders, and the decision its poll loop makes on each answer (`wechatScanStep`, tested by+ * value). The QR itself is QQ's component and is tested there.*- * It carries more states than QQ's, and that is what most of this file is about. WeChat- * separates SCANNING from confirming and may interpose a pairing code shown on the phone, so- * two of its answers change the panel's caption while leaving the code up — tearing the QR- * down mid-flow would strand a user who is looking at their phone. Two more end the flow- * without being failures or lapses: a code spent on wrong pairing digits, and a bot that was- * already bound here, which is news rather than an error.- *- * The QR itself is QQ's component, so its rendering rules are asserted there; what is- * asserted here is that this panel reaches for it rather than growing a second one.- *- * The loop is tested by value rather than by mounting: this package's vitest runs in `node`,- * deliberately, so the classification lives in a pure function (`wechatScanStep`, the- * `updateCheckOutcome` idiom) and the effects around it stay a thin shell.+ * - The scan is offered as a control alone, its explanation disclosed elsewhere, and nothing is+ * requested before the user asks; with a credential stored it offers to replace it; it is+ * gated, with the reason, while the connection is enabled.+ * - The loop keeps waiting while nothing has happened, reports scanning and pairing progress+ * without taking the code down, hands the binding on so the editor adopts it without a second+ * GET, ends on a spent pairing code, reports an already-bound bot as news rather than as a+ * failure, rides out a transient failure, and replaces a lapsed code a bounded number of times.*/import { describe, expect, it } from "vitest";import { createElement } from "react";@@ -23,8 +18,7 @@ import type { WeChatBindingInfo, WeChatScanPollResponse } from "@prismshadow/penimport { ApiError } from "../src/api/client";import { WeChatScanConnect, wechatScanStep } from "../src/features/messaging/wechat-scan-connect";import type { WeChatScanTally } from "../src/features/messaging/wechat-scan-connect";-import { S, zh } from "../src/lib/strings";-import { en } from "../src/lib/strings-en";+import { S } from "../src/lib/strings";describe("WeChatScanConnect", () => {const render = (opts: { enabled?: boolean; bound?: boolean } = {}) =>@@ -149,13 +143,4 @@ describe("wechatScanStep", () => {releaseTask: false,});});-- it("names no position for the code, which wraps above the text in a narrow panel", () => {- // The waiting panel is `flex flex-wrap`: in the dock or on a phone the steps sit BELOW- // the QR, so copy that says "the code on the left" is wrong exactly where it is read.- for (const dict of [zh, en]) {- expect(dict.wechat.scanSteps).not.toMatch(/左侧|右侧|left|right/);- expect(dict.wechat.verifyPrompt).not.toMatch(/左侧|右侧|left|right/);- }- });});diff --git a/packages/web/test/workspace-finder.test.ts b/packages/web/test/workspace-finder.test.tsindex 40088b7d..708dc62e 100644--- a/packages/web/test/workspace-finder.test.ts+++ b/packages/web/test/workspace-finder.test.ts@@ -1,16 +1,29 @@/**- * The Workspace finder (src/features/chat/workspace-finder*.tsx): the modal every Workspace- * picker opens. Its decisions live in workspace-finder-model.ts and are exercised directly —- * breadcrumbs for both path families, back/forward history, type-to-select, the keyboard map,- * Quick access per platform with the user's own edits, the context menu's rows, Recent, what- * the box for a refused folder offers, and the footer's no-folder button. The suite has no DOM,- * so the few JSX facts that fail silently are pinned against the source: the finder is a Modal- * (no second overlay system), a permission refusal renders its own box instead of an empty- * folder, the address bar is the one place a path is typed, a folder row carries its own way- * in, and no folder is a footer button rather than a sentence.+ * The Workspace finder every Workspace picker opens; its decisions live in+ * features/chat/workspace-finder-model.ts.+ *+ * - Breadcrumbs split a posix path from the root and keep a drive root whole.+ * - History goes back and forward, a new visit drops what was ahead, and reloading the folder+ * shown records nothing.+ * - The list hides hidden entries and puts folders first; type-to-select finds a folder by+ * prefix and arrow keys skip files, stopping at the ends.+ * - The keyboard map reads the Finder chords with ⌘ on a Mac and Ctrl elsewhere, leaving Enter+ * and Home/End to a text field.+ * - Quick access offers each platform's standard folders that exist there (Windows names+ * ignoring case), keeps Windows drives apart, takes the user's additions and removals (a+ * default included), and stores them per machine, reading anything unreadable as none.+ * - The context menu offers open, choose, Quick access and copy on a folder, copy only on a+ * file, and acts on the open folder (with Refresh) from the list's empty space.+ * - Recent folds the newest Session per Workspace across Agents, leaving temporary ones out;+ * "go to" resolves ~ against the machine's home.+ * - A folder the server may not read gets a box of its own: the desktop app's access request+ * only on a Mac, in the shell, browsing its own server, and never Retry alone where there is+ * something better to do.+ * - The footer's no-folder button is there whenever the host offers no folder, and its tooltip+ * names the folder a temporary Workspace would get (a Windows path keeps its separator) —+ * none without the Agent's directory, while another machine is browsed, or for an unknown+ * layout.*/-import { readFileSync } from "node:fs";-import { fileURLToPath } from "node:url";import { describe, expect, it } from "vitest";import type { DirEntryInfo, DirListResponse } from "@prismshadow/penguin-server/api";import {@@ -41,11 +54,8 @@ import {typeSelectIndex,visibleEntries,} from "../src/features/chat/workspace-finder-model";-import type {- AccessAsk,- DeniedBox,- QuickAccessStorage,-} from "../src/features/chat/workspace-finder-model";+import type { AccessAsk, DeniedBox } from "../src/features/chat/workspace-finder-model";+import { memoryStorage } from "./helpers/storage";const dir = (name: string, kind: "dir" | "file" = "dir"): DirEntryInfo => ({name,@@ -250,21 +260,15 @@ describe("quick access", () => {});it("stores the edits per machine, and reads anything unreadable as none", () => {- const store = new Map<string, string>();- const storage: QuickAccessStorage = {- getItem: (k) => store.get(k) ?? null,- setItem: (k, v) => void store.set(k, v),- };+ const storage = memoryStorage();const edits = { added: ["/srv/work"], removed: ["/home/me/Desktop"] };saveQuickAccess(null, edits, storage);saveQuickAccess("m-1", NO_EDITS, storage);expect(loadQuickAccess(null, storage)).toEqual(edits);expect(loadQuickAccess("m-1", storage)).toEqual(NO_EDITS);- expect(quickAccessKey(null)).toBe("penguin.finderQuickAccess.local");- expect(quickAccessKey("m-1")).toBe("penguin.finderQuickAccess.m-1");- store.set(quickAccessKey("m-2"), "{not json");+ storage.setItem(quickAccessKey("m-2"), "{not json");expect(loadQuickAccess("m-2", storage)).toEqual(NO_EDITS);- store.set(quickAccessKey("m-3"), JSON.stringify({ added: ["/a", 3, ""], removed: "x" }));+ storage.setItem(quickAccessKey("m-3"), JSON.stringify({ added: ["/a", 3, ""], removed: "x" }));expect(loadQuickAccess("m-3", storage)).toEqual({ added: ["/a"], removed: [] });});});@@ -416,49 +420,3 @@ describe("the footer's no-folder button", () => {expect(tempWorkspacePath("/")).toBeNull();});});--describe("the modal (source contract)", () => {- const read = (rel: string) =>- readFileSync(fileURLToPath(new URL(`../src/${rel}`, import.meta.url)), "utf8");- const finder = read("features/chat/workspace-finder.tsx");- const select = read("features/chat/workspace-select.tsx");-- it("is the shared Modal, so it stacks on a host dialog through the one Escape stack", () => {- expect(finder).toContain("<Modal");- // No title bar: Cancel is the way out; the title still names the dialog.- expect(finder).toMatch(/<Modal[\s\S]*?headerless[\s\S]*?>/);- expect(finder).not.toContain("createPortal");- expect(finder).not.toMatch(/fixed inset-0/);- expect(select).not.toContain("Dropdown");- });-- it("says a refused folder is refused, in the box deniedBox decides", () => {- expect(finder).toContain('code === "dir_permission_denied"');- expect(finder).toContain("f[denied.text]");- // The one renderer marker (lib/desktop-renderer.ts), not a check of the finder's own.- expect(finder).toContain("isElectronRenderer(navigator.userAgent)");- expect(finder).toMatch(/api\s*\.requestDirAccess\(projectId, target\)/);- // A server with no shell behind it gets the browser tab's explanation, not an error loop.- expect(finder).toContain('err.code === "shell_unreachable"');- });-- it("types a path in the address bar itself — no separate Go to row or button", () => {- expect(finder).toContain("onClick={editAddress}");- expect(finder).not.toMatch(/goToSubmit|gotoRow/);- });-- it("gives a folder row an enter button, and one context menu covers the finder", () => {- expect(finder).toContain("aria-label={f.openFolder(entry.name)}");- expect(finder).toContain("useRowContextMenu()");- expect(finder).toContain("anchorRect={menu.anchor}");- });-- it("offers no folder as a footer button, with no rule spelled out beside it", () => {- expect(finder).toContain("title={clear.fullPath ?? clearTitle}");- expect(finder).not.toContain("clear.pressed");- expect(finder).toMatch(/api\s*\.getAgentConfig\(projectId, agentId\)/);- expect(finder).not.toMatch(/hint/i);- // The sidebar's new-workspace button adds a folder: it has no empty value to go back to.- expect(select).toMatch(/onClear=\{\s*clearable/);- });-});diff --git a/packages/web/test/workspace-registry.test.ts b/packages/web/test/workspace-registry.test.tsindex b090ea59..e2095008 100644--- a/packages/web/test/workspace-registry.test.ts+++ b/packages/web/test/workspace-registry.test.ts@@ -1,14 +1,22 @@/**- * workspace-registry.ts unit tests: manually-added Workspaces (the header's 新建工作区- * browse pick) persisted per Project and merged into the sidebar's workspace grouping- * as EMPTY groups — a picked directory shows up immediately, Sessions or not. Entries- * are `{ path, alias? }`: the alias (重命名工作区) replaces the basename as the group- * label — for session-backed groups too — and a blank alias reverts to the basename;- * loads keep accepting the branch's earlier string-only stored shape. 删除工作区- * unregisters the entry only (sidebar-side; disk and Sessions untouched — a group with- * Sessions simply persists as session-derived). Paths normalize (trim + trailing- * separators dropped, root kept) so picker output dedups against server-resolved- * Session paths; storage is tolerant of junk; temp-shaped paths never form a group.+ * Workspaces the user added by hand (lib/workspace-registry.ts): kept per Project in+ * localStorage and merged into the sidebar's Workspace grouping as groups of their own.+ *+ * - A picked path is normalized (trimmed, trailing separators dropped, a root or a Windows+ * drive root kept whole), so it dedups against the paths Sessions report.+ * - Registering prepends the pick; an already registered path, a blank one or a temporary+ * Workspace changes nothing (the same array comes back). The machine a directory was picked+ * on is recorded, and the same path on two machines is two Workspaces.+ * - Unregistering drops one machine's entry, alias and all, and nothing when absent.+ * - An alias is trimmed, a blank one reverts to the basename, the input is never mutated, and+ * an unchanged alias changes nothing; renaming one machine's entry leaves the other's alone.+ * - Entries round-trip per Project (alias and machine included); nothing stored or no Project+ * is empty and reading writes nothing; the older string-only shape still loads.+ * - Malformed values, junk elements, junk aliases and empty machine ids are dropped; a storage+ * that throws degrades instead of escaping.+ * - Merged into the groups, empty registered groups follow the session-backed ones, an alias+ * relabels a session-backed group too, a temporary path never forms a group, and each+ * machine gets its own group.*/import { describe, expect, it } from "vitest";import {@@ -24,16 +32,7 @@ import {import type { WorkspaceEntry, WorkspaceRegistryStorage } from "../src/lib/workspace-registry";import { TEMP_WORKSPACE_GROUP_KEY } from "../src/lib/session-grouping";import type { WorkspaceGroup } from "../src/lib/session-grouping";--/** In-memory storage (vitest runs in a Node environment, no localStorage; draft-cache.test.ts convention). */-function memStorage(): WorkspaceRegistryStorage & { map: Map<string, string> } {- const map = new Map<string, string>();- return {- map,- getItem: (k) => map.get(k) ?? null,- setItem: (k, v) => void map.set(k, v),- };-}+import { blockedStorage, memoryStorage } from "./helpers/storage";/** Minimal session-derived group (only the fields the merge reads matter). */function group(key: string, over: Partial<WorkspaceGroup<{ id: string }>> = {}) {@@ -113,24 +112,31 @@ describe("setWorkspaceAlias", () => {});describe("persisted registry (per-Project localStorage)", () => {- it("round-trips entries (alias included) per Project; nothing stored / no Project is empty; reading never writes", () => {- const s = memStorage();+ it("round-trips entries (alias and machine included) per Project; nothing stored / no Project is empty; reading never writes", () => {+ const s = memoryStorage();expect(loadWorkspaceRegistry("p1", s)).toEqual([]);expect(loadWorkspaceRegistry(null, s)).toEqual([]);expect(s.map.size).toBe(0);saveWorkspaceRegistry(null, [{ path: "/x" }], s);expect(s.map.size).toBe(0);- saveWorkspaceRegistry("p1", [{ path: "/srv/beta", alias: "Beta" }, { path: "/srv/app" }], s);+ saveWorkspaceRegistry(+ "p1",+ [+ { path: "/srv/beta", alias: "Beta" },+ { path: "/srv/app", machineId: "noeSE0FFHhNXl2J5" },+ ],+ s,+ );saveWorkspaceRegistry("p2", [{ path: "/other" }], s);expect(loadWorkspaceRegistry("p1", s)).toEqual([{ path: "/srv/beta", alias: "Beta" },- { path: "/srv/app" },+ { path: "/srv/app", machineId: "noeSE0FFHhNXl2J5" },]);expect(loadWorkspaceRegistry("p2", s)).toEqual([{ path: "/other" }]);});it("still loads the branch's earlier string-only shape, mixed with entry objects", () => {- const s = memStorage();+ const s = memoryStorage();s.map.set(workspaceRegistryKey("p1"),'["/old/one/", {"path": "/new/two", "alias": " Two "}, "/old/one"]',@@ -142,7 +148,7 @@ describe("persisted registry (per-Project localStorage)", () => {});it("malformed values degrade to empty; junk elements and junk aliases are dropped", () => {- const s = memStorage();+ const s = memoryStorage();for (const raw of ["{not json", '"x"', "42", "null", "{}", ""]) {s.map.set(workspaceRegistryKey("p1"), raw);expect(loadWorkspaceRegistry("p1", s)).toEqual([]);@@ -155,14 +161,7 @@ describe("persisted registry (per-Project localStorage)", () => {});it("storage throwing (quota/private mode): save does not throw, load yields empty", () => {- const broken: WorkspaceRegistryStorage = {- getItem: () => {- throw new Error("denied");- },- setItem: () => {- throw new Error("denied");- },- };+ const broken = blockedStorage();expect(() => saveWorkspaceRegistry("p1", [{ path: "/x" }], broken)).not.toThrow();expect(loadWorkspaceRegistry("p1", broken)).toEqual([]);});@@ -219,12 +218,9 @@ describe("mergeRegisteredWorkspaces", () => {});describe("a workspace's machine", () => {- it("records the machine a directory was picked on", () => {+ it("records the machine a directory was picked on, and none for this machine (as older entries read)", () => {const entries = registerWorkspace([], "/srv/app", "noeSE0FFHhNXl2J5");expect(entries[0]).toEqual({ path: "/srv/app", machineId: "noeSE0FFHhNXl2J5" });- });-- it("leaves it absent for this machine, which is what every older entry looks like", () => {expect(registerWorkspace([], "/srv/app")[0]).toEqual({ path: "/srv/app" });});@@ -249,43 +245,20 @@ describe("a workspace's machine", () => {expect(registerWorkspace(local, "/srv/app")).toBe(local);});- it("round-trips through storage, and tolerates a stored entry without one", () => {- const store = new Map<string, string>();- const storage = {- getItem: (k: string) => store.get(k) ?? null,- setItem: (k: string, v: string) => void store.set(k, v),- };- saveWorkspaceRegistry(- "p",- [{ path: "/a", machineId: "noeSE0FFHhNXl2J5" }, { path: "/b" }],- storage,- );- expect(loadWorkspaceRegistry("p", storage)).toEqual([- { path: "/a", machineId: "noeSE0FFHhNXl2J5" },- { path: "/b" },- ]);- });-it("drops an empty machine id rather than storing a workspace on nothing", () => {- const store = new Map<string, string>();- store.set(workspaceRegistryKey("p"), JSON.stringify([{ path: "/a", machineId: "" }]));- const storage = {- getItem: (k: string) => store.get(k) ?? null,- setItem: (k: string, v: string) => void store.set(k, v),- };+ const storage = memoryStorage({+ [workspaceRegistryKey("p")]: JSON.stringify([{ path: "/a", machineId: "" }]),+ });expect(loadWorkspaceRegistry("p", storage)).toEqual([{ path: "/a" }]);});it("loads both machines' entries for one path (a path-only dedup here lost one for good)", () => {- const store = new Map<string, string>();- store.set(- workspaceRegistryKey("p"),- JSON.stringify([{ path: "/srv/app", machineId: "noeSE0FFHhNXl2J5" }, { path: "/srv/app" }]),- );- const storage = {- getItem: (k: string) => store.get(k) ?? null,- setItem: (k: string, v: string) => void store.set(k, v),- };+ const storage = memoryStorage({+ [workspaceRegistryKey("p")]: JSON.stringify([+ { path: "/srv/app", machineId: "noeSE0FFHhNXl2J5" },+ { path: "/srv/app" },+ ]),+ });expect(loadWorkspaceRegistry("p", storage)).toEqual([{ path: "/srv/app", machineId: "noeSE0FFHhNXl2J5" },{ path: "/srv/app" },diff --git a/packages/web/test/workspace-tree.test.ts b/packages/web/test/workspace-tree.test.tsindex 0db93bd1..a02cd2e1 100644--- a/packages/web/test/workspace-tree.test.ts+++ b/packages/web/test/workspace-tree.test.ts@@ -1,13 +1,30 @@/**- * Files panel logic (lib/workspace-tree.ts): the tree's rows from lazily loaded listings,- * the rows a whole-Workspace search draws, where a drop lands, the narrow-layout decision and- * the tree pane's width bounds, which files count as text (by name, or by their bytes when the- * name says nothing) and how the read-only file browser previews one, the preferences' tolerant- * parses, when leaving the editor has to ask, and what the panel's "add to conversation" puts in- * the composer.+ * The Files panel's logic (lib/workspace-tree.ts).+ *+ * - A path names its parent and the directories above it; expanding to a file opens the way+ * down without treating the file as a directory, and collapsing closes only that directory.+ * - Listings sort directories before files by name; an entry upserts into sorted position,+ * replacing a same-named one, starting a listing where there was none, never mutating.+ * - The tree's rows walk open directories depth first, number each row within its directory,+ * and mark an open directory still loading or empty; a whole-Workspace search draws a flat+ * list of hits named by their whole path, carrying size and time.+ * - A drop lands on a folder row, in a file row's directory, or in the current directory.+ * - Below the width threshold the panel is one column (two panes while unmeasured); an+ * undragged tree takes about a third within readable bounds, and a dragged width is clamped.+ * - A file's kind comes from its name, or from its bytes when the name says nothing (UTF-8 text+ * cut mid-character is still text; NUL, control-heavy or non-UTF-8 bytes are not); the+ * read-only browser reads HTML as source and an unknown name as unsupported; only whole+ * text-like previews offer the editor, and leaving typed changes asks first.+ * - The tree width, soft wrap and tree visibility preferences parse tolerantly, keep a stored+ * explicit answer over a new default, round-trip, and fall back when storage throws.+ * - A line range is written as an editor writes it; a directory reference carries a trailing+ * slash.+ * - "Add to conversation" hands the composer a reference (the text it will send and its file),+ * still fenced as a quotation, never text for the draft.*/import { describe, expect, it } from "vitest";import type { WorkspaceFileEntry, WorkspaceSearchHit } from "@prismshadow/penguin-server/api";+import { blockedStorage, memoryStorage } from "./helpers/storage";import {type ComposerReference,type Listings,@@ -275,27 +292,6 @@ describe("editing", () => {});});-/** In-memory stand-in for localStorage, and one that throws the way blocked site data does. */-function memPreferences(): {- getItem: (k: string) => string | null;- setItem: (k: string, v: string) => void;-} {- const store = new Map<string, string>();- return {- getItem: (key: string) => store.get(key) ?? null,- setItem: (key: string, value: string) => void store.set(key, value),- };-}--const brokenPreferences = {- getItem: (): string | null => {- throw new Error("blocked");- },- setItem: (): void => {- throw new Error("blocked");- },-};-describe("tree width preference", () => {it("takes a positive integer and treats everything else as unset", () => {expect(parseTreeWidth(null)).toBeNull();@@ -307,12 +303,12 @@ describe("tree width preference", () => {});it("round-trips through storage and reads as unset when storage throws", () => {- const storage = memPreferences();+ const storage = memoryStorage();expect(readTreeWidth(storage)).toBeNull();writeTreeWidth(233.4, storage);expect(readTreeWidth(storage)).toBe(233);- expect(readTreeWidth(brokenPreferences)).toBeNull();- expect(() => writeTreeWidth(200, brokenPreferences)).not.toThrow();+ expect(readTreeWidth(blockedStorage())).toBeNull();+ expect(() => writeTreeWidth(200, blockedStorage())).not.toThrow();});});@@ -326,14 +322,14 @@ describe("soft wrap preference", () => {});it("round-trips through storage and reads as on when storage throws", () => {- const storage = memPreferences();+ const storage = memoryStorage();expect(readWrapLines(storage)).toBe(true);writeWrapLines(false, storage);expect(readWrapLines(storage)).toBe(false);writeWrapLines(true, storage);expect(readWrapLines(storage)).toBe(true);- expect(readWrapLines(brokenPreferences)).toBe(true);- expect(() => writeWrapLines(false, brokenPreferences)).not.toThrow();+ expect(readWrapLines(blockedStorage())).toBe(true);+ expect(() => writeWrapLines(false, blockedStorage())).not.toThrow();});});@@ -347,14 +343,14 @@ describe("tree visibility preference", () => {});it("round-trips through storage and defaults to shown when storage throws", () => {- const storage = memPreferences();+ const storage = memoryStorage();expect(readTreeVisible(storage)).toBe(true);writeTreeVisible(false, storage);expect(readTreeVisible(storage)).toBe(false);writeTreeVisible(true, storage);expect(readTreeVisible(storage)).toBe(true);- expect(readTreeVisible(brokenPreferences)).toBe(true);- expect(() => writeTreeVisible(false, brokenPreferences)).not.toThrow();+ expect(readTreeVisible(blockedStorage())).toBe(true);+ expect(() => writeTreeVisible(false, blockedStorage())).not.toThrow();});});diff --git a/packages/web/vitest.config.ts b/packages/web/vitest.config.tsindex ac37bb60..8f2033a7 100644--- a/packages/web/vitest.config.ts+++ b/packages/web/vitest.config.ts@@ -1,5 +1,6 @@/**- * Vitest config: node environment, tests pure logic only (stream-model / task-stats / format), no DOM tests.+ * Vitest config: node environment, no DOM. Tests drive the app's logic, its stores and the+ * components that render to static markup; e2e/ (Playwright, `test:e2e`) is excluded.* Kept separate from vite.config.ts: vitest's bundled vite 5 types conflict with this package's vite 7* plugin types, and tests don't need the plugin anyway.*/@@ -8,7 +9,10 @@ import { defineConfig } from "vitest/config";export default defineConfig({test: {environment: "node",- // Only run unit tests under test/; e2e/ (Playwright, has its own test:e2e) is excluded from vitest.include: ["test/**/*.test.ts"],+ // Every vi.stubGlobal (fetch, localStorage, …) is undone before the next test starts.+ unstubGlobals: true,+ // `vitest run --coverage`: branch and line coverage of the app's own source.+ coverage: { provider: "v8", include: ["src/**"] },},});diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 44af2039..57cdacf5 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -664,6 +664,9 @@ importers:'@vitejs/plugin-react':specifier: ^4.5.0version: 4.7.0([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))+ '@vitest/coverage-v8':+ specifier: 3.2.7+ version: 3.2.7([email protected])([email protected](@types/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))tailwindcss:specifier: ^4.1.0version: 4.3.2