@firstpick/pi-package-webui 0.8.5 → 0.8.7

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 (110) hide show
  1. package/README.md +18 -584
  2. package/bin/pi-webui-launcher.mjs +22 -0
  3. package/bin/pi-webui-update-supervisor.mjs +86 -0
  4. package/bin/pi-webui.mjs +933 -554
  5. package/index.ts +16 -6
  6. package/lib/component-update-state.mjs +21 -0
  7. package/lib/git-workflow-preferences.mjs +20 -2
  8. package/lib/optional-feature-catalog.mjs +1 -0
  9. package/lib/sampling-parameter-capabilities.mjs +160 -0
  10. package/lib/session-summary-core.mjs +4 -3
  11. package/lib/session-summary-preferences.mjs +16 -1
  12. package/lib/subagent-launch-slots.mjs +14 -2
  13. package/lib/trust-boundaries.mjs +16 -0
  14. package/lib/update/executor.mjs +99 -0
  15. package/lib/update/journal.mjs +175 -0
  16. package/lib/update/owners.mjs +70 -0
  17. package/lib/update/plan.mjs +134 -0
  18. package/lib/update/resolver.mjs +168 -0
  19. package/lib/update/supervisor.mjs +238 -0
  20. package/lib/update/verify.mjs +52 -0
  21. package/lib/update-commands.mjs +25 -13
  22. package/lib/webui-workspaces.mjs +17 -1
  23. package/lib/workspace-session-summaries.mjs +400 -0
  24. package/package.json +4 -4
  25. package/public/app.js +2487 -349
  26. package/public/index.html +200 -51
  27. package/public/middle-button-drag-scroll.mjs +154 -0
  28. package/public/sampling-parameter-controls.mjs +361 -0
  29. package/public/service-worker.js +5 -1
  30. package/public/stream-output-controller.mjs +327 -0
  31. package/public/styles.css +666 -71
  32. package/public/theme-contract.mjs +244 -0
  33. package/session-summary.ts +164 -4
  34. package/tests/aur-review-widget-static.test.mjs +2 -1
  35. package/tests/boot-failure-diagnostics.test.mjs +3 -3
  36. package/tests/browser/control-deck-component-updates.spec.mjs +20 -22
  37. package/tests/browser/interaction-continuity.spec.mjs +2 -2
  38. package/tests/browser/middle-button-drag-scroll.spec.mjs +145 -0
  39. package/tests/browser/persistent-ui-layout.spec.mjs +68 -23
  40. package/tests/browser/sampling-tooltip.spec.mjs +228 -0
  41. package/tests/browser/session-summary.spec.mjs +131 -3
  42. package/tests/browser/stream-output-isolation.spec.mjs +510 -0
  43. package/tests/browser/update-reconnect.spec.mjs +92 -0
  44. package/tests/codex-fast-mode-static.test.mjs +2 -2
  45. package/tests/common-options-submenus-interaction-static.test.mjs +172 -0
  46. package/tests/common-options-submenus-markup-static.test.mjs +152 -0
  47. package/tests/component-update-api-static.test.mjs +22 -61
  48. package/tests/composer-action-grid-reorder-static.test.mjs +3 -3
  49. package/tests/control-deck-component-updates-static.test.mjs +13 -237
  50. package/tests/durable-rpc-supervisor-harness.test.mjs +3 -1
  51. package/tests/fast-mode-client-static.test.mjs +3 -2
  52. package/tests/feature-decision-output-popup-static.test.mjs +2 -2
  53. package/tests/feature-system-prompt-optional-feature-static.test.mjs +49 -0
  54. package/tests/fixtures/fake-pi.mjs +269 -2
  55. package/tests/fixtures/update/tree-timeout-descendant.mjs +6 -0
  56. package/tests/fixtures/update/tree-timeout-parent.mjs +11 -0
  57. package/tests/git-footer-context-menu-static.test.mjs +58 -0
  58. package/tests/git-workflow-preferences.test.mjs +7 -1
  59. package/tests/guided-git-aur-review.test.mjs +4 -3
  60. package/tests/http-endpoints-harness.test.mjs +274 -23
  61. package/tests/middle-button-drag-scroll-static.test.mjs +24 -0
  62. package/tests/middle-button-drag-scroll.test.mjs +170 -0
  63. package/tests/mobile-continuity-tablet-static.test.mjs +3 -3
  64. package/tests/mobile-foundation-static.test.mjs +5 -6
  65. package/tests/mobile-phone-experience-static.test.mjs +1 -1
  66. package/tests/mobile-static.test.mjs +85 -50
  67. package/tests/native-parity.test.mjs +1 -1
  68. package/tests/open-issue-wizard-static.test.mjs +2 -3
  69. package/tests/optional-feature-migration-frontend.test.mjs +9 -5
  70. package/tests/persistent-ui-layout-static.test.mjs +13 -2
  71. package/tests/questionnaire-dialog.test.mjs +3 -3
  72. package/tests/remote-auth-settings-harness.test.mjs +43 -0
  73. package/tests/rpc-supervisor-host.test.mjs +11 -2
  74. package/tests/safety-guard-auto-review-harness.test.mjs +117 -0
  75. package/tests/safety-guard-auto-review-static.test.mjs +34 -0
  76. package/tests/sampling-native-controls-user-flow.test.mjs +752 -0
  77. package/tests/sampling-parameter-capabilities.test.mjs +167 -0
  78. package/tests/sampling-parameter-controls.test.mjs +241 -0
  79. package/tests/session-sampling-helper.test.mjs +228 -0
  80. package/tests/session-sampling-http.test.mjs +168 -0
  81. package/tests/session-sampling-ui-static.test.mjs +370 -0
  82. package/tests/session-summary-core.test.mjs +205 -10
  83. package/tests/side-panel-section-height-removal-static.test.mjs +34 -0
  84. package/tests/side-panel-section-reorder-static.test.mjs +3 -3
  85. package/tests/staged-content-hash-contract.test.mjs +52 -11
  86. package/tests/stream-lifecycle-core.test.mjs +134 -0
  87. package/tests/stream-output-controller.test.mjs +252 -0
  88. package/tests/stream-output-isolation-static.test.mjs +89 -0
  89. package/tests/streaming-ui-coupling.test.mjs +50 -0
  90. package/tests/subagent-gate-visibility.test.mjs +1 -1
  91. package/tests/subagent-launch-slots-static.test.mjs +1 -1
  92. package/tests/subagent-launch-slots.test.mjs +18 -1
  93. package/tests/theme-contract.test.mjs +104 -0
  94. package/tests/theme-customizer-static.test.mjs +82 -0
  95. package/tests/theme-scheme-mode.test.mjs +15 -0
  96. package/tests/ui-layout-settings.test.mjs +18 -1
  97. package/tests/update-api-harness.test.mjs +111 -0
  98. package/tests/update-commands.test.mjs +15 -45
  99. package/tests/update-executor-process-tree-harness.test.mjs +22 -0
  100. package/tests/update-journal-harness.test.mjs +59 -0
  101. package/tests/update-lock-multiprocess-harness.test.mjs +46 -0
  102. package/tests/update-owners.test.mjs +27 -0
  103. package/tests/update-plan.test.mjs +58 -0
  104. package/tests/update-resolver.test.mjs +56 -0
  105. package/tests/update-supervisor-harness.test.mjs +57 -0
  106. package/tests/update-tab-restore-harness.test.mjs +24 -0
  107. package/tests/update-verify.test.mjs +31 -0
  108. package/tests/workspace-files-live-updates-static.test.mjs +13 -4
  109. package/tests/workspace-session-summaries.test.mjs +288 -0
  110. package/webui-rpc-helper.mjs +119 -0
