@firstpick/pi-package-webui 0.8.5 → 0.8.6

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 (47) hide show
  1. package/README.md +23 -1
  2. package/bin/pi-webui.mjs +375 -30
  3. package/index.ts +8 -1
  4. package/lib/git-workflow-preferences.mjs +3 -0
  5. package/lib/session-summary-core.mjs +4 -3
  6. package/lib/trust-boundaries.mjs +13 -0
  7. package/lib/workspace-session-summaries.mjs +400 -0
  8. package/package.json +2 -2
  9. package/public/app.js +1197 -267
  10. package/public/index.html +76 -3
  11. package/public/service-worker.js +3 -1
  12. package/public/stream-output-controller.mjs +327 -0
  13. package/public/styles.css +249 -70
  14. package/public/theme-contract.mjs +244 -0
  15. package/session-summary.ts +164 -4
  16. package/tests/aur-review-widget-static.test.mjs +2 -1
  17. package/tests/browser/interaction-continuity.spec.mjs +2 -2
  18. package/tests/browser/session-summary.spec.mjs +131 -3
  19. package/tests/browser/stream-output-isolation.spec.mjs +510 -0
  20. package/tests/codex-fast-mode-static.test.mjs +1 -1
  21. package/tests/composer-action-grid-reorder-static.test.mjs +1 -1
  22. package/tests/fast-mode-client-static.test.mjs +2 -1
  23. package/tests/fixtures/fake-pi.mjs +203 -2
  24. package/tests/git-workflow-preferences.test.mjs +7 -1
  25. package/tests/guided-git-aur-review.test.mjs +4 -3
  26. package/tests/http-endpoints-harness.test.mjs +207 -6
  27. package/tests/mobile-continuity-tablet-static.test.mjs +1 -1
  28. package/tests/mobile-foundation-static.test.mjs +2 -3
  29. package/tests/mobile-phone-experience-static.test.mjs +1 -1
  30. package/tests/mobile-static.test.mjs +62 -29
  31. package/tests/native-parity.test.mjs +1 -1
  32. package/tests/open-issue-wizard-static.test.mjs +2 -3
  33. package/tests/persistent-ui-layout-static.test.mjs +1 -1
  34. package/tests/questionnaire-dialog.test.mjs +1 -1
  35. package/tests/remote-auth-settings-harness.test.mjs +9 -0
  36. package/tests/session-summary-core.test.mjs +183 -1
  37. package/tests/side-panel-section-reorder-static.test.mjs +1 -1
  38. package/tests/stream-lifecycle-core.test.mjs +134 -0
  39. package/tests/stream-output-controller.test.mjs +252 -0
  40. package/tests/stream-output-isolation-static.test.mjs +89 -0
  41. package/tests/streaming-ui-coupling.test.mjs +50 -0
  42. package/tests/subagent-gate-visibility.test.mjs +1 -1
  43. package/tests/subagent-launch-slots-static.test.mjs +1 -1
  44. package/tests/theme-contract.test.mjs +104 -0
  45. package/tests/theme-customizer-static.test.mjs +82 -0
  46. package/tests/theme-scheme-mode.test.mjs +15 -0
  47. package/tests/workspace-session-summaries.test.mjs +288 -0
