@firstpick/pi-package-webui 0.8.0 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +22 -5
  2. package/bin/pi-webui.mjs +434 -100
  3. package/lib/npm-command.mjs +81 -0
  4. package/lib/queue-mutation.mjs +6 -0
  5. package/lib/workspace-files-live-watcher.mjs +138 -0
  6. package/package.json +8 -3
  7. package/public/app.js +2816 -314
  8. package/public/index.html +112 -27
  9. package/public/mobile-shell-state.mjs +166 -0
  10. package/public/service-worker.js +60 -13
  11. package/public/styles.css +1049 -371
  12. package/public/subagent-gate-visibility.mjs +16 -0
  13. package/public/subagent-launch-slot-state.mjs +16 -0
  14. package/public/transcript-renderer.mjs +433 -0
  15. package/tests/boot-failure-diagnostics.test.mjs +3 -3
  16. package/tests/browser/interaction-continuity.spec.mjs +739 -0
  17. package/tests/browser/mobile-foundation.spec.mjs +352 -0
  18. package/tests/browser/optimistic-prompt.spec.mjs +130 -0
  19. package/tests/chat-scroll-intent-static.test.mjs +6 -1
  20. package/tests/codex-fast-mode-static.test.mjs +8 -5
  21. package/tests/compact-sections-static.test.mjs +20 -2
  22. package/tests/compaction-mutation-contract.test.mjs +18 -4
  23. package/tests/compaction-static.test.mjs +1 -0
  24. package/tests/completion-signal-contract.test.mjs +13 -2
  25. package/tests/fast-mode-client-static.test.mjs +7 -4
  26. package/tests/fixtures/fake-pi.mjs +181 -2
  27. package/tests/git-panel-gitignore-static.test.mjs +104 -0
  28. package/tests/http-endpoints-harness.test.mjs +228 -2
  29. package/tests/interaction-state-stability-static.test.mjs +254 -0
  30. package/tests/mobile-continuity-tablet-static.test.mjs +55 -0
  31. package/tests/mobile-foundation-static.test.mjs +69 -0
  32. package/tests/mobile-phone-experience-static.test.mjs +65 -0
  33. package/tests/mobile-shell-state.test.mjs +69 -0
  34. package/tests/mobile-static.test.mjs +244 -38
  35. package/tests/mobile-transcript-cache-characterization.test.mjs +34 -0
  36. package/tests/npm-command.test.mjs +64 -1
  37. package/tests/open-issue-wizard-static.test.mjs +2 -1
  38. package/tests/queue-edit-reorder-static.test.mjs +9 -1
  39. package/tests/queue-mutation-contract.test.mjs +22 -0
  40. package/tests/service-worker-lifecycle.test.mjs +120 -0
  41. package/tests/sse-backpressure-harness.test.mjs +98 -0
  42. package/tests/streaming-ui-coupling.test.mjs +7 -1
  43. package/tests/subagent-gate-visibility.test.mjs +18 -2
  44. package/tests/subagent-launch-slot-state.test.mjs +32 -0
  45. package/tests/subagent-launch-slots-static.test.mjs +8 -2
  46. package/tests/subagents-helper.test.mjs +90 -0
  47. package/tests/terminal-tab-workspace-static.test.mjs +1 -1
  48. package/tests/update-commands.test.mjs +4 -0
  49. package/tests/workspace-files-live-updates-static.test.mjs +76 -0
  50. package/tests/workspace-files-live-watcher.test.mjs +95 -0
  51. package/webui-rpc-helper.mjs +175 -3
@@ -1,7 +1,7 @@
1
1
  import assert from "node:assert/strict";
2
2
  import { spawn, spawnSync } from "node:child_process";
3
3
  import { createServer } from "node:http";
4
- import { chmod, mkdir, mkdtemp, readFile, rename, rm, stat, symlink, writeFile } from "node:fs/promises";
4
+ import { chmod, link, mkdir, mkdtemp, readFile, rename, rm, stat, symlink, writeFile } from "node:fs/promises";
5
5
  import { networkInterfaces, tmpdir } from "node:os";
6
6
  import path from "node:path";
7
7
  import { setTimeout as delay } from "node:timers/promises";