@@ -0,0 +1,244 @@
1
+ export const PI_THEME_SCHEMA_URL = "https://raw.githubusercontent.com/earendil-works/pi/main/packages/coding-agent/src/modes/interactive/theme/theme-schema.json";
2
+
3
+ export const THEME_TOKEN_GROUPS = Object.freeze([
4
+ { id: "core", label: "Core UI", tokens: [
5
+ ["accent", "Accent"], ["border", "Border"], ["borderAccent", "Accent border"],
6
+ ["borderMuted", "Muted border"], ["success", "Success"], ["error", "Error"],
7
+ ["warning", "Warning"], ["muted", "Muted text"], ["dim", "Dim text"],
8
+ ["text", "Text"], ["thinkingText", "Thinking text"],
9
+ ] },
10
+ { id: "content", label: "Backgrounds & Content", tokens: [
11
+ ["selectedBg", "Selected background"], ["userMessageBg", "User message background"],
12
+ ["userMessageText", "User message text"], ["customMessageBg", "Custom message background"],
13
+ ["customMessageText", "Custom message text"], ["customMessageLabel", "Custom message label"],
14
+ ["toolPendingBg", "Pending tool background"], ["toolSuccessBg", "Successful tool background"],
15
+ ["toolErrorBg", "Failed tool background"], ["toolTitle", "Tool title"], ["toolOutput", "Tool output"],
16
+ ] },
17
+ { id: "markdown", label: "Markdown", tokens: [
18
+ ["mdHeading", "Heading"], ["mdLink", "Link"], ["mdLinkUrl", "Link URL"],
19
+ ["mdCode", "Inline code"], ["mdCodeBlock", "Code block"], ["mdCodeBlockBorder", "Code block border"],
20
+ ["mdQuote", "Quote"], ["mdQuoteBorder", "Quote border"], ["mdHr", "Horizontal rule"],
21
+ ["mdListBullet", "List bullet"],
22
+ ] },
23
+ { id: "diffs", label: "Tool Diffs", tokens: [
24
+ ["toolDiffAdded", "Added line"], ["toolDiffRemoved", "Removed line"], ["toolDiffContext", "Context line"],
25
+ ] },
26
+ { id: "syntax", label: "Syntax Highlighting", tokens: [
27
+ ["syntaxComment", "Comment"], ["syntaxKeyword", "Keyword"], ["syntaxFunction", "Function"],
28
+ ["syntaxVariable", "Variable"], ["syntaxString", "String"], ["syntaxNumber", "Number"],
29
+ ["syntaxType", "Type"], ["syntaxOperator", "Operator"], ["syntaxPunctuation", "Punctuation"],
30
+ ] },
31
+ { id: "thinking", label: "Thinking Levels", tokens: [
32
+ ["thinkingOff", "Off"], ["thinkingMinimal", "Minimal"], ["thinkingLow", "Low"],
33
+ ["thinkingMedium", "Medium"], ["thinkingHigh", "High"], ["thinkingXhigh", "Extra high"],
34
+ ] },
35
+ { id: "bash", label: "Bash Mode", tokens: [["bashMode", "Bash mode"]] },
36
+ ].map((group) => Object.freeze({
37
+ ...group,
38
+ tokens: Object.freeze(group.tokens.map(([name, label]) => Object.freeze({ name, label }))),
39
+ })));
40
+
41
+ export const REQUIRED_THEME_TOKENS = Object.freeze(THEME_TOKEN_GROUPS.flatMap((group) => group.tokens.map(({ name }) => name)));
42
+ export const OPTIONAL_THEME_TOKENS = Object.freeze(["thinkingMax"]);
43
+ export const PI_THEME_EXPORT_FIELDS = Object.freeze(["pageBg", "cardBg", "infoBg"]);
44
+ export const WEBUI_THEME_EXPORT_FIELDS = Object.freeze([
45
+ "backgroundImage", "backgroundOverlay", "backgroundSize", "backgroundPosition", "backgroundRepeat",
46
+ ]);
47
+
48
+ const ROOT_FIELDS = new Set(["$schema", "name", "vars", "colors", "export"]);
49
+ const COLOR_FIELDS = new Set([...REQUIRED_THEME_TOKENS, ...OPTIONAL_THEME_TOKENS]);
50
+ const EXPORT_FIELDS = new Set([...PI_THEME_EXPORT_FIELDS, ...WEBUI_THEME_EXPORT_FIELDS]);
51
+ const FILE_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,74}\.json$/;
52
+ const HEX_COLOR_PATTERN = /^#[0-9a-fA-F]{6}$/;
53
+
54
+ export class ThemeContractError extends Error {
55
+ constructor(message, issues = []) {
56
+ super(message);
57
+ this.name = "ThemeContractError";
58
+ this.code = "THEME_INVALID";
59
+ this.issues = issues;
60
+ }
61
+ }
62
+
63
+ function isRecord(value) {
64
+ return !!value && typeof value === "object" && !Array.isArray(value);
65
+ }
66
+
67
+ function sortedRecord(record) {
68
+ return Object.fromEntries(Object.keys(record || {}).sort().map((key) => [key, record[key]]));
69
+ }
70
+
71
+ function issue(path, message) {
72
+ return { path, message };
73
+ }
74
+
75
+ function validateValue(value, path, variableNames, issues) {
76
+ if (Number.isInteger(value)) {
77
+ if (value < 0 || value > 255) issues.push(issue(path, "must be an integer from 0 to 255"));
78
+ return;
79
+ }
80
+ if (typeof value !== "string") {
81
+ issues.push(issue(path, "must be a 6-digit hex color, xterm index, variable reference, or empty string"));
82
+ return;
83
+ }
84
+ if (value === "" || HEX_COLOR_PATTERN.test(value) || variableNames.has(value)) return;
85
+ issues.push(issue(path, `references an undeclared variable: ${JSON.stringify(value)}`));
86
+ }
87
+
88
+ function validateVariableCycles(vars, issues) {
89
+ const state = new Map();
90
+ const visit = (name, stack) => {
91
+ const current = state.get(name);
92
+ if (current === "done") return;
93
+ if (current === "visiting") {
94
+ issues.push(issue(`vars.${name}`, `contains a circular variable reference: ${[...stack, name].join(" -> ")}`));
95
+ return;
96
+ }
97
+ state.set(name, "visiting");
98
+ const value = vars[name];
99
+ if (typeof value === "string" && value !== "" && !HEX_COLOR_PATTERN.test(value) && Object.hasOwn(vars, value)) {
100
+ visit(value, [...stack, name]);
101
+ }
102
+ state.set(name, "done");
103
+ };
104
+ for (const name of Object.keys(vars)) visit(name, []);
105
+ }
106
+
107
+ export function normalizeThemeFileName(value) {
108
+ const fileName = String(value || "").trim();
109
+ if (!FILE_NAME_PATTERN.test(fileName) || fileName === ".json" || fileName.includes("..")) {
110
+ throw new ThemeContractError("Theme fileName must be a safe .json basename (letters, numbers, dots, underscores, and hyphens; 1-80 characters).", [
111
+ issue("fileName", "is not a safe theme JSON basename"),
112
+ ]);
113
+ }
114
+ return fileName;
115
+ }
116
+
117
+ export function themeNameFromFileName(value) {
118
+ return normalizeThemeFileName(value).slice(0, -5);
119
+ }
120
+
121
+ export function validateTheme(theme, { allowWebuiExport = true } = {}) {
122
+ const issues = [];
123
+ if (!isRecord(theme)) return { ok: false, issues: [issue("theme", "must be an object")] };
124
+
125
+ for (const key of Object.keys(theme)) {
126
+ if (!ROOT_FIELDS.has(key)) issues.push(issue(key, "is not a supported Pi theme field"));
127
+ }
128
+ if (typeof theme.name !== "string" || theme.name.length === 0 || theme.name.includes("/")) {
129
+ issues.push(issue("name", "must be a non-empty string containing no slash"));
130
+ }
131
+ if (theme.$schema !== undefined && (typeof theme.$schema !== "string" || !theme.$schema.trim())) {
132
+ issues.push(issue("$schema", "must be a non-empty string when present"));
133
+ }
134
+
135
+ const vars = theme.vars === undefined ? {} : theme.vars;
136
+ if (!isRecord(vars)) issues.push(issue("vars", "must be an object when present"));
137
+ const safeVars = isRecord(vars) ? vars : {};
138
+ const variableNames = new Set(Object.keys(safeVars));
139
+ for (const name of variableNames) {
140
+ if (!name || HEX_COLOR_PATTERN.test(name)) issues.push(issue(`vars.${name}`, "must be a non-empty non-hex variable name"));
141
+ validateValue(safeVars[name], `vars.${name}`, variableNames, issues);
142
+ }
143
+ validateVariableCycles(safeVars, issues);
144
+
145
+ if (!isRecord(theme.colors)) {
146
+ issues.push(issue("colors", "must be an object"));
147
+ } else {
148
+ for (const key of Object.keys(theme.colors)) {
149
+ if (!COLOR_FIELDS.has(key)) issues.push(issue(`colors.${key}`, "is not a supported Pi color token"));
150
+ }
151
+ for (const token of REQUIRED_THEME_TOKENS) {
152
+ if (!Object.hasOwn(theme.colors, token)) issues.push(issue(`colors.${token}`, "is required"));
153
+ }
154
+ for (const token of [...REQUIRED_THEME_TOKENS, ...OPTIONAL_THEME_TOKENS]) {
155
+ if (Object.hasOwn(theme.colors, token)) validateValue(theme.colors[token], `colors.${token}`, variableNames, issues);
156
+ }
157
+ }
158
+
159
+ if (theme.export !== undefined) {
160
+ if (!isRecord(theme.export)) {
161
+ issues.push(issue("export", "must be an object when present"));
162
+ } else {
163
+ for (const key of Object.keys(theme.export)) {
164
+ if (!EXPORT_FIELDS.has(key) || (!allowWebuiExport && WEBUI_THEME_EXPORT_FIELDS.includes(key))) {
165
+ issues.push(issue(`export.${key}`, "is not a supported Pi theme export field"));
166
+ }
167
+ }
168
+ for (const key of PI_THEME_EXPORT_FIELDS) {
169
+ if (Object.hasOwn(theme.export, key)) validateValue(theme.export[key], `export.${key}`, variableNames, issues);
170
+ }
171
+ for (const key of WEBUI_THEME_EXPORT_FIELDS) {
172
+ if (Object.hasOwn(theme.export, key) && typeof theme.export[key] !== "string") {
173
+ issues.push(issue(`export.${key}`, "must be a string"));
174
+ }
175
+ }
176
+ }
177
+ }
178
+ return { ok: issues.length === 0, issues };
179
+ }
180
+
181
+ export function canonicalizeTheme(theme, options = {}) {
182
+ const result = validateTheme(theme, options);
183
+ if (!result.ok) throw new ThemeContractError(`Invalid Pi theme: ${result.issues.map(({ path, message }) => `${path} ${message}`).join("; ")}`, result.issues);
184
+ const canonical = {
185
+ $schema: typeof theme.$schema === "string" && theme.$schema.trim() ? theme.$schema.trim() : PI_THEME_SCHEMA_URL,
186
+ name: theme.name,
187
+ };
188
+ if (theme.vars && Object.keys(theme.vars).length) canonical.vars = sortedRecord(theme.vars);
189
+ canonical.colors = {};
190
+ for (const token of REQUIRED_THEME_TOKENS) canonical.colors[token] = theme.colors[token];
191
+ if (Object.hasOwn(theme.colors, "thinkingMax")) canonical.colors.thinkingMax = theme.colors.thinkingMax;
192
+ if (theme.export) {
193
+ const exportColors = {};
194
+ for (const key of PI_THEME_EXPORT_FIELDS) {
195
+ if (Object.hasOwn(theme.export, key)) exportColors[key] = theme.export[key];
196
+ }
197
+ if (Object.keys(exportColors).length) canonical.export = exportColors;
198
+ }
199
+ return canonical;
200
+ }
201
+
202
+ export function serializeTheme(theme, options = {}) {
203
+ return `${JSON.stringify(canonicalizeTheme(theme, options), null, 2)}\n`;
204
+ }
205
+
206
+ export function effectiveThemeColors(theme) {
207
+ const canonical = canonicalizeTheme(theme, { allowWebuiExport: true });
208
+ return {
209
+ ...canonical.colors,
210
+ thinkingMax: canonical.colors.thinkingMax ?? canonical.colors.thinkingXhigh,
211
+ };
212
+ }
213
+
214
+ export function resolveThemeColor(value, vars = {}, stack = []) {
215
+ if (value === "" || typeof value === "number" || HEX_COLOR_PATTERN.test(String(value))) return value;
216
+ if (typeof value !== "string" || !Object.hasOwn(vars, value)) throw new ThemeContractError(`Unknown theme variable: ${String(value)}`);
217
+ if (stack.includes(value)) throw new ThemeContractError(`Circular theme variable: ${[...stack, value].join(" -> ")}`);
218
+ return resolveThemeColor(vars[value], vars, [...stack, value]);
219
+ }
220
+
221
+ export function xterm256ToRgb(index) {
222
+ if (!Number.isInteger(index) || index < 0 || index > 255) throw new RangeError("xterm color index must be an integer from 0 to 255");
223
+ const ansi = [
224
+ "#000000", "#800000", "#008000", "#808000", "#000080", "#800080", "#008080", "#c0c0c0",
225
+ "#808080", "#ff0000", "#00ff00", "#ffff00", "#0000ff", "#ff00ff", "#00ffff", "#ffffff",
226
+ ];
227
+ if (index < 16) return ansi[index];
228
+ if (index >= 232) {
229
+ const level = 8 + (index - 232) * 10;
230
+ return `#${level.toString(16).padStart(2, "0").repeat(3)}`;
231
+ }
232
+ const offset = index - 16;
233
+ const levels = [0, 95, 135, 175, 215, 255];
234
+ const red = levels[Math.floor(offset / 36)];
235
+ const green = levels[Math.floor((offset % 36) / 6)];
236
+ const blue = levels[offset % 6];
237
+ return `#${[red, green, blue].map((channel) => channel.toString(16).padStart(2, "0")).join("")}`;
238
+ }
239
+
240
+ export function themeColorToRgb(value, vars = {}, fallback = "#000000") {
241
+ const resolved = resolveThemeColor(value, vars);
242
+ if (resolved === "") return fallback;
243
+ return typeof resolved === "number" ? xterm256ToRgb(resolved) : resolved.toLowerCase();
244
+ }
@@ -1,8 +1,10 @@
1
1
  import { randomUUID } from "node:crypto";