@@ -0,0 +1,104 @@
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
+ import {
6
+ PI_THEME_EXPORT_FIELDS,
7
+ REQUIRED_THEME_TOKENS,
8
+ THEME_TOKEN_GROUPS,
9
+ ThemeContractError,
10
+ canonicalizeTheme,
11
+ effectiveThemeColors,
12
+ normalizeThemeFileName,
13
+ resolveThemeColor,
14
+ serializeTheme,
15
+ themeColorToRgb,
16
+ themeNameFromFileName,
17
+ validateTheme,
18
+ xterm256ToRgb,
19
+ } from "../public/theme-contract.mjs";
20
+
21
+ const root = join(dirname(fileURLToPath(import.meta.url)), "..");
22
+ const schemaPath = join(root, "node_modules", "@earendil-works", "pi-coding-agent", "dist", "modes", "interactive", "theme", "theme-schema.json");
23
+
24
+ function fixture(overrides = {}) {
25
+ return {
26
+ name: "contract-fixture",
27
+ vars: { primary: "#123456", nested: "primary", neutral: 244 },
28
+ colors: Object.fromEntries(REQUIRED_THEME_TOKENS.map((token, index) => [token, index % 3 === 0 ? "nested" : index % 3 === 1 ? 39 : ""])),
29
+ export: { pageBg: "primary", cardBg: 235, infoBg: "", backgroundImage: "url(/fixture.png)" },
30
+ ...overrides,
31
+ };
32
+ }
33
+
34
+ assert.equal(REQUIRED_THEME_TOKENS.length, 51, "the browser contract must expose exactly 51 required tokens");
35
+ assert.equal(new Set(REQUIRED_THEME_TOKENS).size, 51, "required tokens must be unique");
36
+ assert.equal(THEME_TOKEN_GROUPS.length, 7, "the documented token inventory has seven groups");
37
+ assert.deepEqual(THEME_TOKEN_GROUPS.map(({ tokens }) => tokens.length), [11, 11, 10, 3, 9, 6, 1]);
38
+
39
+ const installedSchema = JSON.parse(await readFile(schemaPath, "utf8"));
40
+ assert.deepEqual(
41
+ [...REQUIRED_THEME_TOKENS].sort(),
42
+ [...installedSchema.properties.colors.required].sort(),
43
+ "the shared contract must stay in exact parity with the installed Pi schema",
44
+ );
45
+ assert.deepEqual(
46
+ [...PI_THEME_EXPORT_FIELDS].sort(),
47
+ Object.keys(installedSchema.properties.export.properties).sort(),
48
+ "Pi-native export fields must match the installed schema",
49
+ );
50
+
51
+ const valid = fixture();
52
+ assert.deepEqual(validateTheme(valid), { ok: true, issues: [] });
53
+ assert.equal(validateTheme(fixture({ name: "Pi Theme 1" })).ok, true, "theme names must retain installed Pi schema compatibility");
54
+ assert.equal(resolveThemeColor("nested", valid.vars), "#123456");
55
+ assert.equal(themeColorToRgb("neutral", valid.vars), "#808080");
56
+ assert.equal(effectiveThemeColors(valid).thinkingMax, valid.colors.thinkingXhigh, "thinkingMax must fall back to thinkingXhigh");
57
+ const explicitMax = fixture({ colors: { ...valid.colors, thinkingMax: "primary" } });
58
+ assert.equal(effectiveThemeColors(explicitMax).thinkingMax, "primary");
59
+
60
+ const native = canonicalizeTheme(valid);
61
+ assert.deepEqual(Object.keys(native.export), ["pageBg", "cardBg", "infoBg"]);
62
+ assert.equal(Object.hasOwn(native.export, "backgroundImage"), false, "WebUI-only export fields must not enter Pi-native files");
63
+ assert.deepEqual(Object.keys(native.colors), REQUIRED_THEME_TOKENS, "canonical colors must retain documented order");
64
+ assert.deepEqual(Object.keys(native.vars), ["nested", "neutral", "primary"], "variables must serialize deterministically");
65
+ const serialized = serializeTheme(valid);
66
+ assert.equal(serialized.endsWith("\n"), true, "canonical JSON must have one trailing newline");
67
+ assert.equal(serialized, `${JSON.stringify(native, null, 2)}\n`);
68
+ assert.deepEqual(JSON.parse(serialized), native);
69
+
70
+ for (const [label, theme, expectedPath] of [
71
+ ["unknown root", { ...valid, secret: true }, "secret"],
72
+ ["unknown color", { ...valid, colors: { ...valid.colors, madeUp: "" } }, "colors.madeUp"],
73
+ ["missing required", { ...valid, colors: Object.fromEntries(Object.entries(valid.colors).filter(([key]) => key !== "accent")) }, "colors.accent"],
74
+ ["float", { ...valid, colors: { ...valid.colors, accent: 1.5 } }, "colors.accent"],
75
+ ["range", { ...valid, colors: { ...valid.colors, accent: 256 } }, "colors.accent"],
76
+ ["short hex", { ...valid, colors: { ...valid.colors, accent: "#fff" } }, "colors.accent"],
77
+ ["missing variable", { ...valid, colors: { ...valid.colors, accent: "absent" } }, "colors.accent"],
78
+ ["unknown export", { ...valid, export: { ...valid.export, arbitrary: "value" } }, "export.arbitrary"],
79
+ ["circular variable", { ...valid, vars: { first: "second", second: "first" } }, "vars.first"],
80
+ ]) {
81
+ const result = validateTheme(theme);
82
+ assert.equal(result.ok, false, `${label} must be rejected`);
83
+ assert.ok(result.issues.some(({ path }) => path === expectedPath), `${label} must identify ${expectedPath}`);
84
+ }
85
+ assert.equal(validateTheme(valid, { allowWebuiExport: false }).ok, false, "Pi-only validation must reject WebUI export fields");
86
+ assert.throws(() => canonicalizeTheme({ ...valid, unexpected: true }), ThemeContractError);
87
+
88
+ assert.equal(normalizeThemeFileName("my-theme.json"), "my-theme.json");
89
+ assert.equal(themeNameFromFileName("my-theme.json"), "my-theme");
90
+ for (const invalid of ["", ".json", "../theme.json", "nested/theme.json", "theme.txt", "space theme.json", `x${"y".repeat(75)}.json`]) {
91
+ assert.throws(() => normalizeThemeFileName(invalid), ThemeContractError, `${JSON.stringify(invalid)} must not be a save basename`);
92
+ }
93
+
94
+ assert.equal(xterm256ToRgb(0), "#000000");
95
+ assert.equal(xterm256ToRgb(15), "#ffffff");
96
+ assert.equal(xterm256ToRgb(16), "#000000");
97
+ assert.equal(xterm256ToRgb(21), "#0000ff");
98
+ assert.equal(xterm256ToRgb(39), "#00afff");
99
+ assert.equal(xterm256ToRgb(232), "#080808");
100
+ assert.equal(xterm256ToRgb(255), "#eeeeee");
101
+ assert.throws(() => xterm256ToRgb(-1), RangeError);
102
+ assert.throws(() => xterm256ToRgb(1.5), RangeError);
103
+
104
+ console.log("theme-contract: ok");
@@ -0,0 +1,82 @@
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
+ import { REQUIRED_THEME_TOKENS, THEME_TOKEN_GROUPS } from "../public/theme-contract.mjs";
6
+
7
+ const root = join(dirname(fileURLToPath(import.meta.url)), "..");
8
+ const [app, html, css, serviceWorker, pkg, readme] = await Promise.all([
9
+ readFile(join(root, "public", "app.js"), "utf8"),
10
+ readFile(join(root, "public", "index.html"), "utf8"),
11
+ readFile(join(root, "public", "styles.css"), "utf8"),
12
+ readFile(join(root, "public", "service-worker.js"), "utf8"),
13
+ readFile(join(root, "package.json"), "utf8"),
14
+ readFile(join(root, "README.md"), "utf8"),
15
+ ]);
16
+
17
+ assert.equal(THEME_TOKEN_GROUPS.length, 7, "customizer contract should expose seven labelled groups");
18
+ assert.equal(REQUIRED_THEME_TOKENS.length, 51, "customizer contract should expose exactly 51 required tokens");
19
+ assert.equal(new Set(REQUIRED_THEME_TOKENS).size, 51, "required customizer tokens should be unique");
20
+
21
+ assert.match(html, /id="themeCustomizeButton"[^>]*aria-haspopup="dialog"[^>]*aria-controls="themeCustomizerDialog"/, "theme controls should expose an accessible Customize dialog launcher");
22
+ assert.match(html, /<dialog id="themeCustomizerDialog"[^>]*aria-labelledby="themeCustomizerTitle"[^>]*aria-describedby="themeCustomizerDescription"/, "customizer should use a labelled native dialog");
23
+ for (const id of [
24
+ "themeCustomizerName", "themeCustomizerScope", "themeCustomizerVisualFields", "themeCustomizerThinkingMax",
25
+ "themeCustomizerVars", "themeCustomizerExportFields", "themeCustomizerJson", "themeCustomizerPreview",
26
+ "themeCustomizerStatus", "themeCustomizerCancelButton", "themeCustomizerResetButton", "themeCustomizerSaveButton",
27
+ "themeCustomizerOverwrite", "themeCustomizerOverwriteButton",
28
+ ]) {
29
+ assert.match(html, new RegExp(`id="${id}"`), `customizer should expose #${id}`);
30
+ }
31
+ assert.match(html, /<option id="themeCustomizerProjectOption" value="project">This project<\/option>[\s\S]*<option value="global">Global themes<\/option>/, "save destination should offer project and global scopes");
32
+ assert.match(html, /role="status" aria-live="polite" aria-atomic="true"/, "customizer should expose an atomic polite validation surface");
33
+ assert.match(html, /role="alert" hidden>[\s\S]*Replace this exact target\?/, "overwrite should use a hidden-until-needed alert naming the target");
34
+
35
+ assert.match(app, /from "\.\/theme-contract\.mjs"/, "frontend should consume the shared browser-safe theme contract");
36
+ assert.match(serviceWorker, /"\/theme-contract\.mjs"/, "the PWA app shell should cache the startup-critical theme contract");
37
+ assert.match(serviceWorker, /const CACHE_NAME = "pi-webui-pwa-v74"/, "adding the theme contract to the startup graph should advance the PWA cache identity");
38
+ assert.match(pkg, /node --check public\/theme-contract\.mjs/, "the package check should syntax-check the startup-critical theme contract");
39
+ assert.match(app, /function themeDraftFromCatalog\(theme, name = theme\?\.name\)[\s\S]*colors: cloneThemeDraft\(theme\?\.colors \|\| \{\}\)/, "catalog metadata should be projected into a schema-only editable draft");
40
+ assert.match(app, /for \(const \{ name, label \} of group\.tokens\)/, "visual controls should render from the exact shared token inventory");
41
+ assert.match(app, /row\.dataset\.themeToken = name/, "every required token should receive a stable visual row");
42
+ assert.match(app, /swatch\.type = "color"[\s\S]*value\.type = "text"/, "each visual row should pair a color picker with a raw Pi value control");
43
+ assert.match(app, /const direct = \/\^#\[0-9a-f\]\{6\}\$\/i\.test\(raw\)[\s\S]*swatch\.disabled = !direct[\s\S]*Terminal default; edit the value to replace it/, "variable and terminal-default values should not be silently flattened by the color picker");
44
+ assert.match(app, /validateTheme\(candidate, \{ allowWebuiExport: true \}\)/, "client feedback should validate through the shared contract");
45
+ assert.match(app, /Advanced JSON is invalid:[\s\S]*last valid preview remains active/, "invalid JSON should stay editable without replacing the valid preview");
46
+ assert.match(app, /acceptThemeCustomizerDraft\(candidate, \{ syncJson: false, syncControls: true \}\)/, "valid JSON should synchronize back to visual and optional controls");
47
+ assert.match(app, /elements\.themeCustomizerJson\.value = serializeTheme\(canonical/, "valid visual changes should synchronize canonical advanced JSON");
48
+ assert.match(app, /applyTheme\(canonical, \{ persist: false \}\)/, "live preview must use the non-persisting apply path");
49
+ assert.match(app, /themeColorToRgb\(value, theme\?\.vars \|\| \{\}, fallback\)/, "WebUI preview should convert integer xterm colors through the shared contract");
50
+
51
+ assert.match(app, /function restoreThemeCustomizerOpeningState\(generation\)[\s\S]*state\.generation !== generation[\s\S]*applyTheme\(state\.opening\.theme, \{ persist: false \}\)[\s\S]*setCustomBackgroundRecord\(state\.opening\.background\)[\s\S]*applyCustomBackgroundOverride\(\)/, "cancel should generation-guard restoration of theme, meta/scheme presentation, and custom background");
52
+ assert.match(app, /themeCustomizerDialog\?\.addEventListener\("cancel"[\s\S]*closeThemeCustomizer\(\{ restore: true \}\)/, "Escape should restore and close through the same cancel path");
53
+ assert.match(app, /async function switchTab\(tabId\)[\s\S]*if \(themeCustomizerState\) closeThemeCustomizer\(\{ restore: true \}\)[\s\S]*refreshThemeCatalog\(tabContext\)/, "tab switches should restore an open preview and refresh project-bound catalog metadata");
54
+ assert.doesNotMatch(app.slice(app.indexOf("function themeScopeLabel("), app.indexOf("function renderThemeSelect(")), /localStorage\.(?:setItem|removeItem)/, "customizer preview/save workflow must not mutate browser theme storage directly");
55
+
56
+ assert.match(app, /api\("\/api\/themes\/custom", \{[\s\S]*tabId: state\.tabContext\.tabId[\s\S]*scope,[\s\S]*fileName: `\$\{name\}\.json`[\s\S]*overwrite,[\s\S]*expectedMtimeMs:/, "save should bind the server-derived target to the opening active tab and explicit scope");
57
+ assert.match(app, /state\.overwrite = \{ signature: themeCustomizerDraftSignature\(state\), scope, fileName, mtimeMs: details\.mtimeMs \}/, "overwrite confirmation should bind target, draft signature, and server mtime");
58
+ assert.match(app, /invalidateThemeCustomizerOverwrite\(\);[\s\S]*Any draft, name, or destination change cancels this confirmation/, "editing should invalidate overwrite confirmation");
59
+ assert.match(app, /code === "THEME_CHANGED"[\s\S]*was not overwritten[\s\S]*fresh target-bound confirmation/, "stale overwrite should stop and require fresh confirmation");
60
+ assert.match(app, /themeCustomizerCancelButton\.disabled = !!state\?\.saving[\s\S]*themeCustomizerResetButton\.disabled = !!state\?\.saving/, "cancel and reset should be disabled while a theme save is in flight");
61
+ assert.match(app, /function closeThemeCustomizer[\s\S]*if \(state\.saving\)[\s\S]*Wait for the theme save to finish/, "closing should not imply an in-flight filesystem save was cancelled");
62
+ assert.match(app, /function setThemeCustomizerStatus[\s\S]*urgent \? "alert" : "status"[\s\S]*urgent \? "assertive" : "polite"/, "blocking customizer errors should use assertive alert semantics");
63
+ assert.match(app, /code === "THEME_EXISTS"\) showThemeCustomizerOverwrite/, "same-target conflicts should enter explicit overwrite UI");
64
+ assert.match(app, /theme\.custom[\s\S]*theme-scope-badge/, "custom search results should receive scope badges");
65
+ assert.match(app, /Saved \$\{response\.data\?\.fileName[\s\S]*run \/reload or restart[\s\S]*No Pi or browser theme setting was changed/, "save guidance should truthfully describe manual TUI reload and non-mutation");
66
+
67
+ assert.match(css, /\.theme-customizer-dialog \{[\s\S]*height: min\(92dvh, 58rem\)[\s\S]*overflow: hidden/, "desktop customizer should be viewport-bounded and internally scrollable");
68
+ assert.match(css, /\.theme-customizer-scroll \{[\s\S]*overflow-y: auto[\s\S]*overscroll-behavior: contain/, "long token controls should scroll inside the dialog");
69
+ assert.match(css, /\.theme-token-grid \{[\s\S]*grid-template-columns: repeat\(auto-fit, minmax\(min\(100%, 25rem\), 1fr\)\)/, "token columns should collapse based on their container before labels and inputs overlap");
70
+ assert.match(css, /\.theme-token-swatch-note \{[^}]*min-width: 0[^}]*overflow-wrap: anywhere/, "token helper text should wrap inside narrow rows");
71
+ assert.match(css, /\.theme-customizer-optional-fields fieldset \{[^}]*min-width: 0/, "optional field cards should be allowed to shrink inside the dialog");
72
+ assert.match(css, /\.theme-customizer-export-fields \{[\s\S]*grid-template-columns: repeat\(auto-fit, minmax\(min\(100%, 12rem\), 1fr\)\)/, "export color fields should wrap before their cards overflow");
73
+ assert.match(css, /\.theme-customizer-export-fields input \{[^}]*width: 100%[^}]*min-width: 0/, "export color inputs should stay within their grid tracks");
74
+ assert.match(css, /@media \(max-width: 720px\), \(pointer: coarse\) and \(hover: none\)[\s\S]*\.theme-customizer-dialog[\s\S]*width: 100vw[\s\S]*\.theme-token-grid,[\s\S]*grid-template-columns: minmax\(0, 1fr\)/, "phone/coarse layouts should become a safe one-column full-height editor");
75
+ assert.match(css, /\.extension-dialog\.theme-customizer-dialog \{[\s\S]*inset: 0;[\s\S]*height: var\(--visual-viewport-height, 100dvh\);[\s\S]*max-height: var\(--visual-viewport-height, 100dvh\);[\s\S]*overflow: hidden;[\s\S]*border-radius: 0;/, "the later generic mobile dialog rule must not override full-height customizer geometry");
76
+ assert.match(css, /\.theme-token-swatch \{[^}]*width: 44px[^}]*height: 44px/, "visual color targets should remain at least 44px");
77
+ assert.match(css, /env\(safe-area-inset-bottom\)/, "dialog actions should honor mobile safe-area insets");
78
+
79
+ assert.match(readme, /### Custom themes[\s\S]*exact 51 required theme tokens[\s\S]*last valid preview[\s\S]*This project[\s\S]*Global themes/, "README should document controls, validation, and both scopes");
80
+ assert.match(readme, /does not select the theme or mutate Pi\/browser settings[\s\S]*run `\/reload` or restart Pi/, "README should document non-persistence and truthful TUI activation");
81
+
82
+ console.log("theme-customizer-static: all assertions passed");
@@ -96,6 +96,21 @@ assert.match(
96
96
  /async function applySchemeTheme\(options = \{\}\) \{\s*await setThemeByName\(effectiveThemeName\(\), \{ \.\.\.options, persist: false \}\);\s*\}/,
97
97
  "applySchemeTheme must never persist",
98
98
  );
99
+ assert.match(
100
+ app,
101
+ /function acceptThemeCustomizerDraft\([\s\S]*?applyTheme\(canonical, \{ persist: false \}\)/,
102
+ "custom theme live preview must use a non-persisting apply path",
103
+ );
104
+ assert.match(
105
+ app,
106
+ /function restoreThemeCustomizerOpeningState\(generation\)[\s\S]*?applyTheme\(state\.opening\.theme, \{ persist: false \}\)/,
107
+ "customizer cancel must restore presentation without persisting a selection",
108
+ );
109
+ assert.doesNotMatch(
110
+ app.slice(app.indexOf("function themeScopeLabel("), app.indexOf("function renderThemeSelect(")),
111
+ /storeTheme(?:Name|Mode)|storeSchemeTheme|setThemeByName\([^;]*persist: true/,
112
+ "customizer internals must not bypass chooseTheme or mutate Light/Dark/Auto persistence",
113
+ );
99
114
 
100
115
  // Auto mode also works on MediaQueryList implementations without addEventListener
101
116
  // (legacy addListener API), matching the mobileViewMedia wiring.
@@ -0,0 +1,288 @@
1
+ import assert from "node:assert/strict";
2
+ import { mkdtemp, mkdir, rm, symlink, utimes, writeFile } from "node:fs/promises";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import {
6
+ WORKSPACE_SUMMARY_COMMAND_MAX_CHARS,
7
+ WORKSPACE_SUMMARY_MAX_LIVE_BYTES,
8
+ WORKSPACE_SUMMARY_PROTOCOL_VERSION,
9
+ WORKSPACE_SUMMARY_TOOL_MAX_CHARS,
10
+ canonicalizeWorkspaceCwd,
11
+ createLiveSummaryPayload,
12
+ discoverPersistedWorkspaceSummaries,
13
+ formatWorkspaceSummariesForCommand,
14
+ formatWorkspaceSummariesForTool,
15
+ mergeWorkspaceSessionSummaries,
16
+ normalizeLiveSummaryPayload,
17
+ workspaceCwdsEqual,
18
+ } from "../lib/workspace-session-summaries.mjs";
19
+ import { SESSION_SUMMARY_STATE_TYPE } from "../lib/session-summary-core.mjs";
20
+
21
+ function summaryState(sessionId, summaryMarkdown, {
22
+ title = "Workspace task",
23
+ generatedAt = "2026-08-05T12:00:00.000Z",
24
+ version = 1,
25
+ } = {}) {
26
+ return {
27
+ version,
28
+ source: {
29
+ sessionId,
30
+ leafId: "leaf",
31
+ fingerprint: "f".repeat(64),
32
+ entryCount: 4,
33
+ },
34
+ result: { title, summaryMarkdown },
35
+ generation: {
36
+ provider: "test-provider",
37
+ modelId: "test-model",
38
+ thinkingLevel: "low",
39
+ promptRevision: "session-summary-v1",
40
+ },
41
+ generatedAt,
42
+ settledTurnOrdinal: 2,
43
+ };
44
+ }
45
+
46
+ function sessionJsonl({ id, cwd, summary, name, headerVersion = 3, extraLines = [] }) {
47
+ const entries = [
48
+ { type: "session", version: headerVersion, id, timestamp: "2026-08-05T11:00:00.000Z", cwd },
49
+ { type: "message", id: "raw00001", parentId: null, timestamp: "2026-08-05T11:01:00.000Z", message: { role: "user", content: "RAW_TRANSCRIPT_SECRET ghp_rawtranscript1234567890 /home/private/.pi/agent/sessions/private.jsonl" } },
50
+ ...(name ? [{ type: "session_info", id: "name0001", parentId: "raw00001", timestamp: "2026-08-05T11:02:00.000Z", name }] : []),
51
+ ...extraLines,
52
+ { type: "custom", id: "sum00001", parentId: name ? "name0001" : "raw00001", timestamp: "2026-08-05T12:00:00.000Z", customType: SESSION_SUMMARY_STATE_TYPE, data: summary },
53
+ ];
54
+ return `${entries.map((entry) => typeof entry === "string" ? entry : JSON.stringify(entry)).join("\n")}\n`;
55
+ }
56
+
57
+ function livePayload(cwd, sessionId, summaryMarkdown, generatedAt = "2026-08-05T13:00:00.000Z") {
58
+ return {
59
+ version: WORKSPACE_SUMMARY_PROTOCOL_VERSION,
60
+ sessionId,
61
+ cwd: canonicalizeWorkspaceCwd(cwd),
62
+ title: `Title ${sessionId}`,
63
+ summaryMarkdown,
64
+ generatedAt,
65
+ sessionName: `Session ${sessionId}`,
66
+ };
67
+ }
68
+
69
+ const root = await mkdtemp(path.join(os.tmpdir(), "workspace-session-summaries-"));
70
+ try {
71
+ const workspace = path.join(root, "workspace");
72
+ const otherWorkspace = path.join(root, "other");
73
+ const sessionDir = path.join(root, "sessions");
74
+ await Promise.all([mkdir(workspace), mkdir(otherWorkspace), mkdir(sessionDir)]);
75
+
76
+ assert.equal(canonicalizeWorkspaceCwd(path.join(workspace, ".")), workspace);
77
+ assert.equal(workspaceCwdsEqual(workspace, path.join(workspace, "nested", "..")), true);
78
+ assert.equal(canonicalizeWorkspaceCwd("\0unsafe"), undefined);
79
+ if (process.platform !== "win32") {
80
+ const alias = path.join(root, "workspace-alias");
81
+ await symlink(workspace, alias, "dir");
82
+ assert.equal(workspaceCwdsEqual(workspace, alias), true, "symlink and real CWD should canonicalize equally");
83
+ }
84
+
85
+ const currentId = "current-session";
86
+ const sameId = "same-session";
87
+ const otherId = "other-session";
88
+ const invalidId = "invalid-session";
89
+ await writeFile(path.join(sessionDir, "current.jsonl"), sessionJsonl({
90
+ id: currentId,
91
+ cwd: workspace,
92
+ summary: summaryState(currentId, "Current persisted copy"),
93
+ }));
94
+ await writeFile(path.join(sessionDir, "same.jsonl"), sessionJsonl({
95
+ id: sameId,
96
+ cwd: workspace,
97
+ name: "Same workspace",
98
+ summary: summaryState(sameId, "Implement durable discovery."),
99
+ extraLines: ["{malformed-json", "x".repeat(30 * 1024)],
100
+ }));
101
+ await writeFile(path.join(sessionDir, "other.jsonl"), sessionJsonl({
102
+ id: otherId,
103
+ cwd: otherWorkspace,
104
+ summary: summaryState(otherId, "Must not cross CWD boundaries."),
105
+ }));
106
+ await writeFile(path.join(sessionDir, "invalid-version.jsonl"), sessionJsonl({
107
+ id: invalidId,
108
+ cwd: workspace,
109
+ headerVersion: 2,
110
+ summary: summaryState(invalidId, "Must not migrate or consume old formats."),
111
+ }));
112
+ await writeFile(path.join(sessionDir, "wrong-state-session.jsonl"), sessionJsonl({
113
+ id: "header-session",
114
+ cwd: workspace,
115
+ summary: summaryState("forged-session", "Mismatched state identity."),
116
+ }));
117
+
118
+ const now = new Date("2026-08-05T14:00:00.000Z");
119
+ await utimes(path.join(sessionDir, "same.jsonl"), now, now);
120
+ const discovered = await discoverPersistedWorkspaceSummaries({ cwd: workspace, sessionDir, currentSessionId: currentId });
121
+ assert.deepEqual(discovered.map((entry) => entry.sessionId), [sameId]);
122
+ assert.equal(discovered[0].source, "persisted");
123
+ assert.equal(discovered[0].sessionName, "Same workspace");
124
+ assert.equal(Object.hasOwn(discovered[0], "sessionFile"), false);
125
+ assert.equal(JSON.stringify(discovered).includes("RAW_TRANSCRIPT_SECRET"), false);
126
+ assert.equal(JSON.stringify(discovered).includes(sessionDir), false);
127
+
128
+ const oversizedFileId = "tail-session";
129
+ await writeFile(path.join(sessionDir, "tail.jsonl"), sessionJsonl({
130
+ id: oversizedFileId,
131
+ cwd: workspace,
132
+ summary: summaryState(oversizedFileId, "Found from a bounded tail read."),
133
+ extraLines: [{ type: "message", id: "large001", parentId: "raw00001", timestamp: "2026-08-05T11:30:00.000Z", message: { role: "user", content: "z".repeat(80_000) } }],
134
+ }));
135
+ const tailDiscovered = await discoverPersistedWorkspaceSummaries({
136
+ cwd: workspace,
137
+ sessionDir,
138
+ currentSessionId: currentId,
139
+ maxFileBytes: 32 * 1024,
140
+ });
141
+ assert.equal(tailDiscovered.some((entry) => entry.sessionId === oversizedFileId), true, "bounded tail should retain a recent summary after an oversized line");
142
+ const escapedSessionId = "escaped-session";
143
+ await writeFile(path.join(sessionDir, "escaped.jsonl"), sessionJsonl({
144
+ id: escapedSessionId,
145
+ cwd: workspace,
146
+ summary: summaryState(escapedSessionId, "\\".repeat(16_000)),
147
+ }));
148
+ const escapedDiscovered = await discoverPersistedWorkspaceSummaries({ cwd: workspace, sessionDir, currentSessionId: currentId });
149
+ assert.equal(escapedDiscovered.some((entry) => entry.sessionId === escapedSessionId), true, "valid decoded summaries remain discoverable when JSON escaping expands the custom-entry line");
150
+
151
+ const currentState = summaryState(currentId, "Current work summary.");
152
+ const publication = createLiveSummaryPayload({ cwd: workspace, state: currentState, sessionName: "Current worker" });
153
+ assert.ok(publication);
154
+ assert.equal(Buffer.byteLength(JSON.stringify(publication)) <= WORKSPACE_SUMMARY_MAX_LIVE_BYTES, true);
155
+ assert.equal(normalizeLiveSummaryPayload(publication)?.sessionId, currentId);
156
+ const redactedPublication = createLiveSummaryPayload({
157
+ cwd: workspace,
158
+ state: summaryState(currentId, [
159
+ "Token ghp_abcdefghijklmnopqrstuvwxyz123456 at /home/private/.pi/agent/sessions/private.jsonl",
160
+ "Windows C:\\Users\\alice\\.pi\\agent\\sessions\\--repo--\\secret.jsonl",
161
+ "AWS_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPLE",
162
+ "npm_auth_token=npm_abcdefghijklmnopqrstuvwxyz123456",
163
+ "-----BEGIN PRIVATE KEY-----\nprivate-material\n-----END PRIVATE KEY-----",
164
+ ].join("\n")),
165
+ sessionName: "authorization: secret-value",
166
+ });
167
+ const redactedPublicationText = JSON.stringify(redactedPublication);
168
+ for (const sensitive of ["ghp_abcdefghijklmnopqrstuvwxyz123456", "private.jsonl", "secret.jsonl", "AKIAIOSFODNN7EXAMPLE", "npm_abcdefghijklmnopqrstuvwxyz123456", "private-material", "secret-value"]) {
169
+ assert.equal(redactedPublicationText.includes(sensitive), false, `live publication redacts ${sensitive} before transport`);
170
+ }
171
+ assert.equal(normalizeLiveSummaryPayload({ ...publication, transcript: "private" }), undefined, "unknown live fields should fail closed");
172
+ assert.equal(normalizeLiveSummaryPayload({ ...publication, version: 2 }), undefined);
173
+ assert.equal(normalizeLiveSummaryPayload({ ...publication, cwd: `${otherWorkspace}/nested/..` }), undefined, "non-canonical live CWD should fail");
174
+ assert.equal(normalizeLiveSummaryPayload({ ...publication, summaryMarkdown: "x".repeat(13 * 1024) }), undefined);
175
+ assert.equal(normalizeLiveSummaryPayload({ ...publication, generatedAt: "not-a-date" }), undefined);
176
+ assert.equal(normalizeLiveSummaryPayload({ ...publication, sessionId: "a\tb" }), undefined, "control characters in identifiers fail closed instead of being normalized");
177
+ assert.equal(createLiveSummaryPayload({ cwd: workspace, state: summaryState(currentId, "x".repeat(16 * 1024)) }).summaryMarkdown.length <= 12 * 1024, true);
178
+ assert.equal(createLiveSummaryPayload({
179
+ cwd: path.join(root, "w".repeat(3900)),
180
+ state: summaryState(currentId, "x".repeat(16 * 1024)),
181
+ }), undefined, "aggregate live payloads above the 15 KiB transport envelope fail closed");
182
+
183
+ const liveSame = livePayload(workspace, sameId, "Newer live copy.");
184
+ const liveDisconnected = livePayload(workspace, "disconnected", "Disconnected and stale.");
185
+ const liveCrossCwd = livePayload(otherWorkspace, "cross-cwd", "Wrong workspace.");
186
+ const liveSelf = livePayload(workspace, "self-live", "Self sender.");
187
+ const snapshot = mergeWorkspaceSessionSummaries({
188
+ cwd: workspace,
189
+ currentSessionId: currentId,
190
+ currentState,
191
+ currentSessionName: "Current worker",
192
+ selfSenderId: "sender-self",
193
+ liveAvailable: true,
194
+ connectedSessions: [
195
+ { senderId: "sender-live", cwd: workspace },
196
+ { senderId: "sender-cross", cwd: otherWorkspace },
197
+ { senderId: "sender-self", cwd: workspace },
198
+ ],
199
+ livePeers: [
200
+ { senderId: "sender-live", payload: liveSame, receivedAt: "2026-08-05T13:01:00.000Z" },
201
+ { senderId: "sender-gone", payload: liveDisconnected },
202
+ { senderId: "sender-cross", payload: liveCrossCwd },
203
+ { senderId: "sender-self", payload: liveSelf },
204
+ ],
205
+ persisted: [
206
+ ...discovered,
207
+ { sessionId: "persisted-new", title: "Persisted", summaryMarkdown: "Historical work.", generatedAt: "2026-08-05T14:00:00.000Z", modifiedAt: "2026-08-05T14:00:00.000Z" },
208
+ { sessionId: "persisted-old", title: "Persisted", summaryMarkdown: "Older historical work.", generatedAt: "2026-08-04T14:00:00.000Z", modifiedAt: "2026-08-04T14:00:00.000Z" },
209
+ ],
210
+ });
211
+ assert.deepEqual(snapshot.entries.map((entry) => [entry.sessionId, entry.source]), [
212
+ [currentId, "current"],
213
+ [sameId, "live"],
214
+ ["persisted-new", "persisted"],
215
+ ["persisted-old", "persisted"],
216
+ ]);
217
+ assert.deepEqual(snapshot.counts, { current: 1, live: 1, persisted: 2, peers: 3 });
218
+ assert.equal(snapshot.entries.some((entry) => entry.sessionId === "disconnected"), false);
219
+ assert.equal(snapshot.entries.some((entry) => entry.sessionId === "cross-cwd"), false);
220
+ const claimedIdCollision = mergeWorkspaceSessionSummaries({
221
+ cwd: workspace,
222
+ liveAvailable: true,
223
+ connectedSessions: [{ id: "sender-a", cwd: workspace }, { id: "sender-b", cwd: workspace }],
224
+ livePeers: [
225
+ { senderId: "sender-a", payload: livePayload(workspace, "claimed", "Sender A") },
226
+ { senderId: "sender-b", payload: livePayload(workspace, "claimed", "Sender B") },
227
+ ],
228
+ });
229
+ assert.equal(claimedIdCollision.counts.live, 2, "authoritative live senders are not collapsed by a payload-declared Pi session ID");
230
+ assert.deepEqual(new Set(claimedIdCollision.entries.map((entry) => entry.senderId)), new Set(["sender-a", "sender-b"]));
231
+
232
+ const fallback = mergeWorkspaceSessionSummaries({
233
+ cwd: workspace,
234
+ currentSessionId: currentId,
235
+ currentState,
236
+ liveAvailable: false,
237
+ connectedSessions: [{ senderId: "sender-live", cwd: workspace }],
238
+ livePeers: [{ senderId: "sender-live", payload: liveSame }],
239
+ persisted: discovered,
240
+ });
241
+ assert.equal(fallback.entries.find((entry) => entry.sessionId === sameId)?.source, "persisted");
242
+ assert.equal(fallback.liveAvailable, false);
243
+
244
+ const privateSnapshot = mergeWorkspaceSessionSummaries({
245
+ cwd: workspace,
246
+ currentSessionId: currentId,
247
+ currentState: summaryState(currentId, [
248
+ "Safe goal.",
249
+ "/home/private/.pi/agent/sessions/--private--/secret.jsonl",
250
+ "authorization: BearerValueThatMustNotAppear",
251
+ "ghp_abcdefghijklmnopqrstuvwxyz123456",
252
+ ].join("\n")),
253
+ liveAvailable: false,
254
+ });
255
+ const toolText = formatWorkspaceSummariesForTool(privateSnapshot);
256
+ const commandText = formatWorkspaceSummariesForCommand(privateSnapshot);
257
+ for (const text of [toolText, commandText]) {
258
+ assert.equal(text.includes("secret.jsonl"), false);
259
+ assert.equal(text.includes("BearerValueThatMustNotAppear"), false);
260
+ assert.equal(text.includes("ghp_abcdefghijklmnopqrstuvwxyz123456"), false);
261
+ assert.match(text, /reference-only/i);
262
+ assert.match(text, /intercom/i);
263
+ }
264
+ assert.equal(toolText.length <= WORKSPACE_SUMMARY_TOOL_MAX_CHARS, true);
265
+ assert.equal(commandText.length <= WORKSPACE_SUMMARY_COMMAND_MAX_CHARS, true);
266
+
267
+ const manyPersisted = Array.from({ length: 40 }, (_, index) => ({
268
+ sessionId: `bounded-${String(index).padStart(2, "0")}`,
269
+ title: `Bounded ${index}`,
270
+ summaryMarkdown: "content ".repeat(1000),
271
+ generatedAt: new Date(Date.UTC(2026, 7, 5, 10, index)).toISOString(),
272
+ modifiedAt: new Date(Date.UTC(2026, 7, 5, 10, index)).toISOString(),
273
+ }));
274
+ const boundedSnapshot = mergeWorkspaceSessionSummaries({ cwd: workspace, persisted: manyPersisted, maxEntries: 3 });
275
+ assert.deepEqual(boundedSnapshot.entries.map((entry) => entry.sessionId), ["bounded-39", "bounded-38", "bounded-37"]);
276
+ const boundedToolText = formatWorkspaceSummariesForTool(boundedSnapshot, { maxChars: 1000 });
277
+ const boundedCommandText = formatWorkspaceSummariesForCommand(boundedSnapshot, { maxChars: 700 });
278
+ assert.equal(boundedToolText.length <= 1000, true);
279
+ assert.equal(boundedCommandText.length <= 700, true);
280
+ for (const text of [boundedToolText, boundedCommandText]) {
281
+ assert.match(text, /untrusted|reference-only/i, "safety framing survives aggregate truncation");
282
+ assert.match(text, /intercom/i, "coordination guidance survives aggregate truncation");
283
+ }
284
+
285
+ console.log("workspace-session-summaries tests passed");
286
+ } finally {
287
+ await rm(root, { recursive: true, force: true });
288
+ }