Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

chore(web): enforce v2 frontend release gates

Bingxi Zhao (Frank)23a5e0601dff
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
index e03ffc132..46e98a1d4 100644
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -75,29 +75,31 @@ jobs:
working-directory: web
run: npm ci --legacy-peer-deps
- - name: Check generated frontend contracts
+ - name: Run complete deterministic frontend gate
working-directory: web
- run: npm run contracts:check
+ run: npm run check
- - name: Typecheck frontend
- working-directory: web
- run: npm run typecheck
-
- - name: Run frontend node tests
- working-directory: web
- run: npm run test:node
-
- - name: Run frontend component tests
+ - name: Install Playwright Chromium
working-directory: web
- run: npm run test:unit
+ run: npx playwright install --with-deps chromium
- # eslint was not a gate, so #921 landed two real React violations: a
- # predicate named like a hook (tripping rules-of-hooks) and a synchronous
- # setState inside an effect. Errors only — the repo still carries i18n
- # literal warnings, and turning those red is a separate cleanup.
- - name: Lint frontend
+ - name: Run interaction, accessibility, and visual matrix audits
working-directory: web
- run: npx eslint .
+ run: |
+ npm start -- --hostname 127.0.0.1 --port 3000 > /tmp/deeptutor-web-audit.log 2>&1 &
+ audit_server_pid=$!
+ trap 'kill "$audit_server_pid"' EXIT
+ for attempt in $(seq 1 100); do
+ if curl --fail --silent http://127.0.0.1:3000/ > /dev/null; then
+ break
+ fi
+ if ! kill -0 "$audit_server_pid" 2>/dev/null; then
+ cat /tmp/deeptutor-web-audit.log
+ exit 1
+ fi
+ sleep 0.1
+ done
+ WEB_BASE_URL=http://127.0.0.1:3000 npm run audit
multi-worker-web:
name: Four-worker browser acceptance
diff --git a/docs/plans/2026-09-01-frontend-stabilization-v2-acceptance.md b/docs/plans/2026-09-01-frontend-stabilization-v2-acceptance.md
new file mode 100644
index 000000000..d70583745
--- /dev/null
+++ b/docs/plans/2026-09-01-frontend-stabilization-v2-acceptance.md
@@ -0,0 +1,95 @@
+# DeepTutor v2 Frontend Acceptance Record
+
+**Recorded:** 2026-09-01
+
+**Branch:** `codex/frontend-stabilization-v2`
+
+**Scope:** Frontend stabilization, v2 turn protocol migration, feature-boundary cleanup, lifecycle UX unification, responsive/accessibility repair, and release-gate hardening.
+
+## Decision
+
+The frontend implementation is complete and suitable for integration with the stabilized backend. Final release approval remains conditional on running the registered multi-worker browser suite against the real four-worker Redis fixture and completing the normal canary rollout. This document does not substitute mocked transport evidence for that external proof.
+
+## Architecture acceptance
+
+- Browser chat traffic uses the generated v2 turn protocol through `TurnRuntimeClient` and `UnifiedTurnClient`.
+- The obsolete browser `/api/v1/chat` transport, recovery client, legacy chat shells, and compatibility barrels are removed. A source guard prevents them from returning.
+- Chat state is an external store with selector subscriptions. A 500-content-event test records 501 message renders (initial plus each event) and exactly one sidebar render.
+- Chat, Settings, Knowledge, Co-Writer, Reading, Mastery, and Watching are represented as explicit route/feature boundaries rather than route-owned cross-feature implementations.
+- Terminal, retryable, cancellation-pending, waiting-for-input, reconnecting, and foreign-observer states share the same turn lifecycle model and status vocabulary.
+- Runtime health and protocol compatibility are visible to the user without exposing credentials or raw internal diagnostics.
+
+## Build and performance gates
+
+Next.js 16 no longer exposes useful route-level data in the old client-reference-manifest shape. `route_budgets.mjs` now starts the production server, reads the scripts actually loaded by each route, and subtracts the framework and common root shell. These are raw loaded JavaScript bytes, not transfer-size claims.
+
+| Surface | Measured JS | Budget |
+| --- | ---: | ---: |
+| Landing `/` | 274 KB | 300 KB |
+| Chat | 978 KB | 1,020 KB |
+| Settings | 807 KB | 840 KB |
+| Knowledge | 517 KB | 540 KB |
+| Co-Writer index | 292 KB | 320 KB |
+| Co-Writer document | 493 KB | 515 KB |
+| Reading | 1,083 KB | 1,120 KB |
+| Mastery | 949 KB | 980 KB |
+| Root app shell | 373 KB | 390 KB |
+
+The production build generates 73 static pages. The following large implementation modules remain optimization debt rather than boundary violations:
+
+| Lines | Module |
+| ---: | --- |
+| 2,830 | `features/chat/components/ChatWorkspace.tsx` |
+| 2,703 | `features/chat/trace/TracePresentation.tsx` |
+| 2,475 | `features/co-writer/components/CoWriterWorkspace.tsx` |
+| 2,363 | `features/chat/ChatStateAdapter.tsx` |
+
+Future size work should split these by interaction path without recreating cross-feature state ownership.
+
+## Automated acceptance matrix
+
+`npm run check` is the deterministic local and CI release gate, in this order:
+
+1. generated protocol drift and contract compatibility;
+2. architecture dependency rules;
+3. TypeScript;
+4. Node test suite;
+5. rendered Vitest suite;
+6. ESLint;
+7. i18n parity/audit;
+8. production build;
+9. route budgets.
+
+The browser audit covers semantic landmark/accessibility rules, keyboard-reachable controls, focus return, reduced motion, responsive Reading annotations, and the complete video-learning flow. The release UI matrix checks all six primary surfaces across Snow/Cream/Dark/Glass, English/Chinese, 390 px mobile, tablet, desktop, and a 200%-zoom-equivalent layout viewport. Every matrix case checks horizontal overflow, keyboard focus where controls are present, empty credential fields, and secret-shaped DOM text. CI starts the built production frontend and runs this browser gate after `npm run check`. The critical turn browser suite covers reconnect, cancellation acknowledgement, waiting input, retryable worker loss, reload replay, and foreign observation. Desktop and iPhone 13 reduced-motion projects are registered.
+
+The multi-worker suite defines six scenarios across two browser projects (12 cases) and refuses to run unless its fixture reports exactly four workers plus healthy Redis. CI runs it on schedule or manual dispatch when `DEEPTUTOR_MULTI_WORKER_E2E_URL` is configured, and uploads JSON evidence.
+
+## Recorded verification
+
+| Gate | Result | Observed duration |
+| --- | --- | ---: |
+| Protocol drift | Pass | included in full gate |
+| Architecture | Pass — 733 modules, 1,902 dependencies, 0 violations | included in full gate |
+| Node tests | 928 passed | 2.47 s test process |
+| Rendered tests | 31 passed | 1.53 s |
+| ESLint | 0 errors, 57 existing warnings | included in full gate |
+| i18n | parity passed; audit reports 36 possible literals for follow-up | included in full gate |
+| Production build | 73 pages | 9.8 s compile + 8.7 s TypeScript |
+| Route budgets | 9/9 passed | included in full gate |
+| Focused interaction/accessibility audit | 11/11 passed | 6.2 s |
+| Release UI matrix | 192 surface/configuration checks passed | 16.2 s |
+| Four-worker browser suite | 12 cases registered; intentionally skipped without fixture | external gate |
+
+The i18n audit is a heuristic report and its current candidate list includes code examples, product names, and other known non-copy literals; parity and lint remain the enforced correctness gates. The 57 lint warnings are pre-existing warning-level debt, with no lint errors introduced by this work.
+
+## External release gate
+
+Before declaring the combined frontend/backend release ready:
+
+1. expose the deterministic fixture controls used by `tests/e2e/fixtures/runtime.ts` from an isolated test deployment;
+2. set `DEEPTUTOR_MULTI_WORKER_E2E_URL` and `DEEPTUTOR_MULTI_WORKER_E2E=1`;
+3. run `npm run test:e2e:multi-worker` and retain the evidence artifact;
+4. canary the compatibility window and confirm no v1 browser requests, sequence gaps, duplicate events, or credential-bearing logs;
+5. remove any backend compatibility window only after the canary remains clean.
+
+Until those steps run against the backend deployment, the honest status is **frontend accepted; integrated multi-worker release pending**.
diff --git a/docs/plans/2026-09-01-frontend-stabilization-v2-baseline.md b/docs/plans/2026-09-01-frontend-stabilization-v2-baseline.md
index f945f256e..059cd084b 100644
--- a/docs/plans/2026-09-01-frontend-stabilization-v2-baseline.md
+++ b/docs/plans/2026-09-01-frontend-stabilization-v2-baseline.md
@@ -155,3 +155,9 @@ npm run perf:check
```
The lifecycle browser audit is registered under the `critical-turns` Playwright project. It remains explicitly skipped until the deterministic backend fixture is delivered in the multi-worker acceptance phase.
+
+## 7. Post-refactor comparison
+
+The completed frontend pass replaces the obsolete manifest-based bundle estimate with an HTML-entry measurement from a production Next.js server. The two size tables therefore use different methods and must not be interpreted as a byte-for-byte regression chart. The new measurement is reproducible, route-specific, and enforced by `npm run perf:check`.
+
+The final implementation and gate evidence are recorded in [`2026-09-01-frontend-stabilization-v2-acceptance.md`](./2026-09-01-frontend-stabilization-v2-acceptance.md). In particular, the old `/api/v1/chat` browser transport and compatibility surfaces have been removed, route shells now sit behind explicit feature boundaries, and a 500-event selector test proves that streamed content does not rerender the session sidebar.
diff --git a/web/components/watching/WatchingPane.tsx b/web/components/watching/WatchingPane.tsx
index 0849aee96..25001ca54 100644
--- a/web/components/watching/WatchingPane.tsx
+++ b/web/components/watching/WatchingPane.tsx
@@ -488,11 +488,23 @@ export function WatchingPane({ onClose }: { onClose(): void }) {
{tab === "transcript" ? (
material.transcript.status !== "ready" ? (
<div className="rounded-lg border border-[var(--border)] p-4 text-sm text-[var(--muted-foreground)]">
- {t(
- "Transcript learning is unavailable ({{reason}}). Playback still works, but Explain here is disabled.",
- {
- reason: material.transcript.reason || t("no captions"),
- },
+ <p>
+ {t(
+ "Transcript learning is unavailable ({{reason}}). Playback still works, but Explain here is disabled.",
+ {
+ reason: material.transcript.reason || t("no captions"),
+ },
+ )}
+ </p>
+ {material.playback.provider === "invidious" && (
+ <button
+ type="button"
+ onClick={() => void retryTranscript()}
+ disabled={loading}
+ className="mt-3 rounded border border-[var(--border)] px-2 py-1 font-medium text-[var(--foreground)] disabled:opacity-50"
+ >
+ {t("Retry captions")}
+ </button>
)}
</div>
) : (
@@ -665,16 +677,6 @@ export function WatchingPane({ onClose }: { onClose(): void }) {
) : (
!notesError && <p className="text-sm">{t("No notes yet.")}</p>
)}
- {material.playback.provider === "invidious" && (
- <button
- type="button"
- onClick={() => void retryTranscript()}
- disabled={loading}
- className="mt-3 rounded border border-[var(--border)] px-2 py-1 text-sm font-medium disabled:opacity-50"
- >
- {t("Retry captions")}
- </button>
- )}
</div>
)}
</div>
diff --git a/web/package.json b/web/package.json
index 0c6e9f86a..1a94a2081 100644
--- a/web/package.json
+++ b/web/package.json
@@ -14,7 +14,7 @@
"test:unit:watch": "vitest",
"contracts:generate": "node ./scripts/generate-contracts.mjs",
"contracts:check": "node ./scripts/generate-contracts.mjs --check",
- "check:fast": "npm run contracts:check && npm run typecheck && npm run test:node && npm run test:unit && npm run lint && npm run i18n:check",
+ "check:fast": "npm run contracts:check && npm run architecture:check && npm run typecheck && npm run test:node && npm run test:unit && npm run lint && npm run i18n:check",
"check": "npm run check:fast && npm run build && npm run perf:check",
"perf:check": "node ./scripts/route_budgets.mjs",
"build:perf": "npm run build && npm run perf:check",
@@ -26,6 +26,8 @@
"audit": "playwright test --project=ui-audit",
"audit:ui": "playwright test --ui --project=ui-audit",
"audit:report": "playwright show-report",
+ "test:e2e:critical": "playwright test --project=critical-turns",
+ "test:e2e:multi-worker": "playwright test --project=multi-worker-turns-desktop --project=multi-worker-turns-mobile",
"build:brand-icons": "tsx ./scripts/build-brand-icons.mts"
},
"dependencies": {
diff --git a/web/scripts/route_budgets.mjs b/web/scripts/route_budgets.mjs
index 886bb96f2..f9086edb8 100644
--- a/web/scripts/route_budgets.mjs
+++ b/web/scripts/route_budgets.mjs
@@ -1,130 +1,194 @@
-import fs from "fs";
-import path from "path";
-import vm from "vm";
-
-const APP_SERVER_DIR = path.resolve(".next/server/app");
-const APP_OUTPUT_DIR = path.resolve(".next");
-
-const ROUTE_BUDGETS_KB = {
- "/": 700,
- "/co-writer": 200,
- "/co-writer/[docId]": 700,
- "/knowledge": 450,
- "/memory": 450,
- "/settings": 180,
-};
-
-const ROOT_SHELL_BUDGET_KB = 220;
-
-function walkManifestFiles(rootDir) {
- const entries = [];
- for (const item of fs.readdirSync(rootDir, { withFileTypes: true })) {
- const fullPath = path.join(rootDir, item.name);
- if (item.isDirectory()) {
- entries.push(...walkManifestFiles(fullPath));
- continue;
- }
- if (item.name.endsWith("_client-reference-manifest.js")) {
- entries.push(fullPath);
- }
+import { spawn } from "node:child_process";
+import fs from "node:fs";
+import net from "node:net";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+
+const WEB_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
+const NEXT_OUTPUT_DIR = path.join(WEB_ROOT, ".next");
+const BUILD_MANIFEST_PATH = path.join(NEXT_OUTPUT_DIR, "build-manifest.json");
+const NEXT_BIN = path.join(WEB_ROOT, "node_modules", "next", "dist", "bin", "next");
+
+const ROUTE_TARGETS = [
+ { route: "/", requestPath: "/", budgetKb: 300 },
+ { route: "/home/[[...sessionId]]", requestPath: "/home/perf-budget", budgetKb: 1_020 },
+ { route: "/settings", requestPath: "/settings", budgetKb: 840 },
+ { route: "/knowledge", requestPath: "/knowledge", budgetKb: 540 },
+ { route: "/co-writer", requestPath: "/co-writer", budgetKb: 320 },
+ { route: "/co-writer/[docId]", requestPath: "/co-writer/perf-budget", budgetKb: 515 },
+ {
+ route: "/reading/[workspaceId]/[[...sessionId]]",
+ requestPath: "/reading/perf-budget",
+ budgetKb: 1_120,
+ },
+ {
+ route: "/mastery/[pathId]/study/[[...sessionId]]",
+ requestPath: "/mastery/perf-budget/study",
+ budgetKb: 980,
+ },
+];
+
+const ROOT_SHELL_BUDGET_KB = 390;
+const SERVER_TIMEOUT_MS = 20_000;
+
+function assertBuildPresent() {
+ if (!fs.existsSync(BUILD_MANIFEST_PATH)) {
+ throw new Error("Missing .next build output. Run `npm run build` before `npm run perf:check`.");
}
- return entries.sort();
}
-function evaluateManifest(filePath) {
- const context = { globalThis: { __RSC_MANIFEST: {} } };
- vm.createContext(context);
- vm.runInContext(fs.readFileSync(filePath, "utf8"), context);
- const manifestEntries = Object.entries(context.globalThis.__RSC_MANIFEST);
- if (manifestEntries.length !== 1) {
- throw new Error(`Expected exactly one manifest in ${filePath}`);
- }
- const [manifestKey, manifest] = manifestEntries[0];
- return { manifestKey, manifest };
+function findAvailablePort() {
+ return new Promise((resolve, reject) => {
+ const server = net.createServer();
+ server.unref();
+ server.once("error", reject);
+ server.listen(0, "127.0.0.1", () => {
+ const address = server.address();
+ const port = typeof address === "object" && address ? address.port : 0;
+ server.close((error) => (error ? reject(error) : resolve(port)));
+ });
+ });
}
-function normalizePublicRoute(manifestKey) {
- const withoutGroups = manifestKey.replace(/\/\([^/]+\)/g, "");
- const withoutPageSuffix = withoutGroups.replace(/\/page$/, "");
- return withoutPageSuffix || "/";
+async function waitForServer(baseUrl, processState) {
+ const deadline = Date.now() + SERVER_TIMEOUT_MS;
+ while (Date.now() < deadline) {
+ if (processState.exited) {
+ throw new Error(`Next server exited before readiness:\n${processState.output}`);
+ }
+ try {
+ const response = await fetch(`${baseUrl}/login`);
+ if (response.ok) return;
+ } catch {
+ // Startup races are expected until the listener is ready.
+ }
+ await new Promise((resolve) => setTimeout(resolve, 100));
+ }
+ throw new Error(`Timed out waiting for the production server:\n${processState.output}`);
}
-function resolveChunkSize(chunkPath) {
- const filePath = path.join(APP_OUTPUT_DIR, chunkPath.replace(/^\/+/, ""));
- return fs.existsSync(filePath) ? fs.statSync(filePath).size : 0;
+async function startBuildServer() {
+ const port = await findAvailablePort();
+ const baseUrl = `http://127.0.0.1:${port}`;
+ const child = spawn(
+ process.execPath,
+ [NEXT_BIN, "start", "--hostname", "127.0.0.1", "--port", String(port)],
+ {
+ cwd: WEB_ROOT,
+ env: {
+ ...process.env,
+ NEXT_TELEMETRY_DISABLED: "1",
+ DEEPTUTOR_API_BASE_URL: "http://127.0.0.1:9",
+ },
+ stdio: ["ignore", "pipe", "pipe"],
+ },
+ );
+ const state = { exited: false, output: "" };
+ const capture = (chunk) => {
+ state.output = `${state.output}${String(chunk)}`.slice(-8_000);
+ };
+ child.stdout.on("data", capture);
+ child.stderr.on("data", capture);
+ child.once("exit", () => {
+ state.exited = true;
+ });
+ await waitForServer(baseUrl, state);
+ return { baseUrl, child };
}
-function sumChunkSizes(chunkPaths) {
- return chunkPaths.reduce((total, chunkPath) => total + resolveChunkSize(chunkPath), 0);
+function scriptChunks(html, baseUrl) {
+ const chunks = new Set();
+ for (const match of html.matchAll(/<script[^>]+src="([^"]+\.js(?:\?[^\"]*)?)"/g)) {
+ const pathname = decodeURIComponent(new URL(match[1], baseUrl).pathname);
+ const relative = pathname.replace(/^\/_next\//, "");
+ if (relative.startsWith("static/") && relative.endsWith(".js")) chunks.add(relative);
+ }
+ return chunks;
}
-if (!fs.existsSync(APP_SERVER_DIR)) {
- console.error("Missing .next/server/app. Run `npm run build` before `npm run perf:check`.");
- process.exit(1);
+async function loadRouteChunks(baseUrl, requestPath) {
+ const response = await fetch(`${baseUrl}${requestPath}`);
+ if (!response.ok) {
+ throw new Error(`${requestPath} returned HTTP ${response.status} during route measurement`);
+ }
+ return scriptChunks(await response.text(), baseUrl);
}
-const manifestFiles = walkManifestFiles(APP_SERVER_DIR).filter(
- (filePath) => !filePath.includes("_global-error") && !filePath.includes("_not-found"),
-);
-
-const routeRows = [];
-let rootShellSize = 0;
-
-for (const manifestFile of manifestFiles) {
- const { manifestKey, manifest } = evaluateManifest(manifestFile);
- const route = normalizePublicRoute(manifestKey);
- const entryFiles = manifest.entryJSFiles;
+function intersection(sets) {
+ if (sets.length === 0) return new Set();
+ return sets.slice(1).reduce(
+ (shared, current) => new Set([...shared].filter((item) => current.has(item))),
+ new Set(sets[0]),
+ );
+}
- const rootLayoutFiles = entryFiles["[project]/app/layout"] || [];
- if (!rootShellSize && rootLayoutFiles.length > 0) {
- rootShellSize = sumChunkSizes(rootLayoutFiles);
- }
- const rootLayoutChunks = new Set(rootLayoutFiles);
+function difference(source, ...excludedSets) {
+ const excluded = new Set(excludedSets.flatMap((items) => [...items]));
+ return new Set([...source].filter((item) => !excluded.has(item)));
+}
- const routeEntryKey = Object.keys(entryFiles).find(
- (key) => key.startsWith("[project]/app/") && key.endsWith("/page") && !key.includes("/layout"),
- );
- if (!routeEntryKey) {
- continue;
+function chunkSize(chunkPath) {
+ const filePath = path.join(NEXT_OUTPUT_DIR, chunkPath);
+ if (!fs.existsSync(filePath)) {
+ throw new Error(`Build HTML references missing client chunk ${chunkPath}`);
}
+ return fs.statSync(filePath).size;
+}
- const chunkPaths = (entryFiles[routeEntryKey] || []).filter(
- (chunkPath) => !rootLayoutChunks.has(chunkPath),
- );
- routeRows.push({
- route,
- sizeBytes: sumChunkSizes(chunkPaths),
- chunks: chunkPaths.map((chunkPath) => path.basename(chunkPath)),
- });
+function sumChunkSizes(chunks) {
+ return [...chunks].reduce((total, chunk) => total + chunkSize(chunk), 0);
}
-let hasFailure = false;
+function kb(bytes) {
+ return Math.round(bytes / 1024);
+}
-console.log("Route budgets (excluding root shell):");
-for (const row of routeRows) {
- const sizeKb = Math.round(row.sizeBytes / 1024);
- const budget = ROUTE_BUDGETS_KB[row.route];
- const status = budget && sizeKb > budget ? "FAIL" : "OK";
- if (status === "FAIL") {
- hasFailure = true;
- }
+function printRow(label, sizeKb, budgetKb) {
+ const failed = sizeKb > budgetKb;
console.log(
- `${status.padEnd(4)} ${row.route.padEnd(12)} ${String(sizeKb).padStart(4)}KB` +
- (budget ? ` / budget ${budget}KB` : ""),
+ `${(failed ? "FAIL" : "OK").padEnd(4)} ${label.padEnd(47)} ${String(sizeKb).padStart(4)}KB / budget ${budgetKb}KB`,
);
+ return failed;
}
-if (rootShellSize) {
- const rootShellKb = Math.round(rootShellSize / 1024);
- const rootStatus = rootShellKb > ROOT_SHELL_BUDGET_KB ? "FAIL" : "OK";
- if (rootStatus === "FAIL") {
- hasFailure = true;
+async function main() {
+ assertBuildPresent();
+ const buildManifest = JSON.parse(fs.readFileSync(BUILD_MANIFEST_PATH, "utf8"));
+ const frameworkChunks = new Set([
+ ...(buildManifest.rootMainFiles || []),
+ ...(buildManifest.polyfillFiles || []),
+ ]);
+ const server = await startBuildServer();
+
+ try {
+ const rows = [];
+ for (const target of ROUTE_TARGETS) {
+ rows.push({ ...target, chunks: await loadRouteChunks(server.baseUrl, target.requestPath) });
+ }
+ // Auth uses the root layout but neither utility nor workspace layout, so
+ // it prevents feature shells from being misclassified as the root shell.
+ const authChunks = await loadRouteChunks(server.baseUrl, "/login");
+ const appShellChunks = difference(
+ intersection([...rows.map((row) => row.chunks), authChunks]),
+ frameworkChunks,
+ );
+
+ console.log("Route budgets (raw production JS; framework and root app shell excluded):");
+ let failed = false;
+ for (const row of rows) {
+ const routeChunks = difference(row.chunks, frameworkChunks, appShellChunks);
+ failed = printRow(row.route, kb(sumChunkSizes(routeChunks)), row.budgetKb) || failed;
+ }
+ failed =
+ printRow("root-app-shell", kb(sumChunkSizes(appShellChunks)), ROOT_SHELL_BUDGET_KB) || failed;
+
+ if (failed) process.exitCode = 1;
+ } finally {
+ server.child.kill("SIGTERM");
}
- console.log(
- `${rootStatus.padEnd(4)} ${"root-shell".padEnd(12)} ${String(rootShellKb).padStart(4)}KB / budget ${ROOT_SHELL_BUDGET_KB}KB`,
- );
}
-if (hasFailure) {
- process.exit(1);
-}
+main().catch((error) => {
+ console.error(error instanceof Error ? error.message : error);
+ process.exitCode = 1;
+});
diff --git a/web/tests/e2e/compliance-and-ux.audit.ts b/web/tests/e2e/compliance-and-ux.audit.ts
index 45dfccba5..91c68da55 100644
--- a/web/tests/e2e/compliance-and-ux.audit.ts
+++ b/web/tests/e2e/compliance-and-ux.audit.ts
@@ -57,7 +57,15 @@ test.describe("Compliance :: Accessibility & Semantics", () => {
const text = (a.textContent || "").trim();
const aria = (a.getAttribute("aria-label") || "").trim();
const title = (a.getAttribute("title") || "").trim();
- return text.length === 0 && aria.length === 0 && title.length === 0;
+ const imageName = Array.from(a.querySelectorAll("img")).some(
+ (image) => (image.getAttribute("alt") || "").trim().length > 0,
+ );
+ return (
+ text.length === 0 &&
+ aria.length === 0 &&
+ title.length === 0 &&
+ !imageName
+ );
}).length,
);
expect(
diff --git a/web/tests/e2e/reading-w3c-annotations.audit.ts b/web/tests/e2e/reading-w3c-annotations.audit.ts
index 3a2c8e829..636d38588 100644
--- a/web/tests/e2e/reading-w3c-annotations.audit.ts
+++ b/web/tests/e2e/reading-w3c-annotations.audit.ts
@@ -1,5 +1,7 @@
import { expect, test } from "@playwright/test";
+const WORKSPACE_ID = "w3c-workspace";
+
const material = {
material_id: "w3c-material",
filename: "W3C Annotation Sample.txt",
@@ -16,6 +18,47 @@ const material = {
outline_text: "",
};
+const libraryMaterial = {
+ material_id: material.material_id,
+ content_id: material.material_id,
+ filename: material.filename,
+ title: material.title,
+ source_kind: "file",
+ source_url: "",
+ mime: material.mime,
+ render_mode: "text",
+ cover_url: "",
+ duration_seconds: 0,
+ status: "ready",
+ progress: 0,
+ error_code: "",
+ error_detail: "",
+ created_at: 1,
+ updated_at: 2,
+ last_opened_at: 2,
+ size_bytes: material.byte_size,
+ unit_count: material.unit_count,
+ collections: [],
+};
+
+const workspace = {
+ workspace_id: WORKSPACE_ID,
+ title: "W3C annotation regression",
+ description: "",
+ active_material_id: material.material_id,
+ created_at: 1,
+ updated_at: 2,
+ tabs: [
+ {
+ material: libraryMaterial,
+ tab_order: 0,
+ pinned: false,
+ opened: true,
+ added_at: 1,
+ },
+ ],
+};
+
const annotation = {
annotation_id: "annotation-1",
locator: 1,
@@ -77,6 +120,12 @@ test.beforeEach(async ({ page }) => {
});
}
if (path === "/api/v1/reading/extensions") return json([]);
+ if (path === `/api/v1/reading/workspaces/${WORKSPACE_ID}`) {
+ return json({ workspace, sessions: [] });
+ }
+ if (path === `/api/v1/reading/workspaces/${WORKSPACE_ID}/sessions`) {
+ return json({ sessions: [] });
+ }
if (path === "/api/v1/reading/materials") return json([material]);
if (path === "/api/v1/reading/materials/w3c-material") {
return json(material);
@@ -98,15 +147,7 @@ test.beforeEach(async ({ page }) => {
test("a rich text annotation reflows and activates its sidebar entry", async ({
page,
}) => {
- await page.goto("/home");
-
- await page.getByRole("button", { name: "Chat", exact: true }).click();
- await page
- .getByRole("button", { name: /Immersive Reading/ })
- .last()
- .click();
- await page.getByRole("button", { name: "Open a document to read" }).click();
- await page.getByText("W3C Annotation Sample.txt").click();
+ await page.goto(`/reading/${WORKSPACE_ID}`);
const highlight = page.locator(".r6o-annotation").first();
await expect(highlight).toBeVisible();
@@ -127,6 +168,12 @@ test("a rich text annotation reflows and activates its sidebar entry", async ({
.getByRole("button")
.filter({ hasText: "Wave behavior" });
await expect(sidebarEntry).toBeVisible();
+ await page.getByRole("button", { name: "Close reading companion" }).click();
+ await page
+ .getByRole("button", { name: "Collapse contents" })
+ .first()
+ .click();
+ await expect(page.getByRole("button", { name: "Close panels" })).toBeHidden();
const article = page.locator("article.r6o-annotatable");
const articleBox = await article.boundingBox();
const highlightBox = await highlight.boundingBox();
diff --git a/web/tests/e2e/release-ui-matrix.audit.ts b/web/tests/e2e/release-ui-matrix.audit.ts
new file mode 100644
index 000000000..5dff6c3e3
--- /dev/null
+++ b/web/tests/e2e/release-ui-matrix.audit.ts
@@ -0,0 +1,90 @@
+import { expect, test } from "@playwright/test";
+
+const BASE_URL = process.env.WEB_BASE_URL || "http://127.0.0.1:3300";
+
+const surfaces = [
+ ["Chat", "/home"],
+ ["Reading", "/reading"],
+ ["Mastery", "/mastery"],
+ ["Settings", "/settings"],
+ ["Knowledge", "/knowledge"],
+ ["Co-Writer", "/co-writer"],
+] as const;
+
+const themes = ["snow", "light", "dark", "glass"] as const;
+const languages = ["en", "zh"] as const;
+const viewports = [
+ ["mobile", { width: 390, height: 844 }],
+ // A 1440 px desktop at 200% browser zoom exposes roughly 720 CSS pixels.
+ ["desktop-200pct", { width: 720, height: 500 }],
+ ["tablet", { width: 820, height: 1180 }],
+ ["desktop", { width: 1440, height: 1000 }],
+] as const;
+
+for (const theme of themes) {
+ for (const language of languages) {
+ for (const [viewportName, viewport] of viewports) {
+ test(`${theme}/${language}/${viewportName} keeps all primary surfaces usable`, async ({
+ browser,
+ }) => {
+ const context = await browser.newContext({
+ viewport,
+ reducedMotion: "reduce",
+ });
+ await context.addInitScript(
+ ({ selectedTheme, selectedLanguage }) => {
+ localStorage.setItem("deeptutor-theme", selectedTheme);
+ localStorage.setItem("deeptutor-language", selectedLanguage);
+ },
+ { selectedTheme: theme, selectedLanguage: language },
+ );
+ const page = await context.newPage();
+
+ for (const [surface, path] of surfaces) {
+ await test.step(surface, async () => {
+ await page.goto(`${BASE_URL}${path}`, { waitUntil: "domcontentloaded" });
+ await expect(page.locator("body")).toBeVisible();
+ await page.waitForTimeout(250);
+
+ const rootClasses = await page.locator("html").getAttribute("class");
+ if (theme === "snow") expect(rootClasses).toContain("theme-snow");
+ if (theme === "dark") expect(rootClasses).toContain("dark");
+ if (theme === "glass") {
+ expect(rootClasses).toContain("dark");
+ expect(rootClasses).toContain("theme-glass");
+ }
+ if (theme === "light") {
+ expect(rootClasses || "").not.toMatch(/\bdark\b|\btheme-snow\b|\btheme-glass\b/);
+ }
+
+ const layout = await page.evaluate(() => ({
+ viewport: window.innerWidth,
+ documentWidth: document.documentElement.scrollWidth,
+ populatedPasswords: Array.from(
+ document.querySelectorAll<HTMLInputElement>('input[type="password"]'),
+ ).filter((input) => input.value.length > 0).length,
+ text: document.body.innerText,
+ }));
+ expect(
+ layout.documentWidth,
+ `${surface} overflows at ${theme}/${language}/${viewportName}`,
+ ).toBeLessThanOrEqual(layout.viewport + 1);
+ expect(layout.populatedPasswords).toBe(0);
+ expect(layout.text).not.toMatch(/\bsk-[A-Za-z0-9_-]{20,}\b|\bBearer\s+[A-Za-z0-9._-]{20,}/);
+
+ const focusables = page.locator(
+ 'a[href], button:not([disabled]), input:not([disabled]), textarea:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])',
+ );
+ if ((await focusables.count()) > 0) {
+ await page.keyboard.press("Tab");
+ const focusedTag = await page.evaluate(() => document.activeElement?.tagName);
+ expect(focusedTag).not.toBe("BODY");
+ }
+ });
+ }
+
+ await context.close();
+ });
+ }
+ }
+}
diff --git a/web/tests/e2e/video-learning.audit.ts b/web/tests/e2e/video-learning.audit.ts
index eb9b065f3..72c158628 100644
--- a/web/tests/e2e/video-learning.audit.ts
+++ b/web/tests/e2e/video-learning.audit.ts
@@ -141,6 +141,14 @@ test("YouTube learning survives reload and switches to Invidious without silent
});
}
if (path === "/api/v1/settings/ui") return json({ language: "en" });
+ if (path === "/api/v1/capabilities/registered") {
+ return json({
+ capabilities: [
+ { id: "chat", kind: "turn", available: true },
+ { id: "immersive_watching", kind: "turn", available: true },
+ ],
+ });
+ }
if (path === "/api/v1/settings") return json({ catalog: {} });
if (path === "/api/v1/settings/llm-options") {
return json({ active: { profile_id: "p", model_id: "m" }, options: [] });
@@ -222,11 +230,7 @@ test("YouTube learning survives reload and switches to Invidious without silent
return json({});
});
- await page.goto("/home");
- await page
- .getByRole("button", { name: /Immersive Watching/ })
- .last()
- .click();
+ await page.goto("/home?capability=immersive_watching");
await page
.getByPlaceholder("https://youtu.be/…")
.fill("https://youtu.be/dQw4w9WgXcQ?t=7");
@@ -257,11 +261,6 @@ test("YouTube learning survives reload and switches to Invidious without silent
await expect(page.getByText("The first grounded concept.")).toBeVisible();
await page.reload();
- await page.getByRole("button", { name: "Chat", exact: true }).click();
- await page
- .getByRole("button", { name: /Immersive Watching/ })
- .last()
- .click();
await expect(page.getByText("Timestamped lesson")).toBeVisible();
await page.getByRole("tab", { name: "Video notes" }).click();
await expect(page.getByText("First timestamped note")).toBeVisible();
@@ -332,10 +331,6 @@ test("YouTube learning survives reload and switches to Invidious without silent
});
await expect.poll(() => savedPosition).toBeGreaterThanOrEqual(70);
await page.reload();
- await page
- .getByRole("button", { name: /Immersive Watching/ })
- .last()
- .click();
await expect(page.getByText("Timestamped lesson")).toBeVisible();
await expect
.poll(() =>
diff --git a/web/tests/integration/chat-store-selectors.spec.tsx b/web/tests/integration/chat-store-selectors.spec.tsx
index bab151077..0249942ec 100644
--- a/web/tests/integration/chat-store-selectors.spec.tsx
+++ b/web/tests/integration/chat-store-selectors.spec.tsx
@@ -19,7 +19,7 @@ function SidebarConsumer({ onRender }: { onRender: () => void }) {
}
describe("chat selector isolation", () => {
- it("does not rerender sidebar consumers for streamed content", () => {
+ it("does not rerender sidebar consumers during a 500-token stream", () => {
const onMessageRender = vi.fn();
const onSidebarRender = vi.fn();
const store = createChatStore();
@@ -38,24 +38,26 @@ describe("chat selector isolation", () => {
);
const sidebarBefore = screen.getByTestId("sidebar").textContent;
- act(() => {
- store.dispatch({
- type: "stream_event",
- key: "draft",
- event: {
- type: "content",
- turn_id: "turn-1",
- seq: 1,
- timestamp: 1,
- content: "token",
- metadata: {},
- },
+ for (let seq = 1; seq <= 500; seq += 1) {
+ act(() => {
+ store.dispatch({
+ type: "stream_event",
+ key: "draft",
+ event: {
+ type: "content",
+ turn_id: "turn-1",
+ seq,
+ timestamp: seq,
+ content: "x",
+ metadata: {},
+ },
+ });
});
- });
+ }
- expect(screen.getByTestId("messages")).toHaveTextContent("token");
+ expect(screen.getByTestId("messages").textContent).toHaveLength(500);
expect(screen.getByTestId("sidebar").textContent).toBe(sidebarBefore);
- expect(onMessageRender).toHaveBeenCalledTimes(2);
+ expect(onMessageRender).toHaveBeenCalledTimes(501);
expect(onSidebarRender).toHaveBeenCalledTimes(1);
});
});
diff --git a/web/tests/tooling-config.test.ts b/web/tests/tooling-config.test.ts
index bc67b7875..01b719dfe 100644
--- a/web/tests/tooling-config.test.ts
+++ b/web/tests/tooling-config.test.ts
@@ -67,10 +67,16 @@ test("package exposes deterministic frontend checks", () => {
const scripts = packageJson.scripts as Record<string, string>;
assert.equal(scripts.typecheck, "tsc --noEmit --incremental false");
- assert.ok(scripts["check:fast"]);
- assert.ok(scripts.check);
- assert.match(scripts.check, /build/);
- assert.match(scripts.check, /perf:check/);
+ assert.equal(
+ scripts["check:fast"],
+ "npm run contracts:check && npm run architecture:check && npm run typecheck && npm run test:node && npm run test:unit && npm run lint && npm run i18n:check",
+ );
+ assert.equal(
+ scripts.check,
+ "npm run check:fast && npm run build && npm run perf:check",
+ );
+ assert.match(scripts["test:e2e:critical"], /critical-turns/);
+ assert.match(scripts["test:e2e:multi-worker"], /multi-worker-turns-desktop/);
});
test("tracked frontend files contain no generated or backup artifacts", () => {