@@ -411,6 +411,26 @@ try {
411
411
  const tabId = tabList[0].id;
412
412
  assert.ok(tabId, "tab should have an id");
413
413
 
414
+ const dedupTabResponse = await request("127.0.0.1", "/api/tabs", { method: "POST", body: { cwd, title: "mobile-request-dedup" } });
415
+ assert.equal(dedupTabResponse.status, 201, "mobile request deduplication test tab should open");
416
+ const dedupTabId = dedupTabResponse.body?.data?.tab?.id;
417
+ const requestId = "mobile_request_1234567890";
418
+ const requestBody = { tab: dedupTabId, message: "mobile request dedup fixture", requestId };
419
+ const [firstPrompt, duplicatePrompt] = await Promise.all([
420
+ request("127.0.0.1", "/api/prompt", { method: "POST", body: requestBody }),
421
+ request("127.0.0.1", "/api/prompt", { method: "POST", body: requestBody }),
422
+ ]);
423
+ assert.equal(firstPrompt.status, 200, "the first browser-identified prompt should dispatch");
424
+ assert.equal(duplicatePrompt.status, 200, "a known browser request should return the retained result");
425
+ const duplicateReuse = await request("127.0.0.1", "/api/prompt", { method: "POST", body: { ...requestBody, message: "different prompt" } });
426
+ assert.equal(duplicateReuse.status, 409, "a request ID cannot be reused for a different mutation");
427
+ const dedupCommands = (await readJsonLines(fakePiCommandLog)).filter((entry) => entry.direction === "command" && entry.message === "mobile request dedup fixture");
428
+ assert.equal(dedupCommands.length, 1, "duplicate browser prompt identities must reach Pi exactly once");
429
+ const dedupTabs = await request("127.0.0.1", "/api/tabs");
430
+ const dedupActivity = dedupTabs.body?.data?.tabs?.find((tab) => tab.id === dedupTabId)?.activity;
431
+ assert.match(dedupActivity?.runId || "", /^[0-9a-f-]{36}$/i, "active parent work must expose a server-issued opaque run ID");
432
+ assert.equal((await request("127.0.0.1", "/api/tabs/close", { method: "POST", body: { ids: [dedupTabId] } })).status, 200, "mobile request deduplication test tab should close");
433
+
414
434
  const runtimeQueueBefore = { steering: ["runtime steering"], followUp: ["runtime first", "runtime second", "runtime third"] };
415
435
  const runtimeQueueEdit = await waitForSseEvent(
416
436
  tabId,
@@ -462,6 +482,19 @@ try {
462
482
  assert.equal(runtimeQueueMove.status, 200, "runtime queue moves should use final zero-based indices");
463
483
  assert.deepEqual(runtimeQueueMove.body?.data?.queue?.followUp, ["runtime second", "runtime third", "runtime edited"]);
464
484
 
485
+ const runtimeQueueDelete = await request("127.0.0.1", "/api/queue/mutate", {
486
+ method: "POST",
487
+ body: {
488
+ tab: tabId,
489
+ source: "pi-runtime",
490
+ kind: "followUp",
491
+ expected: { steering: ["runtime steering"], followUp: ["runtime second", "runtime third", "runtime edited"] },
492
+ operation: { type: "delete", index: 1, expectedText: "runtime third" },
493
+ },
494
+ });
495
+ assert.equal(runtimeQueueDelete.status, 200, "runtime queue deletion should remove the selected follow-up");
496
+ assert.deepEqual(runtimeQueueDelete.body?.data?.queue?.followUp, ["runtime second", "runtime edited"]);
497
+
465
498
  const invalidRuntimeQueueMutation = await request("127.0.0.1", "/api/queue/mutate", {
466
499
  method: "POST",
467
500
  body: { tab: tabId, source: "pi-runtime", kind: "steering", expected: { steering: [], followUp: [] }, operation: { type: "edit", index: 0, expectedText: "x", text: "y" } },
@@ -722,6 +755,17 @@ try {
722
755
  assert.equal(subagentOutputResponse.body?.data?.agent?.currentToolArgs, "README.md", "subagent output should include current tool state");
723
756
  assert.equal(subagentOutputResponse.body?.data?.agent?.model, "anthropic/claude-opus-4-8:high", "subagent output should preserve the effective model");
724
757
  assert.equal(subagentOutputResponse.body?.data?.agent?.thinking, "high", "subagent output should preserve the effective reasoning effort");
758
+ assert.deepEqual(subagentOutputResponse.body?.data?.agent?.telemetry, {
759
+ promptInjectionTokens: 1234,
760
+ inputTokens: 300,
761
+ outputTokens: 100,
762
+ tokenSpeed: 20,
763
+ contextTokens: 240,
764
+ contextWindow: 200_000,
765
+ model: "anthropic/claude-opus-4-8:high",
766
+ effort: "high",
767
+ }, "selected output should preserve only the normalized additive telemetry contract");
768
+ assert.equal(Object.hasOwn(subagentOutputResponse.body?.data?.agent?.telemetry || {}, "rawSessionPayload"), false, "selected output must not leak raw child-session/custom payloads");
725
769
  assert.deepEqual(subagentOutputResponse.body?.data?.agent?.transcript, [
726
770
  {
727
771
  role: "assistant",
@@ -855,6 +899,29 @@ try {
855
899
  assert.equal(state.status, 200);
856
900
  assert.equal(state.body?.data?.model?.provider, "fake", "state should come from the fake pi RPC");
857
901
 
902
+ const newSessionTitleTab = await request("127.0.0.1", "/api/tabs", { method: "POST", body: { cwd } });
903
+ assert.equal(newSessionTitleTab.status, 201, `new-session title test tab should open: ${newSessionTitleTab.body?.error || ""}`);
904
+ const newSessionTitleTabId = newSessionTitleTab.body?.data?.tab?.id;
905
+ const defaultNewSessionTabTitle = newSessionTitleTab.body?.data?.tab?.title;
906
+ assert.ok(newSessionTitleTabId && defaultNewSessionTabTitle, "new-session title test tab should include default metadata");
907
+ const autoNamedTab = await request("127.0.0.1", "/api/prompt", {
908
+ method: "POST",
909
+ body: { tab: newSessionTitleTabId, message: "verify new session terminal title refresh" },
910
+ });
911
+ assert.equal(autoNamedTab.status, 200, "the title test prompt should be accepted");
912
+ assert.notEqual(autoNamedTab.body?.tab?.title, defaultNewSessionTabTitle, "the first prompt should auto-name the test tab");
913
+ assert.equal(autoNamedTab.body?.tab?.titleSource, "auto", "the generated title should be marked automatic");
914
+ const freshSession = await request("127.0.0.1", "/api/new-session", {
915
+ method: "POST",
916
+ body: { tab: newSessionTitleTabId },
917
+ });
918
+ assert.equal(freshSession.status, 200, `new session should succeed: ${freshSession.body?.error || ""}`);
919
+ assert.equal(freshSession.body?.tab?.title, defaultNewSessionTabTitle, "new-session responses should immediately reset automatic terminal-tab titles");
920
+ assert.equal(freshSession.body?.tab?.titleSource, "default", "a reset title should be eligible for the new session's first-prompt naming");
921
+ assert.equal(freshSession.body?.tab?.conversationStarted, false, "the new session should reset conversation-title tracking");
922
+ const closeNewSessionTitleTab = await request("127.0.0.1", "/api/tabs/close", { method: "POST", body: { ids: [newSessionTitleTabId] } });
923
+ assert.equal(closeNewSessionTitleTab.status, 200, "new-session title test tab should close before later endpoint checks");
924
+
858
925
  const forkSourceTab = await request("127.0.0.1", "/api/tabs", { method: "POST", body: { cwd, title: "fork-running-source" } });
859
926
  assert.equal(forkSourceTab.status, 201, `fork source tab should open: ${forkSourceTab.body?.error || ""}`);
860
927
  const forkSourceTabId = forkSourceTab.body?.data?.tab?.id;
@@ -1397,6 +1464,165 @@ try {
1397
1464
  assert.ok(id, `${title} tab should have an id`);
1398
1465
  return id;
1399
1466
  };
1467
+ const addToGitignore = (tab, targetPath, kind) => request("127.0.0.1", "/api/git-changes/add-to-gitignore", {
1468
+ method: "POST",
1469
+ body: { tab, path: targetPath, kind },
1470
+ });
1471
+
1472
+ // Add-to-gitignore mutation: literal entries, idempotence, line endings, validation, and target safety.
1473
+ const gitignoreRepo = await makeFixtureRepo("add-to-gitignore");
1474
+ const gitignoreTab = await openFixtureTab(gitignoreRepo, "add-to-gitignore-fixture");
1475
+ await mkdir(path.join(gitignoreRepo, "generated"), { recursive: true });
1476
+ await writeFile(path.join(gitignoreRepo, "generated", "output.log"), "generated\n");
1477
+ await mkdir(path.join(gitignoreRepo, "build"), { recursive: true });
1478
+ await writeFile(path.join(gitignoreRepo, "build", "bundle.js"), "bundle\n");
1479
+ const indexBeforeGitignore = runGitFixture(["diff", "--cached", "--raw"], gitignoreRepo, "gitignore fixture should start with an unchanged index");
1480
+
1481
+ const addIgnoredFile = await addToGitignore(gitignoreTab, "generated/output.log", "file");
1482
+ assert.equal(addIgnoredFile.status, 200);
1483
+ assert.equal(addIgnoredFile.body?.ok, true, `adding a file to .gitignore should succeed: ${addIgnoredFile.body?.error || ""}`);
1484
+ assert.deepEqual({
1485
+ root: addIgnoredFile.body?.data?.root,
1486
+ path: addIgnoredFile.body?.data?.path,
1487
+ kind: addIgnoredFile.body?.data?.kind,
1488
+ entry: addIgnoredFile.body?.data?.entry,
1489
+ added: addIgnoredFile.body?.data?.added,
1490
+ }, {
1491
+ root: gitignoreRepo,
1492
+ path: "generated/output.log",
1493
+ kind: "file",
1494
+ entry: "/generated/output.log",
1495
+ added: true,
1496
+ }, "file mutations should return the approved normalized contract");
1497
+ assert.equal((await readFile(path.join(gitignoreRepo, ".gitignore"), "utf8")), "/generated/output.log\n", "a missing root .gitignore should be created with one LF-terminated entry");
1498
+ assert.equal(addIgnoredFile.body?.data?.changes?.untracked?.some((entry) => entry.path === ".gitignore"), true, "the mutation response should contain refreshed Git status including .gitignore");
1499
+ assert.equal(addIgnoredFile.body?.data?.changes?.untracked?.some((entry) => entry.path === "generated/output.log"), false, "the refreshed snapshot should no longer list the newly ignored file");
1500
+
1501
+ const bytesBeforeRepeat = await readFile(path.join(gitignoreRepo, ".gitignore"));
1502
+ const repeatIgnoredFile = await addToGitignore(gitignoreTab, "generated/output.log", "file");
1503
+ assert.equal(repeatIgnoredFile.body?.data?.added, false, "an exact repeated entry should report a no-op");
1504
+ assert.deepEqual(await readFile(path.join(gitignoreRepo, ".gitignore")), bytesBeforeRepeat, "an exact repeated entry must be byte-idempotent");
1505
+
1506
+ const addIgnoredFolder = await addToGitignore(gitignoreTab, "build", "folder");
1507
+ assert.equal(addIgnoredFolder.body?.data?.entry, "/build/", "folder entries should receive exactly one trailing slash");
1508
+ assert.equal(await readFile(path.join(gitignoreRepo, ".gitignore"), "utf8"), "/generated/output.log\n/build/\n", "folder entries should append without rewriting existing content");
1509
+
1510
+ const concurrentResults = await Promise.all([
1511
+ addToGitignore(gitignoreTab, "concurrent/cache.bin", "file"),
1512
+ addToGitignore(gitignoreTab, "concurrent/cache.bin", "file"),
1513
+ ]);
1514
+ assert.deepEqual(concurrentResults.map((result) => result.body?.data?.added).sort(), [false, true], "per-repository serialization should add one copy under concurrent requests");
1515
+ assert.equal((await readFile(path.join(gitignoreRepo, ".gitignore"), "utf8")).split("/concurrent/cache.bin").length - 1, 1, "serialized concurrent requests should leave one exact line");
1516
+
1517
+ const normalizedSeparators = await addToGitignore(gitignoreTab, "nested\\windows.log", "file");
1518
+ assert.equal(normalizedSeparators.body?.data?.path, "nested/windows.log", "backslash separators should normalize to repository-style slashes");
1519
+ assert.equal(normalizedSeparators.body?.data?.entry, "/nested/windows.log");
1520
+
1521
+ await writeFile(path.join(gitignoreRepo, "file.txt"), "tracked modification\n");
1522
+ const addTrackedFile = await addToGitignore(gitignoreTab, "file.txt", "file");
1523
+ assert.equal(addTrackedFile.body?.data?.added, true, "a tracked path may receive an ignore entry");
1524
+ assert.equal(runGitFixture(["ls-files", "--error-unmatch", "--", "file.txt"], gitignoreRepo, "tracked file must remain in the index"), "file.txt", "adding a tracked path to .gitignore must not untrack it");
1525
+ assert.match(addTrackedFile.body?.data?.changes?.status || "", /(^|\n) M file\.txt(?=\n|$)/, "the refreshed snapshot should keep a modified tracked file visible after adding its ignore entry");
1526
+
1527
+ assert.equal(runGitFixture(["diff", "--cached", "--raw"], gitignoreRepo, "gitignore mutation must not change the index"), indexBeforeGitignore, "add-to-gitignore must not stage any files");
1528
+ assert.equal(runGitFixture(["ls-files", "--stage", "--", ".gitignore"], gitignoreRepo, "gitignore mutation must leave .gitignore untracked"), "", ".gitignore must remain unstaged and untracked");
1529
+
1530
+ const lfRepo = await makeFixtureRepo("gitignore-lf");
1531
+ const lfTab = await openFixtureTab(lfRepo, "gitignore-lf-fixture");
1532
+ await writeFile(path.join(lfRepo, ".gitignore"), "# existing\n", "utf8");
1533
+ assert.equal((await addToGitignore(lfTab, "lf-output.txt", "file")).body?.data?.added, true);
1534
+ assert.equal(await readFile(path.join(lfRepo, ".gitignore"), "utf8"), "# existing\n/lf-output.txt\n", "LF files should retain LF when appending");
1535
+
1536
+ const noFinalNewlineRepo = await makeFixtureRepo("gitignore-no-final-newline");
1537
+ const noFinalNewlineTab = await openFixtureTab(noFinalNewlineRepo, "gitignore-no-final-newline-fixture");
1538
+ await writeFile(path.join(noFinalNewlineRepo, ".gitignore"), "# existing", "utf8");
1539
+ await addToGitignore(noFinalNewlineTab, "separated.txt", "file");
1540
+ assert.equal(await readFile(path.join(noFinalNewlineRepo, ".gitignore"), "utf8"), "# existing\n/separated.txt\n", "append should add a separator when existing content has no final newline");
1541
+
1542
+ const crlfRepo = await makeFixtureRepo("gitignore-crlf");
1543
+ const crlfTab = await openFixtureTab(crlfRepo, "gitignore-crlf-fixture");
1544
+ await writeFile(path.join(crlfRepo, ".gitignore"), Buffer.from("# existing\r\n", "utf8"));
1545
+ await addToGitignore(crlfTab, "crlf-output.txt", "file");
1546
+ assert.deepEqual(await readFile(path.join(crlfRepo, ".gitignore")), Buffer.from("# existing\r\n/crlf-output.txt\r\n", "utf8"), "CRLF files should retain CRLF when appending");
1547
+
1548
+ const literalRepo = await makeFixtureRepo("gitignore-literal-pattern");
1549
+ const literalTab = await openFixtureTab(literalRepo, "gitignore-literal-pattern-fixture");
1550
+ const literalPath = "literal [x] *?.txt";
1551
+ const addLiteral = await addToGitignore(literalTab, literalPath, "file");
1552
+ assert.equal(addLiteral.body?.data?.entry, "/literal\\ \\[x\\]\\ \\*\\?.txt", "spaces and Git pattern metacharacters should be escaped literally");
1553
+ assert.equal(await readFile(path.join(literalRepo, ".gitignore"), "utf8"), "/literal\\ \\[x\\]\\ \\*\\?.txt\n");
1554
+ const intendedLiteralCheck = spawnSync("git", ["check-ignore", "-q", "--no-index", "--", literalPath], { cwd: literalRepo });
1555
+ assert.equal(intendedLiteralCheck.status, 0, "the escaped entry should ignore the intended special-character path");
1556
+ const broaderLiteralCheck = spawnSync("git", ["check-ignore", "-q", "--no-index", "--", "literal x anything.txt"], { cwd: literalRepo });
1557
+ assert.notEqual(broaderLiteralCheck.status, 0, "the escaped entry must not broaden into wildcard or character-class matching");
1558
+
1559
+ const outsideMarker = path.join(gitFixturesRoot, "outside-gitignore-marker.txt");
1560
+ await writeFile(outsideMarker, "outside unchanged\n");
1561
+ const validationBytesBefore = await readFile(path.join(gitignoreRepo, ".gitignore"));
1562
+ const rejectedGitignoreInputs = [
1563
+ { path: "", kind: "file", label: "empty path" },
1564
+ { path: ".", kind: "folder", label: "repository root" },
1565
+ { path: "/absolute.txt", kind: "file", label: "POSIX absolute path" },
1566
+ { path: "C:\\absolute.txt", kind: "file", label: "Windows absolute path" },
1567
+ { path: "../outside-gitignore-marker.txt", kind: "file", label: "traversal" },
1568
+ { path: "nested/../outside.txt", kind: "file", label: "embedded traversal" },
1569
+ { path: "bad\npath.txt", kind: "file", label: "newline control character" },
1570
+ { path: "bad\0path.txt", kind: "file", label: "NUL control character" },
1571
+ { path: "valid.txt", kind: "directory", label: "invalid kind" },
1572
+ { path: "valid.txt", kind: "", label: "empty kind" },
1573
+ ];
1574
+ for (const invalid of rejectedGitignoreInputs) {
1575
+ const rejected = await addToGitignore(gitignoreTab, invalid.path, invalid.kind);
1576
+ assert.equal(rejected.status, 400, `${invalid.label} should be rejected`);
1577
+ assert.equal(rejected.body?.ok, false, `${invalid.label} should return a structured failure`);
1578
+ }
1579
+ assert.deepEqual(await readFile(path.join(gitignoreRepo, ".gitignore")), validationBytesBefore, "validation failures must leave .gitignore byte-for-byte unchanged");
1580
+ assert.equal(await readFile(outsideMarker, "utf8"), "outside unchanged\n", "traversal attempts must not write outside the repository");
1581
+
1582
+ const unsafeRepo = await makeFixtureRepo("gitignore-unsafe-target");
1583
+ const unsafeTab = await openFixtureTab(unsafeRepo, "gitignore-unsafe-target-fixture");
1584
+ const unsafeGitignore = path.join(unsafeRepo, ".gitignore");
1585
+ await mkdir(unsafeGitignore);
1586
+ const directoryTarget = await addToGitignore(unsafeTab, "blocked.txt", "file");
1587
+ assert.equal(directoryTarget.status, 409, "a non-regular root .gitignore target should fail closed");
1588
+ await rm(unsafeGitignore, { recursive: true, force: true });
1589
+
1590
+ const hardlinkTarget = path.join(gitFixturesRoot, "outside-hardlink-target.txt");
1591
+ await writeFile(hardlinkTarget, "hard-link target unchanged\n");
1592
+ let hardlinkSupported = true;
1593
+ try {
1594
+ await link(hardlinkTarget, unsafeGitignore);
1595
+ } catch (error) {
1596
+ if (error?.code === "EPERM" || error?.code === "EACCES" || error?.code === "ENOSYS" || error?.code === "EXDEV") hardlinkSupported = false;
1597
+ else throw error;
1598
+ }
1599
+ if (hardlinkSupported) {
1600
+ const hardlinkResponse = await addToGitignore(unsafeTab, "blocked.txt", "file");
1601
+ assert.equal(hardlinkResponse.status, 409, "a root .gitignore hard link should fail closed");
1602
+ assert.equal(await readFile(hardlinkTarget, "utf8"), "hard-link target unchanged\n", "a rejected .gitignore hard link must not modify its outside target");
1603
+ await rm(unsafeGitignore, { force: true });
1604
+ }
1605
+
1606
+ const symlinkTarget = path.join(gitFixturesRoot, "outside-symlink-target.txt");
1607
+ await writeFile(symlinkTarget, "symlink target unchanged\n");
1608
+ let symlinkSupported = true;
1609
+ try {
1610
+ await symlink(symlinkTarget, unsafeGitignore, "file");
1611
+ } catch (error) {
1612
+ if (error?.code === "EPERM" || error?.code === "EACCES" || error?.code === "ENOSYS") symlinkSupported = false;
1613
+ else throw error;
1614
+ }
1615
+ if (symlinkSupported) {
1616
+ const symlinkResponse = await addToGitignore(unsafeTab, "blocked.txt", "file");
1617
+ assert.equal(symlinkResponse.status, 409, "a root .gitignore symlink should fail closed");
1618
+ assert.equal(await readFile(symlinkTarget, "utf8"), "symlink target unchanged\n", "a rejected .gitignore symlink must not be followed");
1619
+ await rm(unsafeGitignore, { force: true });
1620
+ }
1621
+
1622
+ await writeFile(unsafeGitignore, Buffer.alloc(5 * 1024 * 1024 + 1, 0x23));
1623
+ const oversizedResponse = await addToGitignore(unsafeTab, "blocked.txt", "file");
1624
+ assert.equal(oversizedResponse.status, 409, "an oversized root .gitignore should be rejected as an unsafe server-side file state before it is read into memory");
1625
+ assert.equal((await stat(unsafeGitignore)).size, 5 * 1024 * 1024 + 1, "oversized refusal must leave .gitignore unchanged");
1400
1626
 
1401
1627
  // File-scoped Git diff endpoint: staged, unstaged, untracked, empty, deleted, and rejected inputs.
1402
1628
  const fileDiffRepo = await makeFixtureRepo("file-diff");
@@ -1820,7 +2046,7 @@ try {
1820
2046
  const pruneConfirmed = await request("127.0.0.1", "/api/git-worktrees/prune", { method: "POST", body: { tab: undoTab, confirmed: true }, timeoutMs: 20_000 });
1821
2047
  assert.equal(pruneConfirmed.body?.ok, true, `confirmed prune should succeed: ${pruneConfirmed.body?.error || ""}`);
1822
2048
 
1823
- const closeGitActionTabs = await request("127.0.0.1", "/api/tabs/close", { method: "POST", body: { ids: [stagingTab, truncationTab, mergeTab, abortTab, rebaseTab, bisectTab, stashTab, undoTab] }, timeoutMs: 10_000 });
2049
+ const closeGitActionTabs = await request("127.0.0.1", "/api/tabs/close", { method: "POST", body: { ids: [gitignoreTab, lfTab, noFinalNewlineTab, crlfTab, literalTab, unsafeTab, fileDiffTab, stagingTab, truncationTab, mergeTab, abortTab, rebaseTab, bisectTab, stashTab, undoTab] }, timeoutMs: 10_000 });
1824
2050
  assert.equal(closeGitActionTabs.status, 200, "git action fixture tabs should close");
1825
2051
  await rmWithRetry(gitFixturesRoot);
1826
2052
 
@@ -0,0 +1,254 @@
1
+ import assert from "node:assert/strict";
2
+ import { readFile } from "node:fs/promises";
3
+ import { dirname, join } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+
6
+ const root = join(dirname(fileURLToPath(import.meta.url)), "..");
7
+ const app = await readFile(join(root, "public", "app.js"), "utf8");
8
+ const renderer = await readFile(join(root, "public", "transcript-renderer.mjs"), "utf8");
9
+
10
+ function functionBody(name, source = app) {
11
+ const signature = new RegExp(`function\\s+${name}\\s*\\(`, "m");
12
+ const match = signature.exec(source);
13
+ assert.ok(match, `${name} should remain a standalone frontend helper`);
14
+ let parenDepth = 0;
15
+ let openBrace = -1;
16
+ for (let index = match.index + match[0].length - 1; index < source.length; index += 1) {
17
+ const char = source[index];
18
+ if (char === "(") parenDepth += 1;
19
+ else if (char === ")") parenDepth -= 1;
20
+ else if (char === "{" && parenDepth === 0) {
21
+ openBrace = index;
22
+ break;
23
+ }
24
+ }
25
+ assert.notEqual(openBrace, -1, `${name} body should open`);
26
+ let depth = 0;
27
+ for (let index = openBrace; index < source.length; index += 1) {
28
+ const char = source[index];
29
+ if (char === "{") depth += 1;
30
+ else if (char === "}") {
31
+ depth -= 1;
32
+ if (depth === 0) return source.slice(openBrace + 1, index);
33
+ }
34
+ }
35
+ assert.fail(`${name} body should close`);
36
+ }
37
+
38
+ const captureControl = functionBody("captureScopedControlContinuity");
39
+ const restoreControl = functionBody("restoreScopedControlContinuity");
40
+ const setScroll = functionBody("setScopedScrollContinuity");
41
+ const rememberScroll = functionBody("rememberScopedScrollContinuity");
42
+ const bindScroll = functionBody("bindScopedScrollContinuity");
43
+ const restoreScroll = functionBody("restoreScopedScrollContinuity");
44
+ const deferPointer = functionBody("deferUiRenderDuringPointerActivation");
45
+ const deferSurface = functionBody("deferUiRenderDuringInteractiveSurface");
46
+ const flushDeferred = functionBody("flushDeferredUiRenders");
47
+ const captureTooltip = functionBody("captureTooltipContinuity");
48
+ const restoreTooltip = functionBody("restoreTooltipContinuity");
49
+ const renderTabs = functionBody("renderTabs");
50
+ const renderFooter = functionBody("renderFooter");
51
+ const renderFileTree = functionBody("renderFileTree");
52
+ const renderWidgets = functionBody("renderWidgets");
53
+ const renderSubagents = functionBody("renderSubagents");
54
+ const renderGitWorkflow = functionBody("renderGitWorkflow");
55
+ const renderGitPanel = functionBody("renderGitPanel");
56
+ const renderQueue = functionBody("renderQueue");
57
+ const captureChatText = functionBody("captureChatTextSelection");
58
+ const matchChatText = functionBody("chatTextSelectionMatch");
59
+ const restoreChatText = functionBody("restoreChatTextSelection");
60
+ const renderAllMessages = functionBody("renderAllMessages");
61
+ const renderStreamingMarkdown = functionBody("renderStreamingMarkdown");
62
+ const refreshMessages = functionBody("refreshMessages");
63
+ const captureMobileSurface = functionBody("captureMobileSurfaceRenderFocus");
64
+ const restoreMobileSurface = functionBody("restoreMobileSurfaceRenderFocus");
65
+ const captureAppRunnerInput = functionBody("captureAppRunnerInputFocus");
66
+ const restoreAppRunnerInput = functionBody("restoreAppRunnerInputFocus");
67
+ const captureGitInput = functionBody("captureGitWorkflowInputFocus");
68
+ const restoreGitInput = functionBody("restoreGitWorkflowInputFocus");
69
+
70
+ assert.match(captureControl, /root\?\.contains\(source\)/, "control capture must be scoped to the renderer root");
71
+ assert.match(captureControl, /const targetKey = targetKeyFor\?\.\(source\);[\s\S]*if \(!targetKey\) return null;/, "control capture requires a semantic target key");
72
+ assert.match(captureControl, /contextKey,[\s\S]*selectionStart:[\s\S]*selectionEnd:[\s\S]*selectionDirection:[\s\S]*scrollTop:[\s\S]*scrollLeft:/, "control snapshots must retain context, selection direction, and both control scroll axes");
73
+ assert.match(restoreControl, /snapshot\.contextKey !== contextKey \|\| document\.activeElement === snapshot\.source/, "restore must reject mismatched contexts and leave an already-focused surviving source alone");
74
+ assert.match(restoreControl, /isMeaningfulConnectedFocus\(document\.activeElement\)/, "restore must not steal focus from a meaningful connected target");
75
+ assert.match(restoreControl, /snapshot\.source\.isConnected && root\?\.contains\(snapshot\.source\)[\s\S]*targetForKey\?\.\(snapshot\.targetKey\)[\s\S]*root\?\.contains\(target\)[\s\S]*target\.disabled/, "restore must prefer a surviving reattached control or resolve a valid replacement inside its root");
76
+ assert.match(restoreControl, /target\.focus\(\{ preventScroll: true \}\)[\s\S]*setSelectionRange\(start, end, snapshot\.selectionDirection \|\| "none"\)/, "restore must restore focus and directional selection without scrolling the page");
77
+ assert.match(restoreControl, /target\.scrollTop = Math\.min[\s\S]*target\.scrollLeft = Math\.min/, "restore must bound control scroll rather than applying stale offsets blindly");
78
+
79
+ assert.match(captureTooltip, /footerTooltipTarget \|\| footerTooltipPendingTarget[\s\S]*root\?\.contains\(target\)[\s\S]*tooltipTargetKey\(target\)[\s\S]*target\.matches\?\.\(":hover"\)[\s\S]*remainingDelay:/, "tooltip capture must use a root-local semantic target and retain any in-progress hover delay");
80
+ assert.match(restoreTooltip, /querySelectorAll\?\.\("\[data-tooltip-target-key\]"\)[\s\S]*tooltipTargetKey\(node\) === snapshot\.key/, "tooltip restore must find the semantic replacement rather than reusing detached DOM");
81
+ assert.match(restoreTooltip, /!target \|\| !target\.hasAttribute\("data-tooltip"\)[\s\S]*hideFooterTooltip\(snapshot\.target\)/, "removed or inapplicable tooltip targets must close the old tooltip");
82
+ assert.match(restoreTooltip, /snapshot\.pending\) scheduleFooterTooltip\(target, snapshot\.remainingDelay\)[\s\S]*showFooterTooltip\(target\)/, "surviving visible tooltips must rebind synchronously while pending tooltips retain only their remaining delay");
83
+
84
+ assert.match(setScroll, /scopedScrollContinuityByKey\.delete\(key\)[\s\S]*size > SCOPED_SCROLL_CONTINUITY_LIMIT[\s\S]*keys\(\)\.next\(\)\.value/, "scroll continuity must use bounded recency storage");
85
+ assert.match(rememberScroll, /!node\?\.isConnected \|\| !key[\s\S]*const previous = scopedScrollContinuityByKey\.get\(key\);[\s\S]*preserveMode && previous \? previous\.mode : maxScrollTop - node\.scrollTop <= 24 \? "follow-end" : "position"/, "scroll capture must ignore detached stale emitters and latch reader mode across programmatic renders");
86
+ assert.match(bindScroll, /dataset\.continuityScrollKey = key[\s\S]*_scopedScrollContinuityUserIntentUntil[\s\S]*rememberScopedScrollContinuity\(node, undefined, \{ allowPendingRestore: userInitiated, preserveMode: !userInitiated \}\)/, "scroll listeners must resolve the current semantic key and only change mode after user intent");
87
+ assert.match(restoreScroll, /requestAnimationFrame[\s\S]*state\.mode === "follow-end" \? maxScrollTop : Math\.min/, "scroll restore must apply its mode after layout and bound a retained position");
88
+ assert.match(app, /bindScopedScrollContinuity\(terminal, scrollKey\)[\s\S]*restoreScopedScrollContinuity\(terminal, scrollKey\)/, "app-runner output must participate in explicit scroll continuity");
89
+ assert.match(app, /bindScopedScrollContinuity\(transcript, scrollKey\)[\s\S]*restoreScopedScrollContinuity\(transcript, scrollKey\)/, "subagent transcript output must participate in explicit scroll continuity");
90
+
91
+ assert.match(deferPointer, /shouldDeferUiRenderForPointerActivation\(\)[\s\S]*deferredUiRenderCallbacks\.set\(key, callback\)/, "pointer-active updates must defer through a latest-wins keyed callback map");
92
+ assert.match(deferSurface, /isInteractiveDropdownOpen\(\)[\s\S]*deferredUiRenderCallbacks\.set\(key, callback\)[\s\S]*scheduleDeferredUiFlushAfterDropdownClose\(\)/, "open interactive surfaces must defer their invalidation until they close");
93
+ assert.match(flushDeferred, /\[\.\.\.deferredUiRenderCallbacks\.values\(\)\][\s\S]*deferredUiRenderCallbacks\.clear\(\)[\s\S]*for \(const callback of callbacks\)/, "deferred renders must coalesce and flush each retained callback once");
94
+
95
+ for (const [name, source, root] of [
96
+ ["terminal tabs", renderTabs, "elements.tabBar"],
97
+ ["footer", renderFooter, "elements.statusBar"],
98
+ ["file tree", renderFileTree, "root"],
99
+ ["widgets", renderWidgets, "elements.widgetArea"],
100
+ ["subagent panel", renderSubagents, "box"],
101
+ ]) {
102
+ assert.match(source, /deferUiRenderDuringPointerActivation/, `${name} must participate in primary-pointer deferral`);
103
+ assert.match(source, /captureScopedControlContinuity|captureScopedScrollContinuity/, `${name} must capture only its own continuity state`);
104
+ if (name === "terminal tabs" || name === "footer" || name === "file tree" || name === "subagent panel") {
105
+ assert.match(source, new RegExp(`restoreScopedControlContinuity\\(${root.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`), `${name} must restore through its own root`);
106
+ }
107
+ }
108
+ assert.match(renderTabs, /captureTooltipContinuity\(elements\.tabBar\)[\s\S]*restoreTooltipContinuity\(elements\.tabBar, tooltipSnapshot\)/, "terminal-tab rerenders must retain semantic tooltip continuity");
109
+ assert.match(renderFooter, /captureTooltipContinuity\(elements\.statusBar\)[\s\S]*restoreTooltipContinuity\(elements\.statusBar, tooltipSnapshot\)/, "footer rerenders must retain semantic tooltip continuity");
110
+ assert.match(renderGitWorkflow, /captureGitWorkflowInputFocus\(\)[\s\S]*deferUiRenderDuringPointerActivation\("git-workflow", renderGitWorkflow\)[\s\S]*restoreGitWorkflowInputFocus\(inputFocus\)/, "guided Git renders must defer pointer teardown and restore only their captured input");
111
+
112
+ assert.match(captureAppRunnerInput, /activeTabContext\(\)[\s\S]*selectionDirection:[\s\S]*scrollTop:[\s\S]*scrollLeft:/, "app-runner input capture must include its tab context and complete text-control state");
113
+ assert.match(restoreAppRunnerInput, /isCurrentTabContext\(state\.context\) \|\| state\.source\?\.isConnected/, "app-runner input restore must reject stale tab contexts and connected sources");
114
+ assert.match(restoreAppRunnerInput, /isMeaningfulConnectedFocus\(document\.activeElement\)[\s\S]*elements\.widgetArea\.querySelectorAll\("\.app-runner-stdin-input"\)[\s\S]*candidate\.dataset\.runId === state\.runId/, "app-runner input restore must stay inside the widget root and match runner identity");
115
+ assert.match(captureGitInput, /activeTabContext\(\)[\s\S]*selectionDirection:[\s\S]*scrollTop:[\s\S]*scrollLeft:/, "Guided Git input capture must include its context and complete text-control state");
116
+ assert.match(restoreGitInput, /state\.tabId !== activeTabId \|\| state\.runId !== gitWorkflow\?\.runId \|\| !isCurrentTabContext\(state\.context\) \|\| state\.source\?\.isConnected/, "Guided Git input restore must require the exact tab, run, and current context");
117
+
118
+ assert.match(renderGitPanel, /captureScopedControlContinuity\(elements\.gitPanelGroups[\s\S]*data-git-panel-continuity-key[\s\S]*scrollTop = scrollTop/, "Git-panel rebuilds must preserve semantic focus and panel scroll");
119
+ assert.match(renderQueue, /captureScopedControlContinuity\(elements\.queueBox[\s\S]*data-queue-continuity-key[\s\S]*restoreContinuity\(\)/, "queue rebuilds must preserve semantic action focus and panel scroll");
120
+ assert.match(app, /dataset\.mobileContinuityKey = "context:paste-text"[\s\S]*dataset\.mobileDraftAuthority = "dom"/, "mobile paste text must have a stable DOM-authoritative continuity identity");
121
+ assert.match(captureMobileSurface, /mobileDraftAuthority === "dom"[\s\S]*selectionDirection:[\s\S]*scrollTop:[\s\S]*scrollLeft:/, "mobile DOM drafts must capture selection and scroll state");
122
+ assert.match(restoreMobileSurface, /target\.dataset\.mobileDraftAuthority === "dom"[\s\S]*target\.value = snapshot\.value[\s\S]*setSelectionRange[\s\S]*target\.focus\(\{ preventScroll: true \}\)/, "mobile DOM drafts must restore value, selection, scroll, and focus");
123
+
124
+ assert.match(captureChatText, /selection\.isCollapsed[\s\S]*anchorSurface !== focusSurface[\s\S]*chatTextSelectionContextKey\(\)[\s\S]*itemKey:[\s\S]*streaming:[\s\S]*anchorOffset,[\s\S]*focusOffset,[\s\S]*text,/, "main-output selection capture must require one semantic text surface and retain context, identity, direction, and exact text");
125
+ assert.match(matchChatText, /range\.toString\(\) === snapshot\.text/, "main-output selection restoration must reject offsets whose rendered text changed");
126
+ assert.match(restoreChatText, /snapshot\.contextKey !== chatTextSelectionContextKey\(\)[\s\S]*chatTextSelectionCandidates\(snapshot\)[\s\S]*candidates\.includes\(currentAnchorSurface\)[\s\S]*currentText && currentAnchorSurface && currentFocusSurface[\s\S]*setBaseAndExtent/, "main-output selection restoration must reject stale contexts and meaningful newer selections while preserving anchor direction");
127
+ assert.match(renderStreamingMarkdown, /captureChatTextSelection\(block\)[\s\S]*restoreChatTextSelection\(selectionSnapshot\)/, "streaming Markdown tail replacement must preserve a still-valid browser Range");
128
+ assert.match(renderAllMessages, /captureChatTextSelection\(\)[\s\S]*restoreChatTextSelection\(selectionSnapshot\)/, "authoritative transcript rerenders must preserve a still-valid main-output Range");
129
+ assert.match(refreshMessages, /const selectionSnapshot = captureChatTextSelection\(\);[\s\S]*adoptedOutput = adoptLiveAssistantBubble\(latestMessages\)[\s\S]*resetStreamBubble\(\{ preserveCompact: adoptedOutput === "compact" \}\)[\s\S]*restoreStreamRenderAfterChatRebuild\(\)[\s\S]*restoreChatTextSelection\(selectionSnapshot\)/, "stream settlement must adopt matching normal or compact output before reset and retain exact fallback selection");
130
+
131
+ // --- Transcript mutation coordinator contracts (keyed DOM ownership) ---
132
+
133
+ const renderThinkingMarkdown = functionBody("renderThinkingMarkdown");
134
+ const flushCompactLiveOutput = functionBody("flushCompactLiveOutput");
135
+ const updateLiveToolCard = functionBody("updateLiveToolCard");
136
+ const renderLiveToolRun = functionBody("renderLiveToolRun");
137
+ const renderMermaidDiagram = functionBody("renderMermaidDiagram");
138
+ const renderStreamingToolCallCard = functionBody("renderStreamingToolCallCard");
139
+ const adoptLiveAssistantBubble = functionBody("adoptLiveAssistantBubble");
140
+ const authoritativeAssistantTextForAdoption = functionBody("authoritativeAssistantTextForAdoption");
141
+ const resetChatOutput = functionBody("resetChatOutput");
142
+ const ownTranscriptBubble = functionBody("ownTranscriptBubble");
143
+ const transcriptSurfaceKind = functionBody("transcriptSurfaceKind");
144
+ const ensureStreamBubble = functionBody("ensureStreamBubble");
145
+ const ensureStreamingThinkingBubble = functionBody("ensureStreamingThinkingBubble");
146
+ const ensureCompactTextBubble = functionBody("ensureCompactTextBubble");
147
+ const ensureCompactThinkingBubble = functionBody("ensureCompactThinkingBubble");
148
+ const renderCompactToolShell = functionBody("renderCompactToolShell");
149
+ const removeLiveTranscriptBubble = functionBody("removeLiveTranscriptBubble");
150
+ const removeStreamingThinkingBubble = functionBody("removeStreamingThinkingBubble");
151
+ const removeStreamBubble = functionBody("removeStreamBubble");
152
+ const removeCompactLiveBubble = functionBody("removeCompactLiveBubble");
153
+ const finalizeAdoptedAssistantBubble = functionBody("finalizeAdoptedAssistantBubble");
154
+ const prunePendingTranscriptAdoptions = functionBody("prunePendingTranscriptAdoptions");
155
+
156
+ const commitTranscriptMutation = functionBody("commitTranscriptMutation", renderer);
157
+ const applyMutation = functionBody("applyMutation", renderer);
158
+ const reconcileMarkdownSurface = functionBody("reconcileMarkdownSurface", renderer);
159
+ const updateTextSurface = functionBody("updateTextSurface", renderer);
160
+ const ownMessage = functionBody("ownMessage", renderer);
161
+ const ownSurface = functionBody("ownSurface", renderer);
162
+ const ownBlocks = functionBody("ownBlocks", renderer);
163
+ const restoreCoordinatedSelection = functionBody("restoreSelection", renderer);
164
+ const rangeForSnapshot = functionBody("rangeForSnapshot", renderer);
165
+ const coordinatedTextPoint = functionBody("textPoint", renderer);
166
+ const logMutation = functionBody("logMutation", renderer);
167
+
168
+ // Coordinator import and initialization.
169
+ assert.match(app, /import \{ createTranscriptRenderer \} from "\.\/transcript-renderer\.mjs";/, "app must import the transcript mutation coordinator module");
170
+ assert.match(app, /const transcriptRenderer = createTranscriptRenderer\(\{[\s\S]*?chat: elements\.chat[\s\S]*?contextKey: \(\) => chatTextSelectionContextKey\(\)[\s\S]*?\}\);/, "the coordinator must be initialized once against #chat with the transcript context key");
171
+ assert.doesNotMatch(renderer, /^\s*import\s/m, "the transcript renderer must stay dependency-free");
172
+ assert.match(renderer, /export function createTranscriptRenderer\(/, "the coordinator must be the module's exported factory");
173
+ assert.match(renderer, /if \(!chat\) throw new Error/, "the coordinator must require the transcript root");
174
+
175
+ // Semantic message/surface/block ownership.
176
+ assert.match(ownMessage, /dataset\.transcriptMessageKey[\s\S]*dataset\.transcriptRole/, "messages must receive durable semantic keys and roles");
177
+ assert.match(ownSurface, /dataset\.transcriptSurface = kind[\s\S]*dataset\.transcriptSurfaceKey/, "surfaces must receive durable semantic kind and identity keys");
178
+ assert.match(ownBlocks, /dataset\.transcriptBlockKey[\s\S]*dataset\.transcriptBlock = tail \? "mutable-tail" : "committed"/, "streamed Markdown blocks must carry stable committed-block versus mutable-tail identity");
179
+ assert.match(transcriptSurfaceKind, /role === "thinking"[\s\S]*"assistant-thinking"[\s\S]*role === "toolExecution"[\s\S]*"tool-execution"[\s\S]*role === "toolResult"[\s\S]*"tool-result"[\s\S]*role === "compactionSummary"[\s\S]*"compaction-summary"[\s\S]*return "assistant-final"/, "surface kinds must cover assistant, thinking, tool execution/result, and compaction surfaces");
180
+ assert.match(ownTranscriptBubble, /transcriptRenderer\.ownMessage\(bubble, \{ key: itemKey \|\| bubble\.dataset\.itemKey \|\| fallbackKey, role \}\)[\s\S]*surfaces\.forEach\(\(surface, index\) => transcriptRenderer\.ownSurface/, "every transcript bubble and its selectable surfaces must receive semantic ownership");
181
+ assert.match(ensureStreamBubble, /transcriptRenderer\.ownSurface\(streamText, \{ messageKey: "live:assistant", kind: "assistant-final", segment: "0" \}\)/, "the live assistant surface must be semantically owned");
182
+ assert.match(ensureStreamingThinkingBubble, /transcriptRenderer\.ownSurface\(streamThinking, \{ messageKey: "live:thinking", kind: "assistant-thinking", segment: "0" \}\)/, "the live thinking surface must be semantically owned");
183
+ assert.match(ensureCompactTextBubble, /transcriptRenderer\.ownSurface\(compactTextNode, \{ messageKey: "live:compact-output", kind: "compact-output", segment: "0" \}\)/, "the compact live-output surface must be semantically owned");
184
+ assert.match(ensureCompactThinkingBubble, /transcriptRenderer\.ownSurface\(compactThinkingNode, \{ messageKey: "live:compact-thinking", kind: "assistant-thinking", segment: "0" \}\)/, "the compact thinking surface must be semantically owned");
185
+ assert.match(renderCompactToolShell, /transcriptRenderer\.ownMessage\(bubble, \{ key: `live:compact-tool:\$\{id\}`, role: "toolExecution" \}\)[\s\S]*transcriptRenderer\.ownSurface\(body, \{ messageKey: `live:compact-tool:\$\{id\}`, kind: "tool-execution"/, "compact tool shells must receive semantic message and surface ownership");
186
+
187
+ // Normal/compact/thinking/tool/Mermaid routing through the coordinator.
188
+ assert.match(renderStreamingMarkdown, /transcriptRenderer\.reconcileMarkdownSurface\(\{[\s\S]*?kind: "assistant-final"[\s\S]*?stableBoundary: streamingMarkdownStableBoundary[\s\S]*?renderInto: renderMarkdownInto/, "normal streaming output must route through the coordinator committed-block reconciler");
189
+ assert.match(renderThinkingMarkdown, /transcriptRenderer\.reconcileMarkdownSurface\(\{[\s\S]*?kind: "assistant-thinking"[\s\S]*?stableBoundary: streamingMarkdownStableBoundary[\s\S]*?renderInto: renderMarkdownInto/, "streaming thinking must share the same committed-block reconciler");
190
+ assert.match(flushCompactLiveOutput, /transcriptRenderer\.updateTextSurface\(\{[\s\S]*?surface: compactTextNode[\s\S]*?kind: "compact-output"/, "compact live output must update a stable text surface through the coordinator");
191
+ assert.match(flushCompactLiveOutput, /renderThinkingMarkdown\(compactThinkingNode, compactLiveState\.thinking\)/, "compact thinking must share the thinking reconciler path");
192
+ assert.match(updateLiveToolCard, /transcriptRenderer\.ownMessage\(bubble, \{ key: messageKey, role: "toolExecution" \}\)[\s\S]*transcriptRenderer\.ownSurface\(body, \{ messageKey, kind: "tool-execution"[\s\S]*transcriptRenderer\.commitTranscriptMutation\(\{[\s\S]*?kind: "reconcile"[\s\S]*?transcriptRenderer\.replaceChildren\(body\)[\s\S]*?transcriptRenderer\.ownSurface\(body, \{ messageKey, kind: "tool-execution"/, "live tool body must have semantic ownership before selection capture and remain inside one coordinator-owned transaction");
193
+ assert.match(renderLiveToolRun, /key: `tool-replace:\$\{id\}`[\s\S]*kind: "reconcile"[\s\S]*mutate: \(\) => existing\.replaceWith\(created\.bubble\)/, "live tool card replacement must be a coordinator transaction");
194
+ assert.match(renderMermaidDiagram, /transcriptRenderer\.commitTranscriptMutation\(\{[\s\S]*?kind: "destructive"[\s\S]*?transcriptRenderer\.replaceHtml\(diagram, svg\)/, "async Mermaid completion must register its destructive mutation with the coordinator");
195
+ assert.match(renderStreamingToolCallCard, /transcriptRenderer\.updateTextSurface\(\{[\s\S]*?surface: streamToolCallText[\s\S]*?kind: "tool-execution"/, "streaming tool-call text must update through the coordinator text surface");
196
+ assert.match(removeLiveTranscriptBubble, /transcriptRenderer\.commitTranscriptMutation\(\{[\s\S]*kind: "authoritative"[\s\S]*invalidateSelection: true[\s\S]*mutate: \(\) => bubble\.remove\(\)/, "presentation removals must be explicit coordinator-owned invalidations rather than raw transcript mutation");
197
+ assert.match(removeCompactLiveBubble, /removeLiveTranscriptBubble\(bubble, messageKey\)/, "compact removals must share the authoritative live-output removal gateway");
198
+ assert.match(removeStreamingThinkingBubble, /removeLiveTranscriptBubble\(streamThinkingBubble, "thinking"\)/, "thinking visibility changes must use the authoritative removal gateway");
199
+ assert.match(removeStreamBubble, /removeLiveTranscriptBubble\(streamBubble, "assistant"\)/, "normal-to-compact transitions must use the authoritative removal gateway");
200
+ for (const [name, source] of [["compact", removeCompactLiveBubble], ["thinking", removeStreamingThinkingBubble], ["assistant", removeStreamBubble]]) {
201
+ assert.doesNotMatch(source, /\.remove\(\)/, `${name} presentation removal must not bypass the coordinator helper`);
202
+ }
203
+
204
+ // Stable compact text-node updates.
205
+ assert.match(updateTextSurface, /_transcriptTextNode[\s\S]*node\.appendData\(value\.slice\(node\.data\.length\)\)[\s\S]*else node\.data = value/, "text surfaces must reuse one stable Text node and append in place instead of replacing it");
206
+
207
+ // Stable committed blocks and a bounded mutable tail.
208
+ assert.match(reconcileMarkdownSurface, /if \(boundary > state\.stableText\.length\)/, "committed blocks must never be re-rendered for append-only input");
209
+ assert.match(reconcileMarkdownSurface, /for \(const node of state\.tailNodes\) node\.remove\(\)/, "only the mutable tail may be detached during streaming");
210
+ assert.match(reconcileMarkdownSurface, /const diverged = !!state && !value\.startsWith\(state\.stableText\);[\s\S]*invalidateSelection: diverged/, "authoritative divergence must explicitly invalidate selection rather than silently rebuilding");
211
+
212
+ // Live settlement adoption.
213
+ assert.match(authoritativeAssistantTextForAdoption, /if \(finalParts\.length !== 1\) return null;/, "multi-part settlement must not be fuzzy-adopted onto a single live surface");
214
+ assert.match(adoptLiveAssistantBubble, /compactCandidate[\s\S]*normalCandidate[\s\S]*authoritativeText !== candidate\.text[\s\S]*transcriptRenderer\.ownMessage\(candidate\.bubble, \{ key, role: "assistant" \}\)[\s\S]*transcriptRenderer\.ownSurface\(candidate\.surface[\s\S]*pendingTranscriptAdoptions\.set\(key, candidate\.bubble\)/, "live settlement adoption requires exact authoritative agreement and re-keys the same normal or compact bubble");
215
+ assert.match(renderAllMessages, /const commit = transcriptRenderer\.commitTranscriptMutation\(\{[\s\S]*?kind: forceRebuild \? "authoritative" : "reconcile"[\s\S]*?invalidateSelection: forceRebuild[\s\S]*?pendingTranscriptAdoptions\.get\(entry\.key\)/, "authoritative reconciliation must be one coordinator transaction that adopts matching live bubbles");
216
+ assert.match(renderAllMessages, /if \(commit\.deferred\) return;/, "a deferred transcript commit must not run post-mutation restore work");
217
+ assert.match(refreshMessages, /adoptedOutput = adoptLiveAssistantBubble\(latestMessages\);[\s\S]*resetStreamBubble\(\{ preserveCompact: adoptedOutput === "compact" \}\)/, "settlement must try exact live-bubble adoption and preserve a matching compact owner through reset");
218
+ assert.match(finalizeAdoptedAssistantBubble, /compact-live-text[\s\S]*classList\.add\("markdown-body", "compact-transcript-text"\)[\s\S]*transcriptRenderer\.reconcileMarkdownSurface\(\{[\s\S]*stableBoundary: \(value\) => value\.length/, "an adopted compact surface must retain its DOM owner while final Markdown reconciles in place");
219
+ assert.match(prunePendingTranscriptAdoptions, /for \(const \[key, bubble\] of pendingTranscriptAdoptions\)[\s\S]*!bubble\?\.isConnected[\s\S]*pendingTranscriptAdoptions\.delete\(key\)/, "disconnected unconsumed adoptions must not retain detached transcript trees");
220
+
221
+ // Bounded mutation logging.
222
+ assert.match(renderer, /MUTATION_LOG_LIMIT = \d+/, "the coordinator must bound its mutation log");
223
+ assert.match(logMutation, /mutationLog\.push\([\s\S]*mutationLog\.length > MUTATION_LOG_LIMIT[\s\S]*mutationLog\.splice/, "the mutation log must drop oldest entries once the bound is exceeded");
224
+
225
+ // Pointer-selection sessions and destructive-mutation coalescing.
226
+ assert.match(renderer, /document\.addEventListener\("pointerdown"[\s\S]*chat\.addEventListener\("pointerdown"[\s\S]*window\.addEventListener\("pointerup"[\s\S]*window\.addEventListener\("pointercancel"[\s\S]*window\.addEventListener\("blur"[\s\S]*document\.addEventListener\("selectionchange"[\s\S]*chat\.addEventListener\("copy"/, "the coordinator must track transcript pointer selection while ending gestures released outside #chat or the window");
227
+ assert.match(commitTranscriptMutation, /DESTRUCTIVE_KINDS\.has\(kind\)[\s\S]*!invalidateSelection[\s\S]*pointerSession[\s\S]*selectedSurfaceIntersects\(surfaces\)[\s\S]*deferredMutations\.set\(key, entry\)/, "destructive commits intersecting an active pointer drag must coalesce latest-wins until the gesture ends");
228
+
229
+ // Exact single-surface fallback and explicit invalidation.
230
+ assert.match(applyMutation, /if \(context !== contextKey\(\)\) return \{ applied: false, stale: true \}/, "stale-context mutations must be rejected");
231
+ assert.match(applyMutation, /selectionSnapshot\(\) \|\| selectionSession\?\.snapshot \|\| null/, "coordinator mutations must retain the last exact semantic bookmark when an adjacent render step already detached the native range");
232
+ assert.match(rangeForSnapshot, /range\.toString\(\) === snapshot\.text/, "fallback restoration must require exact text evidence");
233
+ assert.match(rangeForSnapshot, /surfaceText\.indexOf\(snapshot\.text\)[\s\S]*surfaceText\.indexOf\(snapshot\.text, exactStart \+ 1\) !== -1[\s\S]*anchorOffset = backward \? exactEnd : exactStart/, "structurally shifted selections may remap only to one exact occurrence in the same semantic surface while preserving direction");
234
+ assert.match(coordinatedTextPoint, /target < next \|\| \(target === next && !forwardAffinity\)/, "selection starts at text-node boundaries must bind to the next node while ends retain backward affinity, avoiding implicit block newlines");
235
+ assert.match(restoreCoordinatedSelection, /snapshot\.context !== contextKey\(\)[\s\S]*!forceRemap && currentText === snapshot\.text[\s\S]*currentText && currentAnchor && currentFocus[\s\S]*snapshot\.anchorOffset > snapshot\.focusOffset[\s\S]*setBaseAndExtent[\s\S]*selection\.addRange\(match\.range\)/, "fallback restoration must reject stale contexts, preserve backward direction, and use the exact validated Range for forward selection");
236
+ assert.match(applyMutation, /intersectsSelection = selectedSurfaceIntersects\(surfaces\)[\s\S]*forceRemap = DESTRUCTIVE_KINDS\.has\(kind\) && intersectsSelection[\s\S]*restoreSelection\(snapshot, \{ forceRemap \}\)/, "destructive mutations intersecting a captured selection must remap a fresh semantic Range instead of trusting transient browser boundaries");
237
+ assert.match(applyMutation, /restoredSelection && forceRemap && typeof requestAnimationFrame[\s\S]*requestAnimationFrame\(\(\) => \{[\s\S]*selectionIntentRevision !== restoreIntentRevision[\s\S]*restoreSelection\(snapshot, \{ forceRemap: true \}\)/, "destructive selection restoration must survive the browser's deferred Range adjustment without clobbering a newer pointer or keyboard selection");
238
+ assert.match(renderer, /function invalidateSelection\(\{ surfaces = \[\] \} = \{\}\) \{[\s\S]*clearSelectionFor\(surfaces\)/, "explicit invalidation must be a first-class coordinator operation");
239
+
240
+ // Prevention of unapproved direct destructive transcript mutations.
241
+ assert.doesNotMatch(app, /elements\.chat\.(?:replaceChildren|replaceWith)\(|elements\.chat\.innerHTML\s*=/, "no direct destructive #chat mutation may bypass the coordinator");
242
+ assert.match(resetChatOutput, /transcriptRenderer\.replaceChildren\(elements\.chat/, "full chat resets must go through the coordinator");
243
+ for (const [name, source] of [
244
+ ["streaming markdown", renderStreamingMarkdown],
245
+ ["streaming thinking", renderThinkingMarkdown],
246
+ ["compact live output", flushCompactLiveOutput],
247
+ ["authoritative reconciliation", renderAllMessages],
248
+ ["live tool card", updateLiveToolCard],
249
+ ["mermaid renderer", renderMermaidDiagram],
250
+ ]) {
251
+ assert.doesNotMatch(source, /(?<!transcriptRenderer)\.(?:replaceChildren|replaceWith|replaceHtml)\(|\.innerHTML\s*=/, `${name} must not perform unapproved direct destructive transcript mutations`);
252
+ }
253
+
254
+ console.log("interaction-state-stability-static.test.mjs passed");
@@ -0,0 +1,55 @@
1
+ import assert from "node:assert/strict";
2
+ import { readFile } from "node:fs/promises";
3
+ import { dirname, join } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+
6
+ const root = join(dirname(fileURLToPath(import.meta.url)), "..");
7
+ const [app, html, css, serviceWorker, readme] = await Promise.all([
8
+ readFile(join(root, "public", "app.js"), "utf8"),
9
+ readFile(join(root, "public", "index.html"), "utf8"),
10
+ readFile(join(root, "public", "styles.css"), "utf8"),
11
+ readFile(join(root, "public", "service-worker.js"), "utf8"),
12
+ readFile(join(root, "README.md"), "utf8"),
13
+ ]);
14
+
15
+ assert.match(app, /MOBILE_CONTINUITY_STORAGE_KEY = "pi-webui-mobile-continuity-v1"/, "continuity state must be browser-scoped and versioned");
16
+ assert.match(app, /requiresReselect: true/, "restored attachment records must be metadata-only");
17
+ assert.match(app, /Reselect required/, "metadata-only attachment restoration must be labelled truthfully");
18
+ assert.match(app, /function retryMobileFailedSend\([\s\S]*?body: pending\.body[\s\S]*?original request identity/, "failed sends must require a manual retry with the original request body and identity");
19
+ assert.match(app, /error\?\.backendOffline === true[\s\S]*?mobileFailedSend =/, "manual failed-send recovery must be created only for ambiguous transport failures, not confirmed HTTP rejection");
20
+ assert.match(app, /MOBILE_FAILED_SEND_RECOVERY_TTL_MS = 10 \* 60 \* 1000[\s\S]*?recoveryAgeMs <= MOBILE_FAILED_SEND_RECOVERY_TTL_MS/, "persisted request identity must not outlive the server deduplication window");
21
+ assert.match(app, /!Array\.isArray\(mobileFailedSend\.body\?\.images\) \|\| mobileFailedSend\.body\.images\.length === 0[\s\S]*?!Array\.isArray\(failed\.body\.images\) \|\| failed\.body\.images\.length === 0/, "failed-send persistence and restore must agree on empty image arrays");
22
+ assert.match(app, /function scheduleMobileContinuityPersist\([\s\S]*?MOBILE_CONTINUITY_PERSIST_DEBOUNCE_MS/, "composer draft persistence must be debounced off the keystroke hot path");
23
+ assert.match(app, /This implementation intentionally never retries an\n \/\/ ambiguous mutation automatically/, "ambiguous prompt mutations must never replay automatically");
24
+ assert.match(html, /id="mobileFailedSendRecovery"[\s\S]*Not sent\.[\s\S]*id="mobileFailedSendRetryButton"[\s\S]*id="mobileFailedSendDiscardButton"/, "failed sends need visible Retry and Discard actions");
25
+ assert.match(app, /mobileButton\("Add Context"[\s\S]*mobileSetSurfacePage\("context"\)/, "the action sheet must expose unified context capture");
26
+ for (const source of ["Camera", "Photos", "Files", "Paste text"]) assert.match(app, new RegExp(source), `${source} must be represented in Add Context`);
27
+ assert.match(app, /Camera and photo access are requested by your browser only after you select them/, "capture permissions need contextual copy before the browser prompt");
28
+ assert.match(app, /active Web UI clients only/, "notification settings must state the active-client delivery limit");
29
+ assert.match(app, /mobileNotificationTarget\(\{ route: "activity", tabId, blockerId \}\)/, "blocker notifications must carry a versioned opaque target");
30
+ assert.match(app, /applyPendingMobileNavigationTarget\([\s\S]*?foreground reconcile/, "notification navigation must be deferred until reconciliation");
31
+ assert.match(app, /if \(targetTab\.id !== activeTabId\) await switchTab\(targetTab\.id\);[\s\S]*?if \(target\.blockerId && !mobileTargetBlockerExists/, "background-tab notification targets must switch before exact blocker validation");
32
+ assert.match(app, /That notification target is no longer available/, "stale targets need a visible fallback explanation");
33
+ assert.match(serviceWorker, /client\.postMessage\(\{ type: MOBILE_NAVIGATION_MESSAGE_TYPE, target \}\)/, "existing clients must focus and receive the exact target");
34
+ assert.match(serviceWorker, /openWindow\?\.\(targetUrl\)/, "no-client notification clicks must open only the bounded target URL");
35
+ assert.doesNotMatch(serviceWorker, /data\?\.url/, "service-worker fallback must not accept an arbitrary notification URL");
36
+ assert.match(app, /visibilitychange[\s\S]*?pageshow[\s\S]*?network online/, "visibility, page-show, and online returns must reconcile");
37
+ assert.match(app, /Continued while away · reconciled/, "return status must distinguish reconciled background continuation");
38
+ assert.match(app, /function renderMobileDiagnosticsPage\(/, "local diagnostics need a dedicated Copy/Clear surface");
39
+ assert.match(app, /function scrubMobileDiagnosticDetail\([\s\S]*?redacted potentially sensitive detail/, "diagnostic details must redact path-like and credential-like values");
40
+ assert.match(app, /excludes prompts, transcript text, paths, filenames, and credentials/, "diagnostics must document their privacy boundary");
41
+ assert.match(app, /function renderMobileInstallPage\(/, "install education must be contextual and dismissible");
42
+
43
+ assert.match(app, /TABLET_SHELL_STORAGE_KEY/, "tablet mode must use an independent browser flag");
44
+ assert.match(app, /initialUrlParams\.get\("tabletShell"\)/, "tablet mode must support an independent URL override");
45
+ assert.match(css, /@media \(min-width: 721px\) and \(max-width: 1050px\)/, "tablet layout must own only medium widths");
46
+ assert.match(css, /html\[data-tablet-shell="v2"\] \.mobile-shell-nav[\s\S]*?width: 7rem/, "tablet destinations must use a rail rather than the phone bottom bar");
47
+ assert.match(css, /html\[data-tablet-shell="v2"\] \.mobile-shell-surface[\s\S]*?width: min\(30rem, 72vw\)/, "tablet inspector must be a bounded right-side sheet");
48
+ assert.match(css, /html\[data-tablet-shell="v2"\] \.file-viewer-pane[\s\S]*?position: fixed[\s\S]*?inset: 0/, "tablet files must default to full-screen replacement");
49
+ assert.match(css, /and \(pointer: coarse\)[\s\S]*?min-height: 44px/, "coarse tablet pointers must retain the 44px target floor");
50
+ assert.match(serviceWorker, /const CACHE_NAME = "pi-webui-pwa-v61"/, "continuity/tablet assets need a coherent cache identity");
51
+ assert.match(html, /styles\.css\?v=92/, "tablet CSS must have a coherent HTML revision");
52
+ assert.match(html, /app\.js\?v=103/, "continuity app logic must have a coherent HTML revision");
53
+ assert.match(readme, /tabletShell=v2/, "tablet preview and rollback must be documented");
54
+
55
+ console.log("mobile-continuity-tablet-static.test.mjs passed");