2
+ import path from "node:path";
2
3
  import { completeSimple } from "@earendil-works/pi-ai/compat";
3
4
  import type { ExtensionAPI, ExtensionCommandContext, ExtensionContext } from "@earendil-works/pi-coding-agent";
4
5
  import { getMarkdownTheme } from "@earendil-works/pi-coding-agent";
5
6
  import { Markdown } from "@earendil-works/pi-tui";
7
+ import { Type } from "typebox";
6
8
  import {
7
9
  SESSION_SUMMARY_DISPLAY_TYPE,
8
10
  SESSION_SUMMARY_MAX_OUTPUT_TOKENS,
@@ -29,6 +31,13 @@ import {
29
31
  supportedSessionSummaryThinkingLevels,
30
32
  writeSessionSummaryPreferences,
31
33
  } from "./lib/session-summary-preferences.mjs";
34
+ import {
35
+ createLiveSummaryPayload,
36
+ discoverPersistedWorkspaceSummaries,
37
+ formatWorkspaceSummariesForCommand,
38
+ formatWorkspaceSummariesForTool,
39
+ mergeWorkspaceSessionSummaries,
40
+ } from "./lib/workspace-session-summaries.mjs";
32
41
 
33
42
  type SummaryContext = ExtensionContext | ExtensionCommandContext;
34
43
  type CompleteFunction = typeof completeSimple;
@@ -170,6 +179,133 @@ async function runSetup(pi: ExtensionAPI, ctx: ExtensionCommandContext): Promise
170
179
  export function createSessionSummaryExtension({ completeFn = completeSimple }: { completeFn?: CompleteFunction } = {}) {
171
180
  return function registerSessionSummary(pi: ExtensionAPI): void {
172
181
  let selfGeneratedName: { sessionId: string; name: string } | undefined;
182
+ let activeContext: SummaryContext | undefined;
183
+ let liveAvailable = false;
184
+ let activeChannel: any;
185
+ let channelRegistered = false;
186
+ const livePeers = new Map<string, { senderId: string; payload: unknown; receivedAt?: string }>();
187
+
188
+ const channelIsLive = (): boolean => {
189
+ try {
190
+ const snapshot = activeChannel?.snapshot?.();
191
+ return snapshot?.connected === true && snapshot?.supported === true;
192
+ } catch {
193
+ return false;
194
+ }
195
+ };
196
+
197
+ const publishLiveSummary = (ctx: SummaryContext | undefined = activeContext): void => {
198
+ if (!ctx || !activeChannel || !channelIsLive()) return;
199
+ try {
200
+ const state = latestSummaryState(ctx.sessionManager.getBranch());
201
+ if (!state) return;
202
+ const payload = createLiveSummaryPayload({ cwd: ctx.cwd, state, sessionName: pi.getSessionName() });
203
+ if (payload) activeChannel.publish(payload, { audience: "capable" });
204
+ } catch {
205
+ // The optional live channel must never break local summary behavior.
206
+ }
207
+ };
208
+
209
+ const setupLiveChannel = (channel: any): void => {
210
+ if (!channel || typeof channel.snapshot !== "function" || typeof channel.publish !== "function" || typeof channel.listSessions !== "function") return;
211
+ activeChannel = channel;
212
+ liveAvailable = channelIsLive();
213
+ if (liveAvailable) publishLiveSummary();
214
+ };
215
+
216
+ const handleLiveChannelEvent = (event: any): void => {
217
+ if (!event || typeof event.type !== "string") return;
218
+ if (event.type === "connection") {
219
+ liveAvailable = event.connected === true && event.supported === true;
220
+ if (!liveAvailable) {
221
+ livePeers.clear();
222
+ } else {
223
+ publishLiveSummary();
224
+ }
225
+ return;
226
+ }
227
+ if (event.type === "message" && typeof event.fromSessionId === "string") {
228
+ livePeers.set(event.fromSessionId, {
229
+ senderId: event.fromSessionId,
230
+ payload: event.payload,
231
+ receivedAt: new Date().toISOString(),
232
+ });
233
+ return;
234
+ }
235
+ if (event.type === "session_left" && typeof event.sessionId === "string") {
236
+ livePeers.delete(event.sessionId);
237
+ return;
238
+ }
239
+ if (event.type === "session_joined") {
240
+ if (typeof event.session?.id === "string") livePeers.delete(event.session.id);
241
+ publishLiveSummary();
242
+ }
243
+ };
244
+
245
+ const registerLiveChannel = (): void => {
246
+ if (channelRegistered || !pi.events || typeof pi.events.emit !== "function") return;
247
+ channelRegistered = true;
248
+ try {
249
+ pi.events.emit("intercom:extension-register", {
250
+ namespace: "firstpick/session-summary/v1",
251
+ ownerEligible: false,
252
+ onReady: setupLiveChannel,
253
+ onEvent: handleLiveChannelEvent,
254
+ });
255
+ } catch {
256
+ // pi-intercom is optional; persisted discovery remains available.
257
+ }
258
+ };
259
+
260
+ const getWorkspaceSnapshot = async (ctx: SummaryContext) => {
261
+ const cwd = ctx.cwd;
262
+ const currentSessionId = ctx.sessionManager.getSessionId();
263
+ const currentState = latestSummaryState(ctx.sessionManager.getBranch());
264
+ const currentSessionName = pi.getSessionName();
265
+ const sessionFile = ctx.sessionManager.getSessionFile();
266
+ const configuredSessionDir = (ctx.sessionManager as any).getSessionDir?.();
267
+ const sessionDir = typeof configuredSessionDir === "string" && configuredSessionDir
268
+ ? configuredSessionDir
269
+ : sessionFile ? path.dirname(sessionFile) : undefined;
270
+ const persisted = await discoverPersistedWorkspaceSummaries({ cwd, sessionDir, currentSessionId });
271
+
272
+ let connectedSessions: any[] = [];
273
+ liveAvailable = channelIsLive();
274
+ if (liveAvailable) {
275
+ try {
276
+ connectedSessions = await activeChannel.listSessions();
277
+ } catch {
278
+ liveAvailable = false;
279
+ }
280
+ }
281
+
282
+ return mergeWorkspaceSessionSummaries({
283
+ cwd,
284
+ currentSessionId,
285
+ currentState,
286
+ currentSessionName,
287
+ livePeers: [...livePeers.values()],
288
+ connectedSessions,
289
+ persisted,
290
+ liveAvailable,
291
+ });
292
+ };
293
+
294
+ pi.registerTool({
295
+ name: "workspace_session_summaries",
296
+ label: "Workspace Session Summaries",
297
+ description: "Show bounded generated summaries from current, connected, and persisted Pi sessions in the same canonical working directory so overlap can be identified before writes.",
298
+ promptSnippet: "Inspect same-CWD session summaries before potentially overlapping repository work",
299
+ promptGuidelines: [
300
+ "Use workspace_session_summaries when another Pi session in the same working directory may overlap the current work.",
301
+ "After workspace_session_summaries, compare goals, files or symbols, decisions, and next steps; when overlap is material or ownership is unclear, coordinate through intercom before writing.",
302
+ ],
303
+ parameters: Type.Object({}, { additionalProperties: false }),
304
+ async execute(_toolCallId, _params, _signal, _onUpdate, ctx) {
305
+ const snapshot = await getWorkspaceSnapshot(ctx);
306
+ return { content: [{ type: "text", text: formatWorkspaceSummariesForTool(snapshot) }], details: snapshot.counts };
307
+ },
308
+ });
173
309
 
174
310
  const publishCurrentState = async (ctx: SummaryContext): Promise<void> => {
175
311
  const state = latestSummaryState(ctx.sessionManager.getBranch());
@@ -239,7 +375,7 @@ export function createSessionSummaryExtension({ completeFn = completeSimple }: {
239
375
  return { stale: true };
240
376
  }
241
377
 
242
- const currentName = pi.getSessionName();
378
+ const currentName = typeof (pi as any).getSessionName === "function" ? (pi as any).getSessionName() : undefined;
243
379
  const applyTitle = shouldApplySummaryTitle({
244
380
  candidate: output.title,
245
381
  currentSessionName: currentName,
@@ -285,6 +421,7 @@ export function createSessionSummaryExtension({ completeFn = completeSimple }: {
285
421
  sendRpc(pi, ctx, "title", { title: output.title });
286
422
  }
287
423
  sendRpc(pi, ctx, "success", { title: state.result.title, summaryMarkdown: state.result.summaryMarkdown });
424
+ publishLiveSummary(ctx);
288
425
  if (!ctx.sessionManager.getSessionFile() && manual) ctx.ui.notify("Summary created in memory; this session has no durable session file.", "warning");
289
426
  return { state, appliedTitle: applyTitle };
290
427
  } catch (error) {
@@ -319,6 +456,7 @@ export function createSessionSummaryExtension({ completeFn = completeSimple }: {
319
456
  });
320
457
 
321
458
  pi.on("session_info_changed", (event, ctx) => {
459
+ activeContext = ctx;
322
460
  if (selfGeneratedName?.sessionId === ctx.sessionManager.getSessionId() && selfGeneratedName.name === event.name) {
323
461
  selfGeneratedName = undefined;
324
462
  return;
@@ -328,20 +466,26 @@ export function createSessionSummaryExtension({ completeFn = completeSimple }: {
328
466
  version: 1,
329
467
  explicit: event.name !== undefined,
330
468
  });
469
+ publishLiveSummary(ctx);
331
470
  });
332
471
 
333
472
  pi.on("session_start", async (_event, ctx) => {
334
473
  selfGeneratedName = undefined;
474
+ activeContext = ctx;
475
+ registerLiveChannel();
335
476
  try {
336
477
  await publishCurrentState(ctx);
478
+ publishLiveSummary(ctx);
337
479
  } catch (error) {
338
480
  sendRpc(pi, ctx, "failure", { message: errorMessage(error) });
339
481
  }
340
482
  });
341
483
 
342
484
  pi.on("session_tree", async (_event, ctx) => {
485
+ activeContext = ctx;
343
486
  try {
344
487
  await publishCurrentState(ctx);
488
+ publishLiveSummary(ctx);
345
489
  } catch (error) {
346
490
  sendRpc(pi, ctx, "failure", { message: errorMessage(error) });
347
491
  }
@@ -349,6 +493,10 @@ export function createSessionSummaryExtension({ completeFn = completeSimple }: {
349
493
 
350
494
  pi.on("session_shutdown", () => {
351
495
  selfGeneratedName = undefined;
496
+ activeContext = undefined;
497
+ activeChannel = undefined;
498
+ liveAvailable = false;
499
+ livePeers.clear();
352
500
  scheduler.abort();
353
501
  });
354
502
 
@@ -364,8 +512,20 @@ export function createSessionSummaryExtension({ completeFn = completeSimple }: {
364
512
  };
365
513
 
366
514
  pi.registerCommand("summary", {
367
- description: "Show the latest session summary or generate one; use /summary refresh to force an update",
515
+ description: "Show the latest session summary or generate one; use /summary refresh to force an update, or /summary workspace to view all workspace session summaries",
368
516
  handler: async (args, ctx) => {
517
+ const trimmed = args.trim().toLowerCase();
518
+ if (trimmed === "workspace") {
519
+ const snapshot = await getWorkspaceSnapshot(ctx);
520
+ const text = formatWorkspaceSummariesForCommand(snapshot);
521
+ pi.appendEntry(SESSION_SUMMARY_DISPLAY_TYPE, {
522
+ version: 1,
523
+ title: "Workspace session summaries",
524
+ summaryMarkdown: text,
525
+ });
526
+ return;
527
+ }
528
+
369
529
  const preferences = await readSessionSummaryPreferences().catch((error) => {
370
530
  ctx.ui.notify(`Session summary settings failed: ${errorMessage(error)}`, "error");
371
531
  return undefined;
@@ -376,9 +536,9 @@ export function createSessionSummaryExtension({ completeFn = completeSimple }: {
376
536
  await generateManual(ctx);
377
537
  } else {
378
538
  const state = latestSummaryState(ctx.sessionManager.getBranch());
379
- const refresh = args.trim().toLowerCase() === "refresh";
539
+ const refresh = trimmed === "refresh";
380
540
  if (args.trim() && !refresh) {
381
- ctx.ui.notify("Usage: /summary [refresh]", "warning");
541
+ ctx.ui.notify("Usage: /summary [refresh | workspace]", "warning");
382
542
  return;
383
543
  }
384
544
  if (!state || refresh) await generateManual(ctx);
@@ -21,6 +21,7 @@ assert.match(payloadParser, /decision\.reviewedFingerprint !== payload\.fingerpr
21
21
  assert.match(payloadParser, /stagedPayload \? decision\.reviewedStagedContentHash !== payload\.stagedContentHash/, "payload parsing should bind staged terminal decisions to the staged-content hash");
22
22
  assert.match(payloadParser, /payload\.changedFiles\.length >= payload\.changedFileTotal/, "payload parsing should reject equality at the truncated-file boundary");
23
23
  assert.match(app, /function renderAurReviewWidget\(\)[\s\S]*Review changes[\s\S]*Refresh[\s\S]*Approve[\s\S]*Decline[\s\S]*Close[\s\S]*openAurReviewReportInViewer\(reportPath, payload\.repoRoot\)/, "renderer should open reports against the payload's repo root rather than the tab cwd");
24
+ assert.match(app, /payload\.origin === "guided-git" && payload\.scope === "staged" && payload\.decision\.state === "approved"[\s\S]*return null/, "an approved Guided Git staged review should close its manual review card");
24
25
  assert.match(app, /async function openAurReviewReportInViewer\(path = "", repoRoot = ""\)[\s\S]*\/api\/aur-review\/report-content[\s\S]*readOnly: true/s, "report viewing must use the narrow read-only canonical-root endpoint");
25
26
  assert.match(app, /viewer\.readOnly === true \|\| !viewer\.dirty[\s\S]*viewer\.readOnly === true \|\| !viewerPath/s, "repo-root report views must not enable generic save or default-editor actions");
26
27
  assert.match(app, /function aurReviewActionButton\(label, action, className = ""\)[\s\S]*action === "review"[\s\S]*openGitChangesDialog\(\)[\s\S]*`\/aur-review \$\{action\}`/, "Review changes should reuse the current Git diff dialog and other controls should call canonical extension commands");
@@ -32,7 +33,7 @@ assert.match(css, /\.aur-review-widget \{[\s\S]*\.aur-review-actions[\s\S]*\.aur
32
33
  assert.equal(JSON.parse(pkg).optionalDependencies?.["@firstpick/pi-extension-aur-review"], undefined, "WebUI must not reference the unpublished review extension from clean npm installs");
33
34
  assert.equal(JSON.parse(pkg).pi?.extensions?.some((entry) => String(entry).includes("pi-extension-aur-review")), false, "WebUI must not bundle an unpublished nested review extension path");
34
35
  assert.match(optionalFeatureCatalog, /\["aurReview", "@firstpick\/pi-extension-aur-review", "\^0\.1\.1"\]/, "optional-feature catalog should retain the future/local review companion mapping without bundling it");
35
- assert.match(server, /"aur-review-payload\.mjs", "guided-git-command-state\.mjs", "guided-git-review-state\.mjs"/, "server must serve every browser module used by the review gate");
36
+ assert.match(server, /STATIC_PUBLIC_FILE_EXTENSIONS[\s\S]*"\.mjs"/, "server must serve typed browser modules from the public asset boundary");
36
37
  assert.match(server, /STAGED_CONTENT_HASH_DOMAIN = "firstpick\/aur-review\/staged-content\/v1\\0"[\s\S]*git diff --cached[\s\S]*\/api\/git-workflow\/staged-content/, "server must expose the bounded read-only staged-content hash helper");
37
38
  assert.match(server, /async function getAurReviewReportContentData\(tab, \{ path: requestedPath = "", repoRoot = "" \} = \{\}\)[\s\S]*repoRoot !== root[\s\S]*lstat\(targetPath\)[\s\S]*isSymbolicLink\(\)[\s\S]*readBoundedAurReviewReport[\s\S]*\/api\/aur-review\/report-content/s, "server must bind report reads to the canonical Git root and reject symlinked paths through a dedicated read-only route");
38
39
  assert.match(server, /entry\.name\.startsWith\("pi-"\)[\s\S]*packageNameForResourcePath\(path\.join\(candidate, "package\.json"\)\)/, "workspace optional-package discovery must recognize the pi-extension-aur-review sibling by manifest name");
@@ -65,7 +65,7 @@ function makeEnvironment({
65
65
  reload: new FakeElement(),
66
66
  copyStatus: new FakeElement(),
67
67
  };
68
- const styleLink = new FakeElement({ href: "http://127.0.0.1:31415/styles.css?v=98", sheet: stylesheetLoaded ? {} : null });
68
+ const styleLink = new FakeElement({ href: "http://127.0.0.1:31415/styles.css?v=104", sheet: stylesheetLoaded ? {} : null });
69
69
  const listeners = new Map();
70
70
  const timers = new Map();
71
71
  let timerId = 0;
@@ -84,7 +84,7 @@ function makeEnvironment({
84
84
  removeEventListener(name) { listeners.delete(name); },
85
85
  };
86
86
  const document = {
87
- currentScript: new FakeElement({ dataset: { appSrc: "/app.js?v=113" } }),
87
+ currentScript: new FakeElement({ dataset: { appSrc: "/app.js?v=120" } }),
88
88
  readyState: "complete",
89
89
  querySelector(selector) {
90
90
  return {
@@ -232,7 +232,7 @@ for (const moduleName of startupModuleNames) {
232
232
  assert.ok(serviceWorker.includes(`"/${moduleName}"`), `the PWA app shell should include every app.js startup module: ${moduleName}`);
233
233
  }
234
234
  assert.match(serviceWorker, /pi-webui-pwa-v\d+/, "the app-shell cache should retain a versioned identity");
235
- assert.ok(html.indexOf('id="webuiBootLoader"') < html.indexOf("/app.js?v=113"), "the inline loader should own app module startup");
235
+ assert.ok(html.indexOf('id="webuiBootLoader"') < html.indexOf("/app.js?v=120"), "the inline loader should own app module startup");
236
236
  assert.doesNotMatch(html, /<script type="module" src="\/app\.js/, "the app module should not bypass the guarded loader");
237
237
 
238
238
  console.log("boot-failure-diagnostics.test.mjs passed");
@@ -86,26 +86,21 @@ test("component tags and dialogs expose safe background update lifecycle", async
86
86
  await route.fulfill({
87
87
  status: 200,
88
88
  contentType: "application/json",
89
- body: JSON.stringify({ ok: true, data: { version: "0.83.0", body: "Fixture release notes", url: "https://example.test/pi" } }),
89
+ body: JSON.stringify({ ok: true, data: { version: "0.84.0", body: "Fixture v0.84.0 release notes", url: "https://example.test/pi/v0.84.0" } }),
90
90
  });
91
91
  });
92
- await page.route("**/api/component-update", async (route) => {
92
+ const plan = { transactionId: "browser-pi-plan", digest: "a".repeat(64), targets: [{ id: "pi", currentVersion: "0.83.0", targetVersion: "0.84.0" }], refusals: [] };
93
+ await page.route("**/api/update/plan", async (route) => {
93
94
  const body = route.request().postDataJSON();
94
- requests.push({ method: route.request().method(), body });
95
- const target = body?.target;
95
+ requests.push({ endpoint: "plan", method: route.request().method(), body });
96
+ await route.fulfill({ status: 201, contentType: "application/json", body: JSON.stringify({ ok: true, data: { plan } }) });
97
+ });
98
+ await page.route("**/api/update/apply", async (route) => {
99
+ const body = route.request().postDataJSON();
100
+ requests.push({ endpoint: "apply", method: route.request().method(), body });
96
101
  status.updateInProgress = true;
97
- status.componentUpdates[target] = {
98
- ...status.componentUpdates[target],
99
- state: "running",
100
- canStart: false,
101
- message: `Updating ${target === "pi" ? "Pi" : "Web UI"}…`,
102
- error: "",
103
- };
104
- await route.fulfill({
105
- status: 202,
106
- contentType: "application/json",
107
- body: JSON.stringify({ ok: true, data: status.componentUpdates[target] }),
108
- });
102
+ status.componentUpdates.pi = { ...status.componentUpdates.pi, state: "running", canStart: false, message: "Updating Pi…", error: "" };
103
+ await route.fulfill({ status: 202, contentType: "application/json", body: JSON.stringify({ ok: true, data: { state: "applying", outcome: "success", receipts: [{ targetId: "pi", status: "success" }] } }) });
109
104
  });
110
105
  await page.route("**/api/update-status*", async (route) => {
111
106
  if (status.componentUpdates.pi.state === "running") {
@@ -144,18 +139,21 @@ test("component tags and dialogs expose safe background update lifecycle", async
144
139
  await piTag.click();
145
140
  const piDialog = page.locator("#piReleaseNotesDialog");
146
141
  await expect(piDialog).toBeVisible();
142
+ await expect(page.locator("#piReleaseNotesTitle")).toHaveText("Pi v0.84.0 release notes");
143
+ await expect(page.locator("#piReleaseNotesBody")).toContainText("Fixture v0.84.0 release notes");
144
+ await expect(page.locator("#piReleaseNotesGithubLink")).toHaveAttribute("href", "https://example.test/pi/v0.84.0");
147
145
  await expect(page.locator("#piComponentUpdateStatus")).toContainText("Pi v0.83.0 → v0.84.0 is available");
148
146
  await page.locator("#piComponentUpdateButton").click();
149
147
  await expect(page.locator("#confirmationDialog")).toBeVisible();
150
- await expect(page.locator("#confirmationSummary")).toContainText("Web UI server and running Pi tabs are not restarted");
148
+ await expect(page.locator("#confirmationSummary")).toContainText("Bundled Pi updates are staged with the current Web UI in a side-by-side managed runtime");
151
149
  await page.locator("#confirmationConfirmButton").click();
152
150
 
153
- await expect(piTag).toHaveAttribute("data-update-state", "running");
154
- await expect(piTag).toHaveAccessibleName(/update running/);
155
- await expect(page.locator("#piComponentUpdateButton")).toBeDisabled();
156
- assert.deepEqual(requests, [{ method: "POST", body: { target: "pi" } }], "the dialog must submit exactly one Pi-only POST");
151
+ assert.deepEqual(requests, [
152
+ { endpoint: "plan", method: "POST", body: { targets: ["pi"] } },
153
+ { endpoint: "apply", method: "POST", body: { transactionId: plan.transactionId, planDigest: plan.digest } },
154
+ ], "the dialog must create one target-only plan and apply only its transaction id plus digest");
157
155
 
158
- await expect(piTag).toHaveAttribute("data-update-state", "succeeded", { timeout: 5_000 });
156
+ await expect(piTag).toHaveAttribute("data-update-state", "succeeded", { timeout: 8_000 });
159
157
  await expect(page.locator("#piComponentUpdateStatus")).toContainText("New or reloaded Pi sessions use the update");
160
158
  await expect(page.locator("#piComponentUpdateStatus")).toContainText("already-running tabs keep their current runtime");
161
159
  assert.ok(statusPollsAfterStart >= 1, "the browser should poll while the accepted job is running");
@@ -713,9 +713,9 @@ test("individually expanded tool details stay open through transcript rerenders"
713
713
  await triggerTranscriptContinuity(page, "tool");
714
714
  const details = page.locator(".message.toolExecution .tool-raw-details").last();
715
715
  await expect(details).toBeAttached();
716
- await expect.poll(() => details.evaluate((node) => node.open)).toBe(false);
716
+ await expect(details).toContainText("unselected revision one");
717
717
  const summary = details.locator("summary");
718
- await summary.click();
718
+ await details.evaluate((node) => { node.open = true; });
719
719
  await expect.poll(() => details.evaluate((node) => node.open)).toBe(true);
720
720
  await waitForFixtureSettlement(page);
721
721
  const rawOutput = details.locator(".tool-raw-code");