@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.
- package/README.md +18 -584
- package/bin/pi-webui-launcher.mjs +22 -0
- package/bin/pi-webui-update-supervisor.mjs +86 -0
- package/bin/pi-webui.mjs +933 -554
- package/index.ts +16 -6
- package/lib/component-update-state.mjs +21 -0
- package/lib/git-workflow-preferences.mjs +20 -2
- package/lib/optional-feature-catalog.mjs +1 -0
- package/lib/sampling-parameter-capabilities.mjs +160 -0
- package/lib/session-summary-core.mjs +4 -3
- package/lib/session-summary-preferences.mjs +16 -1
- package/lib/subagent-launch-slots.mjs +14 -2
- package/lib/trust-boundaries.mjs +16 -0
- package/lib/update/executor.mjs +99 -0
- package/lib/update/journal.mjs +175 -0
- package/lib/update/owners.mjs +70 -0
- package/lib/update/plan.mjs +134 -0
- package/lib/update/resolver.mjs +168 -0
- package/lib/update/supervisor.mjs +238 -0
- package/lib/update/verify.mjs +52 -0
- package/lib/update-commands.mjs +25 -13
- package/lib/webui-workspaces.mjs +17 -1
- package/lib/workspace-session-summaries.mjs +400 -0
- package/package.json +4 -4
- package/public/app.js +2487 -349
- package/public/index.html +200 -51
- package/public/middle-button-drag-scroll.mjs +154 -0
- package/public/sampling-parameter-controls.mjs +361 -0
- package/public/service-worker.js +5 -1
- package/public/stream-output-controller.mjs +327 -0
- package/public/styles.css +666 -71
- package/public/theme-contract.mjs +244 -0
- package/session-summary.ts +164 -4
- package/tests/aur-review-widget-static.test.mjs +2 -1
- package/tests/boot-failure-diagnostics.test.mjs +3 -3
- package/tests/browser/control-deck-component-updates.spec.mjs +20 -22
- package/tests/browser/interaction-continuity.spec.mjs +2 -2
- package/tests/browser/middle-button-drag-scroll.spec.mjs +145 -0
- package/tests/browser/persistent-ui-layout.spec.mjs +68 -23
- package/tests/browser/sampling-tooltip.spec.mjs +228 -0
- package/tests/browser/session-summary.spec.mjs +131 -3
- package/tests/browser/stream-output-isolation.spec.mjs +510 -0
- package/tests/browser/update-reconnect.spec.mjs +92 -0
- package/tests/codex-fast-mode-static.test.mjs +2 -2
- package/tests/common-options-submenus-interaction-static.test.mjs +172 -0
- package/tests/common-options-submenus-markup-static.test.mjs +152 -0
- package/tests/component-update-api-static.test.mjs +22 -61
- package/tests/composer-action-grid-reorder-static.test.mjs +3 -3
- package/tests/control-deck-component-updates-static.test.mjs +13 -237
- package/tests/durable-rpc-supervisor-harness.test.mjs +3 -1
- package/tests/fast-mode-client-static.test.mjs +3 -2
- package/tests/feature-decision-output-popup-static.test.mjs +2 -2
- package/tests/feature-system-prompt-optional-feature-static.test.mjs +49 -0
- package/tests/fixtures/fake-pi.mjs +269 -2
- package/tests/fixtures/update/tree-timeout-descendant.mjs +6 -0
- package/tests/fixtures/update/tree-timeout-parent.mjs +11 -0
- package/tests/git-footer-context-menu-static.test.mjs +58 -0
- package/tests/git-workflow-preferences.test.mjs +7 -1
- package/tests/guided-git-aur-review.test.mjs +4 -3
- package/tests/http-endpoints-harness.test.mjs +274 -23
- package/tests/middle-button-drag-scroll-static.test.mjs +24 -0
- package/tests/middle-button-drag-scroll.test.mjs +170 -0
- package/tests/mobile-continuity-tablet-static.test.mjs +3 -3
- package/tests/mobile-foundation-static.test.mjs +5 -6
- package/tests/mobile-phone-experience-static.test.mjs +1 -1
- package/tests/mobile-static.test.mjs +85 -50
- package/tests/native-parity.test.mjs +1 -1
- package/tests/open-issue-wizard-static.test.mjs +2 -3
- package/tests/optional-feature-migration-frontend.test.mjs +9 -5
- package/tests/persistent-ui-layout-static.test.mjs +13 -2
- package/tests/questionnaire-dialog.test.mjs +3 -3
- package/tests/remote-auth-settings-harness.test.mjs +43 -0
- package/tests/rpc-supervisor-host.test.mjs +11 -2
- package/tests/safety-guard-auto-review-harness.test.mjs +117 -0
- package/tests/safety-guard-auto-review-static.test.mjs +34 -0
- package/tests/sampling-native-controls-user-flow.test.mjs +752 -0
- package/tests/sampling-parameter-capabilities.test.mjs +167 -0
- package/tests/sampling-parameter-controls.test.mjs +241 -0
- package/tests/session-sampling-helper.test.mjs +228 -0
- package/tests/session-sampling-http.test.mjs +168 -0
- package/tests/session-sampling-ui-static.test.mjs +370 -0
- package/tests/session-summary-core.test.mjs +205 -10
- package/tests/side-panel-section-height-removal-static.test.mjs +34 -0
- package/tests/side-panel-section-reorder-static.test.mjs +3 -3
- package/tests/staged-content-hash-contract.test.mjs +52 -11
- package/tests/stream-lifecycle-core.test.mjs +134 -0
- package/tests/stream-output-controller.test.mjs +252 -0
- package/tests/stream-output-isolation-static.test.mjs +89 -0
- package/tests/streaming-ui-coupling.test.mjs +50 -0
- package/tests/subagent-gate-visibility.test.mjs +1 -1
- package/tests/subagent-launch-slots-static.test.mjs +1 -1
- package/tests/subagent-launch-slots.test.mjs +18 -1
- package/tests/theme-contract.test.mjs +104 -0
- package/tests/theme-customizer-static.test.mjs +82 -0
- package/tests/theme-scheme-mode.test.mjs +15 -0
- package/tests/ui-layout-settings.test.mjs +18 -1
- package/tests/update-api-harness.test.mjs +111 -0
- package/tests/update-commands.test.mjs +15 -45
- package/tests/update-executor-process-tree-harness.test.mjs +22 -0
- package/tests/update-journal-harness.test.mjs +59 -0
- package/tests/update-lock-multiprocess-harness.test.mjs +46 -0
- package/tests/update-owners.test.mjs +27 -0
- package/tests/update-plan.test.mjs +58 -0
- package/tests/update-resolver.test.mjs +56 -0
- package/tests/update-supervisor-harness.test.mjs +57 -0
- package/tests/update-tab-restore-harness.test.mjs +24 -0
- package/tests/update-verify.test.mjs +31 -0
- package/tests/workspace-files-live-updates-static.test.mjs +13 -4
- package/tests/workspace-session-summaries.test.mjs +288 -0
- package/webui-rpc-helper.mjs +119 -0
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import {
|
|
3
|
+
DEFAULT_STREAM_PENDING_BYTE_LIMIT,
|
|
4
|
+
DEFAULT_STREAM_PENDING_ENTRY_LIMIT,
|
|
5
|
+
TRANSCRIPT_STREAM_MESSAGE_UPDATE_TYPES,
|
|
6
|
+
classifyTranscriptStreamEvent,
|
|
7
|
+
createStreamOutputController,
|
|
8
|
+
} from "../public/stream-output-controller.mjs";
|
|
9
|
+
|
|
10
|
+
function messageUpdate(type, delta = "", extra = {}) {
|
|
11
|
+
return { type: "message_update", assistantMessageEvent: { type, delta, ...extra } };
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
class FakeFrames {
|
|
15
|
+
next = 1;
|
|
16
|
+
callbacks = new Map();
|
|
17
|
+
cancelled = [];
|
|
18
|
+
|
|
19
|
+
schedule = (callback) => {
|
|
20
|
+
const handle = this.next++;
|
|
21
|
+
this.callbacks.set(handle, callback);
|
|
22
|
+
return handle;
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
cancel = (handle) => {
|
|
26
|
+
this.cancelled.push(handle);
|
|
27
|
+
this.callbacks.delete(handle);
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
run(handle = this.callbacks.keys().next().value) {
|
|
31
|
+
const callback = this.callbacks.get(handle);
|
|
32
|
+
assert.equal(typeof callback, "function", `frame ${handle} should be pending`);
|
|
33
|
+
this.callbacks.delete(handle);
|
|
34
|
+
callback();
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
assert.deepEqual(TRANSCRIPT_STREAM_MESSAGE_UPDATE_TYPES, [
|
|
39
|
+
"thinking_start", "thinking_delta", "thinking_end",
|
|
40
|
+
"text_start", "text_delta", "text_end",
|
|
41
|
+
"toolcall_start", "toolcall_delta", "toolcall_end",
|
|
42
|
+
"error",
|
|
43
|
+
]);
|
|
44
|
+
assert.deepEqual(classifyTranscriptStreamEvent(messageUpdate("text_delta")), {
|
|
45
|
+
kind: "text", subtype: "text_delta", recognized: true, barrier: false,
|
|
46
|
+
});
|
|
47
|
+
assert.equal(classifyTranscriptStreamEvent(messageUpdate("thinking_end")).barrier, true);
|
|
48
|
+
assert.equal(classifyTranscriptStreamEvent(messageUpdate("toolcall_end")).kind, "tool-call");
|
|
49
|
+
assert.equal(classifyTranscriptStreamEvent({ type: "tool_execution_update" }).kind, "tool-execution");
|
|
50
|
+
assert.deepEqual(classifyTranscriptStreamEvent(messageUpdate("future_delta")), {
|
|
51
|
+
kind: "unknown-message-update", subtype: "future_delta", recognized: false, barrier: false,
|
|
52
|
+
});
|
|
53
|
+
assert.equal(classifyTranscriptStreamEvent({ type: "agent_start" }), null);
|
|
54
|
+
assert.equal(DEFAULT_STREAM_PENDING_ENTRY_LIMIT, 128);
|
|
55
|
+
assert.equal(DEFAULT_STREAM_PENDING_BYTE_LIMIT, 256 * 1024);
|
|
56
|
+
|
|
57
|
+
// Adjacent compatible deltas coalesce, while kind changes retain exact order.
|
|
58
|
+
{
|
|
59
|
+
const frames = new FakeFrames();
|
|
60
|
+
const calls = [];
|
|
61
|
+
const controller = createStreamOutputController({
|
|
62
|
+
scheduleFrame: frames.schedule,
|
|
63
|
+
cancelFrame: frames.cancel,
|
|
64
|
+
applyTextUpdate: (event) => calls.push(`text:${event.assistantMessageEvent.delta}`),
|
|
65
|
+
applyThinkingUpdate: (event) => calls.push(`thinking:${event.assistantMessageEvent.delta}`),
|
|
66
|
+
applyToolCallUpdate: (event) => calls.push(`tool-call:${event.assistantMessageEvent.delta}`),
|
|
67
|
+
applyToolExecutionUpdate: (event) => calls.push(`tool-execution:${event.partialResult?.content || ""}`),
|
|
68
|
+
applyFollowScroll: () => calls.push("follow"),
|
|
69
|
+
});
|
|
70
|
+
controller.dispatch(messageUpdate("text_delta", "A"));
|
|
71
|
+
controller.dispatch(messageUpdate("text_delta", "B"));
|
|
72
|
+
controller.dispatch(messageUpdate("thinking_delta", "C"));
|
|
73
|
+
controller.dispatch(messageUpdate("thinking_delta", "D"));
|
|
74
|
+
controller.dispatch(messageUpdate("toolcall_delta", "E", { contentIndex: 2, toolCall: { id: "tool-1" } }));
|
|
75
|
+
controller.dispatch(messageUpdate("toolcall_delta", "F", { contentIndex: 2, toolCall: { id: "tool-1" } }));
|
|
76
|
+
controller.dispatch({ type: "tool_execution_update", toolCallId: "tool-1", partialResult: { content: "partial" } });
|
|
77
|
+
controller.dispatch({ type: "tool_execution_update", toolCallId: "tool-1", partialResult: { content: "complete" } });
|
|
78
|
+
assert.equal(frames.callbacks.size, 1, "all raw updates should share one frame");
|
|
79
|
+
assert.equal(controller.pendingCount(), 4, "four adjacent semantic groups should remain");
|
|
80
|
+
frames.run();
|
|
81
|
+
assert.deepEqual(calls, ["text:AB", "thinking:CD", "tool-call:EF", "tool-execution:complete", "follow"]);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// A realistic 1,000-delta burst is lossless and bounded to one sink call.
|
|
85
|
+
{
|
|
86
|
+
const frames = new FakeFrames();
|
|
87
|
+
const chunks = Array.from({ length: 1_000 }, (_, index) => `[${index}]`);
|
|
88
|
+
const applied = [];
|
|
89
|
+
const controller = createStreamOutputController({
|
|
90
|
+
scheduleFrame: frames.schedule,
|
|
91
|
+
cancelFrame: frames.cancel,
|
|
92
|
+
applyTextUpdate: (event) => applied.push(event.assistantMessageEvent.delta),
|
|
93
|
+
});
|
|
94
|
+
for (let index = 0; index < chunks.length; index += 1) {
|
|
95
|
+
controller.dispatch({ ...messageUpdate("text_delta", chunks[index]), isolationDeltaIndex: index });
|
|
96
|
+
}
|
|
97
|
+
assert.equal(controller.pendingCount(), 1, "adjacent non-empty text deltas should coalesce to one pending entry");
|
|
98
|
+
assert.ok(controller.pendingBytes() <= controller.limits().maxPendingBytes);
|
|
99
|
+
frames.run();
|
|
100
|
+
assert.deepEqual(applied, [chunks.join("")], "coalescing must preserve exact output bytes and order");
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// Alternating kinds cannot coalesce, so count overflow drains synchronously
|
|
104
|
+
// instead of dropping or retaining an unbounded queue.
|
|
105
|
+
{
|
|
106
|
+
const frames = new FakeFrames();
|
|
107
|
+
const calls = [];
|
|
108
|
+
const overflows = [];
|
|
109
|
+
const controller = createStreamOutputController({
|
|
110
|
+
scheduleFrame: frames.schedule,
|
|
111
|
+
cancelFrame: frames.cancel,
|
|
112
|
+
maxPendingEntries: 4,
|
|
113
|
+
maxPendingBytes: 10_000,
|
|
114
|
+
applyTextUpdate: (event) => calls.push(`t${event.assistantMessageEvent.delta}`),
|
|
115
|
+
applyThinkingUpdate: (event) => calls.push(`h${event.assistantMessageEvent.delta}`),
|
|
116
|
+
onOverflow: (overflow) => overflows.push(overflow.reason),
|
|
117
|
+
});
|
|
118
|
+
const expected = [];
|
|
119
|
+
for (let index = 0; index < 21; index += 1) {
|
|
120
|
+
const text = index % 2 === 0;
|
|
121
|
+
expected.push(`${text ? "t" : "h"}${index}`);
|
|
122
|
+
controller.dispatch(messageUpdate(text ? "text_delta" : "thinking_delta", String(index)));
|
|
123
|
+
assert.ok(controller.pendingCount() <= 4, "pending count must never exceed its configured bound");
|
|
124
|
+
assert.ok(controller.pendingBytes() <= 10_000, "pending bytes must never exceed their configured bound");
|
|
125
|
+
}
|
|
126
|
+
controller.barrier("test-overflow-tail");
|
|
127
|
+
assert.deepEqual(calls, expected);
|
|
128
|
+
assert.ok(overflows.includes("entry-limit"));
|
|
129
|
+
assert.equal(frames.callbacks.size, 0);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// A single oversize event is applied directly after the prior batch. It is not
|
|
133
|
+
// retained beyond the byte bound and no content is lost.
|
|
134
|
+
{
|
|
135
|
+
const calls = [];
|
|
136
|
+
const overflows = [];
|
|
137
|
+
const controller = createStreamOutputController({
|
|
138
|
+
maxPendingBytes: 80,
|
|
139
|
+
applyTextUpdate: (event) => calls.push(event.assistantMessageEvent.delta),
|
|
140
|
+
onOverflow: (overflow) => overflows.push(overflow.reason),
|
|
141
|
+
});
|
|
142
|
+
controller.dispatch(messageUpdate("text_delta", "x".repeat(200)));
|
|
143
|
+
assert.equal(controller.pendingCount(), 0);
|
|
144
|
+
assert.equal(controller.pendingBytes(), 0);
|
|
145
|
+
assert.deepEqual(calls, ["x".repeat(200)]);
|
|
146
|
+
assert.ok(overflows.includes("oversize-event"));
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// Raw and semantic barriers preserve text/thinking/tool/error chronology and
|
|
150
|
+
// cancel the retained frame before the transition can mutate chrome.
|
|
151
|
+
{
|
|
152
|
+
const frames = new FakeFrames();
|
|
153
|
+
const calls = [];
|
|
154
|
+
const controller = createStreamOutputController({
|
|
155
|
+
scheduleFrame: frames.schedule,
|
|
156
|
+
cancelFrame: frames.cancel,
|
|
157
|
+
applyTextUpdate: (event) => calls.push(`text:${event.assistantMessageEvent.delta}`),
|
|
158
|
+
applyThinkingUpdate: (event) => calls.push(`thinking:${event.assistantMessageEvent.delta}`),
|
|
159
|
+
applyToolExecutionUpdate: (event) => calls.push(`tool:${event.partialResult.content}`),
|
|
160
|
+
applyStreamError: () => calls.push("error"),
|
|
161
|
+
applyFollowScroll: () => calls.push("follow"),
|
|
162
|
+
});
|
|
163
|
+
controller.dispatch(messageUpdate("text_delta", "tail"));
|
|
164
|
+
controller.dispatch(messageUpdate("thinking_delta", "thought"));
|
|
165
|
+
controller.dispatch({ type: "tool_execution_update", toolCallId: "t", partialResult: { content: "tool tail" } });
|
|
166
|
+
const queuedHandle = frames.callbacks.keys().next().value;
|
|
167
|
+
assert.equal(controller.barrier("auto_retry_start"), 3);
|
|
168
|
+
assert.deepEqual(calls, ["text:tail", "thinking:thought", "tool:tool tail", "follow"]);
|
|
169
|
+
assert.ok(frames.cancelled.includes(queuedHandle));
|
|
170
|
+
controller.dispatch(messageUpdate("thinking_delta", "before-end"));
|
|
171
|
+
controller.dispatch(messageUpdate("thinking_end"));
|
|
172
|
+
assert.deepEqual(calls.slice(-3), ["thinking:before-end", "thinking:", "follow"]);
|
|
173
|
+
controller.dispatch(messageUpdate("error"));
|
|
174
|
+
assert.deepEqual(calls.slice(-2), ["error", "follow"], "stream errors must never be dropped by batching");
|
|
175
|
+
controller.dispatch(messageUpdate("text_delta", "abort-tail"));
|
|
176
|
+
const abortHandle = frames.callbacks.keys().next().value;
|
|
177
|
+
assert.equal(controller.barrier("user-abort"), 1);
|
|
178
|
+
assert.deepEqual(calls.slice(-2), ["text:abort-tail", "follow"], "user abort must synchronously preserve a pending text tail");
|
|
179
|
+
assert.ok(frames.cancelled.includes(abortHandle));
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
// Hidden-frame delay preserves the tail; a stale owner is rejected both at
|
|
183
|
+
// dispatch and if ownership changes before the delayed frame runs.
|
|
184
|
+
{
|
|
185
|
+
const frames = new FakeFrames();
|
|
186
|
+
const calls = [];
|
|
187
|
+
let currentOwner = "tab-a:1";
|
|
188
|
+
const controller = createStreamOutputController({
|
|
189
|
+
scheduleFrame: frames.schedule,
|
|
190
|
+
cancelFrame: frames.cancel,
|
|
191
|
+
isOwnerCurrent: (owner) => owner === currentOwner,
|
|
192
|
+
applyTextUpdate: (event) => calls.push(event.assistantMessageEvent.delta),
|
|
193
|
+
onStaleOwner: (_event, owner) => calls.push(`stale:${owner}`),
|
|
194
|
+
});
|
|
195
|
+
controller.dispatch(messageUpdate("text_delta", "hidden-tail"), { owner: currentOwner });
|
|
196
|
+
assert.deepEqual(calls, [], "a throttled/hidden frame may remain pending without losing output");
|
|
197
|
+
controller.barrier("visibility-barrier");
|
|
198
|
+
assert.deepEqual(calls, ["hidden-tail"]);
|
|
199
|
+
controller.dispatch(messageUpdate("text_delta", "stale-later"), { owner: currentOwner });
|
|
200
|
+
currentOwner = "tab-a:2";
|
|
201
|
+
frames.run();
|
|
202
|
+
assert.deepEqual(calls, ["hidden-tail", "stale:tab-a:1"]);
|
|
203
|
+
assert.equal(controller.dispatch(messageUpdate("text_delta", "stale-now"), { owner: "tab-b:1" }), true);
|
|
204
|
+
assert.deepEqual(calls, ["hidden-tail", "stale:tab-a:1", "stale:tab-b:1"]);
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
// Unknown transcript-shaped events remain isolated but reach the fallback with
|
|
208
|
+
// bounded diagnostic metadata; indexed coalesced input reports receipt/apply.
|
|
209
|
+
{
|
|
210
|
+
const frames = new FakeFrames();
|
|
211
|
+
const unknown = [];
|
|
212
|
+
const diagnostics = [];
|
|
213
|
+
const controller = createStreamOutputController({
|
|
214
|
+
scheduleFrame: frames.schedule,
|
|
215
|
+
cancelFrame: frames.cancel,
|
|
216
|
+
applyTextUpdate: () => {},
|
|
217
|
+
onUnknownStreamEvent: (event, classification, owner) => unknown.push({ event, classification, owner }),
|
|
218
|
+
onDiagnostic: (record) => diagnostics.push(record),
|
|
219
|
+
});
|
|
220
|
+
controller.dispatch({ ...messageUpdate("text_delta", "A"), isolationDeltaIndex: 0 }, { owner: "tab:1" });
|
|
221
|
+
controller.dispatch({ ...messageUpdate("text_delta", "B"), isolationDeltaIndex: 1 }, { owner: "tab:1" });
|
|
222
|
+
controller.dispatch(messageUpdate("future_delta", "preserve me"), { owner: "tab:1" });
|
|
223
|
+
frames.run();
|
|
224
|
+
assert.equal(unknown.length, 1);
|
|
225
|
+
assert.equal(unknown[0].event.assistantMessageEvent.delta, "preserve me");
|
|
226
|
+
assert.equal(unknown[0].classification.subtype, "future_delta");
|
|
227
|
+
const receipts = diagnostics.filter((record) => record.type === "receipt");
|
|
228
|
+
assert.deepEqual(receipts.slice(0, 2).map((record) => record.index), [0, 1]);
|
|
229
|
+
const textApply = diagnostics.find((record) => record.type === "apply" && record.kind === "text");
|
|
230
|
+
assert.equal(textApply.sourceCount, 2);
|
|
231
|
+
assert.deepEqual(textApply.sourceIndexes, [0, 1]);
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
for (const mode of ["normal", "compact-v1"]) {
|
|
235
|
+
const frames = new FakeFrames();
|
|
236
|
+
const seen = [];
|
|
237
|
+
const controller = createStreamOutputController({
|
|
238
|
+
scheduleFrame: frames.schedule,
|
|
239
|
+
cancelFrame: frames.cancel,
|
|
240
|
+
applyTextUpdate: (event) => seen.push(`${mode}:${event.assistantMessageEvent.delta}`),
|
|
241
|
+
applyFollowScroll: () => seen.push(`${mode}:follow`),
|
|
242
|
+
});
|
|
243
|
+
controller.dispatch(messageUpdate("text_delta", "same"));
|
|
244
|
+
controller.dispatch(messageUpdate("text_delta", " output"));
|
|
245
|
+
frames.run();
|
|
246
|
+
assert.deepEqual(seen, [`${mode}:same output`, `${mode}:follow`], `${mode} should use the same coalescing and ordering contract`);
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
assert.throws(() => createStreamOutputController({ maxPendingEntries: 0 }), /positive safe integer/);
|
|
250
|
+
assert.throws(() => createStreamOutputController({ maxPendingBytes: -1 }), /positive safe integer/);
|
|
251
|
+
|
|
252
|
+
console.log("stream-output-controller.test.mjs passed");
|
|
@@ -0,0 +1,89 @@
|
|
|
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 controller = await readFile(join(root, "public", "stream-output-controller.mjs"), "utf8");
|
|
9
|
+
|
|
10
|
+
function functionBody(source, name) {
|
|
11
|
+
const match = new RegExp(`function\\s+${name}\\s*\\(`).exec(source);
|
|
12
|
+
assert.ok(match, `${name} should be defined`);
|
|
13
|
+
let parens = 0;
|
|
14
|
+
let open = -1;
|
|
15
|
+
for (let index = match.index + match[0].length - 1; index < source.length; index += 1) {
|
|
16
|
+
if (source[index] === "(") parens += 1;
|
|
17
|
+
else if (source[index] === ")") parens -= 1;
|
|
18
|
+
else if (source[index] === "{" && parens === 0) {
|
|
19
|
+
open = index;
|
|
20
|
+
break;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
assert.notEqual(open, -1, `${name} should open`);
|
|
24
|
+
let depth = 0;
|
|
25
|
+
for (let index = open; index < source.length; index += 1) {
|
|
26
|
+
if (source[index] === "{") depth += 1;
|
|
27
|
+
else if (source[index] === "}" && --depth === 0) return source.slice(open + 1, index);
|
|
28
|
+
}
|
|
29
|
+
assert.fail(`${name} should close`);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const forbiddenSinks = [
|
|
33
|
+
"renderWidgets", "renderFooter", "renderTabs", "renderStatus",
|
|
34
|
+
"renderWorkspaceDashboard", "renderContextMeter", "renderFeedbackTray",
|
|
35
|
+
"scheduleRefreshState", "scheduleRefreshFooter", "requestGitFooterWebuiPayload",
|
|
36
|
+
"trackSkillsFromEvent", "addEvent", "scheduleComposerModeButtons",
|
|
37
|
+
".focus(", "scrollIntoView", "fetch(", "api(",
|
|
38
|
+
];
|
|
39
|
+
|
|
40
|
+
assert.match(app, /import \{ createStreamOutputController \} from "\.\/stream-output-controller\.mjs";/);
|
|
41
|
+
assert.match(controller, /export function classifyTranscriptStreamEvent/);
|
|
42
|
+
assert.match(controller, /export function createStreamOutputController/);
|
|
43
|
+
assert.match(controller, /let frameHandle = null;[\s\S]*?let pending = \[\];[\s\S]*?let pendingBytes = 0;/, "controller should retain one cancellable bounded queue");
|
|
44
|
+
assert.match(controller, /if \(classification\.barrier\) \{[\s\S]*?flush\(\);/, "recognized raw end/error barriers should flush synchronously");
|
|
45
|
+
assert.match(controller, /COALESCIBLE_DELTA_TYPES[\s\S]*?function mergedAdjacentEntry[\s\S]*?previousKey !== entryCoalesceKey\(incoming\)/, "adjacent compatible stream deltas should coalesce before rendering");
|
|
46
|
+
assert.match(controller, /pending\.length >= entryLimit|pendingBytes \+ entry\.bytes > byteLimit/, "pending count and bytes should have explicit bounds");
|
|
47
|
+
assert.match(controller, /reason: "oversize-event"[\s\S]*?applyOversize\(entry\)/, "single oversize events should be applied directly rather than dropped");
|
|
48
|
+
assert.match(controller, /if \(!ownerIsCurrent\(owner\)\)[\s\S]*?reportStale/, "stale owners should fail closed");
|
|
49
|
+
|
|
50
|
+
for (const sink of forbiddenSinks) {
|
|
51
|
+
assert.equal(controller.includes(sink), false, `dependency-free controller must not reference forbidden sink ${sink}`);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const dispatch = functionBody(app, "dispatchTranscriptStreamEvent");
|
|
55
|
+
const rawMessageHandler = functionBody(app, "handleMessageUpdate");
|
|
56
|
+
const handleEvent = functionBody(app, "handleEvent");
|
|
57
|
+
const toolUpdate = functionBody(app, "applyTranscriptToolExecutionUpdate");
|
|
58
|
+
const dispatchIndex = handleEvent.indexOf("dispatchTranscriptStreamEvent(event)");
|
|
59
|
+
const tabActivityIndex = handleEvent.indexOf("ingestEventTabActivity(event)");
|
|
60
|
+
const skillTrackingIndex = handleEvent.indexOf("trackSkillsFromEvent(event)");
|
|
61
|
+
assert.ok(dispatchIndex >= 0 && dispatchIndex < tabActivityIndex && dispatchIndex < skillTrackingIndex, "raw dispatch must run before global tab/activity/skill processing");
|
|
62
|
+
assert.match(handleEvent, /if \(dispatchTranscriptStreamEvent\(event\)\) return;/, "consumed raw events must bypass the lifecycle switch");
|
|
63
|
+
assert.match(dispatch, /streamOutputController\.dispatch\(event,[\s\S]*?owner: transcriptStreamOwner/, "dispatch should bind updates to the current tab generation owner");
|
|
64
|
+
|
|
65
|
+
for (const sink of forbiddenSinks) {
|
|
66
|
+
assert.equal(dispatch.includes(sink), false, `raw dispatch seam must not reach forbidden sink ${sink}`);
|
|
67
|
+
assert.equal(rawMessageHandler.includes(sink), false, `message-update transcript sink must not reach forbidden sink ${sink}`);
|
|
68
|
+
}
|
|
69
|
+
assert.doesNotMatch(rawMessageHandler, /setRunIndicatorActivity|scheduleLiveTodoProgressWidgetSync|scheduleStreamingAssistantTextRender|scheduleChatFollowScroll/, "raw message deltas must bypass composer activity, widgets, and parallel schedulers");
|
|
70
|
+
assert.match(rawMessageHandler, /compactOutputActive\(\) && handleCompactMessageUpdate\(event\)/, "normal and compact modes should share the isolated controller sink");
|
|
71
|
+
assert.match(toolUpdate, /renderLiveToolRun\(run, \{ scroll: false \}\)/, "isolated tool updates should render in the controller frame rather than queue another tool frame");
|
|
72
|
+
assert.doesNotMatch(toolUpdate, /scheduleLiveToolRunRender/, "isolated tool updates must not create a parallel render queue");
|
|
73
|
+
assert.match(app, /applyToolExecutionUpdate: \(event\) => \{\s+if \(!compactOutputActive\(\)\) applyTranscriptToolExecutionUpdate\(event\);/, "raw tool execution updates should use only the transcript sink");
|
|
74
|
+
assert.doesNotMatch(app.slice(app.indexOf("const streamOutputController"), app.indexOf("let assistantErrorSurfacedThisRun")), /renderWidgets|renderFooter|renderTabs|renderStatus|renderFeedbackTray|setRunIndicatorActivity|scheduleLiveTodoProgressWidgetSync|addEvent|fetch\(|api\(/, "controller integration must inject transcript-only sinks");
|
|
75
|
+
const connectEvents = functionBody(app, "connectEvents");
|
|
76
|
+
assert.match(connectEvents, /streamOutputController\.cancel\(\);[\s\S]*?resetCompactLiveOutput\(\);/, "reconnect and tab switches should cancel retained raw frames before resetting live output");
|
|
77
|
+
assert.match(connectEvents, /source\.onerror = \(\) => \{[\s\S]*?streamOutputController\.flush\(\);[\s\S]*?streamOutputController\.cancel\(\);/, "an actual EventSource disconnect must flush and cancel retained transcript work before browser retry");
|
|
78
|
+
const barrier = functionBody(app, "flushTranscriptStreamBarrier");
|
|
79
|
+
const abort = functionBody(app, "abortActiveRun");
|
|
80
|
+
assert.match(barrier, /streamOutputController\.barrier\(event\.type\)/, "semantic lifecycle boundaries should flush raw output first");
|
|
81
|
+
assert.match(app, /"auto_retry_start",\s+"auto_retry_end",/, "retry start/end should be explicit stream barriers");
|
|
82
|
+
assert.ok(abort.indexOf('streamOutputController.barrier("user-abort")') < abort.indexOf("abortRequestInFlight = true"), "accepted user abort must flush transcript output before chrome/RPC transitions");
|
|
83
|
+
assert.doesNotMatch(handleEvent, /case "message_update"|case "tool_execution_update"/, "raw event switch cases consumed by the controller must be removed");
|
|
84
|
+
assert.doesNotMatch(app, /function scheduleStreamingAssistantTextRender|function handleToolExecutionUpdate|scheduleLiveToolRunRender/, "superseded raw render schedulers must be removed");
|
|
85
|
+
assert.match(app, /onUnknownStreamEvent: preserveUnknownTranscriptEvidence/, "unknown transcript-shaped events should retain transcript-only evidence");
|
|
86
|
+
assert.match(app, /reconcileUnknownTranscriptEvidenceAtBarrier\(event\)/, "unknown evidence should request authoritative reconciliation only at a semantic barrier");
|
|
87
|
+
assert.match(app, /streamIsolationDebug[\s\S]*?__piStreamIsolationDebug/, "the opt-in test diagnostic ledger should be exposed only behind the explicit debug flag");
|
|
88
|
+
|
|
89
|
+
console.log("stream-output-isolation-static.test.mjs passed");
|
|
@@ -201,6 +201,56 @@ assert.match(requestGitFooterWebuiPayload, /currentState\?\.isStreaming \|\| cur
|
|
|
201
201
|
assert.match(findCaseBody(handleEvent, "agent_settled"), /currentState\) currentState = \{ \.\.\.currentState, isStreaming: false \};[\s\S]*?requestGitFooterWebuiPayload\(tabContext, \{ force: true \}\)/, "theory #8: forced git-footer refresh should only happen after agent settlement clears streaming state");
|
|
202
202
|
assert.doesNotMatch(findCaseBody(handleEvent, "agent_end"), /isStreaming: false|requestGitFooterWebuiPayload/, "theory #8: low-level agent_end must not expose an idle window before retry or continuation");
|
|
203
203
|
|
|
204
|
+
// --- WS2a: lifecycle / chrome / todo ownership separation ---
|
|
205
|
+
// These are hard invariants, not future theories: raw stream output may not own
|
|
206
|
+
// lifecycle chrome, and lifecycle chrome may not be driven by token cadence.
|
|
207
|
+
|
|
208
|
+
const renderMessages = findFunctionBody(app, "renderMessages");
|
|
209
|
+
const refreshMessages = findFunctionBody(app, "refreshMessages");
|
|
210
|
+
const setRunIndicatorActivityBody = findFunctionBody(app, "setRunIndicatorActivity");
|
|
211
|
+
const startRunIndicatorTicker = findFunctionBody(app, "startRunIndicatorTicker");
|
|
212
|
+
const startLifecycleStateWatchdog = findFunctionBody(app, "startLifecycleStateWatchdog");
|
|
213
|
+
const reconcileTodoProgressFromMessages = findFunctionBody(app, "reconcileTodoProgressFromMessages");
|
|
214
|
+
const eventMayAffectSkillUsage = findFunctionBody(app, "eventMayAffectSkillUsage");
|
|
215
|
+
const flushSemanticReconcile = findFunctionBody(app, "flushSemanticReconcile");
|
|
216
|
+
|
|
217
|
+
// (1) Transcript rendering is transcript-only; chrome belongs to the reconciler.
|
|
218
|
+
assert.doesNotMatch(renderMessages, /renderFooter\(\)|renderFeedbackTray\(\)|renderWidgets\(\)|renderStatus\(\)/, "WS2a: renderMessages must be transcript-only and must not render footer/feedback/widget/status chrome");
|
|
219
|
+
assert.match(renderMessages, /renderAllMessages\(\)/, "WS2a: renderMessages must still own transcript rendering");
|
|
220
|
+
|
|
221
|
+
// (2) Todo progress derives from authoritative content, never token cadence.
|
|
222
|
+
assert.doesNotMatch(app, /function scheduleLiveTodoProgressWidgetSync/, "WS2a: the token-driven todo-progress scheduler must be removed");
|
|
223
|
+
assert.doesNotMatch(app, /scheduleLiveTodoProgressWidgetSync\(/, "WS2a: nothing may schedule token-driven todo-progress syncs");
|
|
224
|
+
assert.match(reconcileTodoProgressFromMessages, /authoritativeTodoProgressSourceText\([\s\S]*?syncLiveTodoProgressWidgetFromText\(/, "WS2a: todo progress must be derived from authoritative assistant content");
|
|
225
|
+
assert.match(refreshMessages, /reconcileTodoProgressFromMessages\(latestMessages, tabContext\.tabId\)/, "WS2a: todo progress must be derived once at authoritative message reconciliation");
|
|
226
|
+
assert.match(findFunctionBody(app, "syncLiveTodoProgressWidgetFromText"), /todoProgressSignatureByTab\.get\(tabId\) === signature\) return false/, "WS2a: the todo widget record may change only when its semantic value changes");
|
|
227
|
+
|
|
228
|
+
// (3) Activity wording is transcript-owned; composer/Stop changes on transitions.
|
|
229
|
+
assert.doesNotMatch(setRunIndicatorActivityBody, /^\s*scheduleComposerModeButtonsUpdate\(\);/m, "WS2a: activity wording must not unconditionally reconcile composer chrome");
|
|
230
|
+
assert.match(setRunIndicatorActivityBody, /syncLifecycleComposerState\(\)/, "WS2a: composer/Stop reconciliation must be gated on a lifecycle signature change");
|
|
231
|
+
assert.match(findFunctionBody(app, "syncLifecycleComposerState"), /signature === lifecycleComposerSignature\) return false/, "WS2a: an unchanged lifecycle signature must not schedule composer work");
|
|
232
|
+
assert.match(app, /runIndicatorBubble\.dataset\.streamOwned = "run-indicator"/, "WS2a: the live activity root must be a stable transcript-owned node");
|
|
233
|
+
|
|
234
|
+
// (4) The transcript ticker must not perform lifecycle/network reconciliation.
|
|
235
|
+
assert.doesNotMatch(startRunIndicatorTicker, /maybeRefreshRunIndicatorState\(\)/, "WS2a: the transcript-owned ticker must only repaint its own node");
|
|
236
|
+
assert.match(startLifecycleStateWatchdog, /maybeRefreshRunIndicatorState\(\)/, "WS2a: canonical state rechecks belong to the lifecycle watchdog");
|
|
237
|
+
|
|
238
|
+
// (5) Skills and event-log records happen once at semantic tool boundaries.
|
|
239
|
+
assert.doesNotMatch(eventMayAffectSkillUsage, /tool_execution_update|toolcall_start/, "WS2a: skill tracking must not be reachable from tool update/argument cadence");
|
|
240
|
+
assert.match(eventMayAffectSkillUsage, /"tool_execution_start", "tool_execution_end"/, "WS2a: skill tracking must run at semantic tool boundaries");
|
|
241
|
+
assert.match(trackSkillsFromEvent, /recordedToolBoundaryKeys\.has\(key\)[\s\S]*?trackSkillsFromToolInvocation[\s\S]*?if \(tracked && key\) rememberToolBoundaryRecordKey\(key\)/, "WS2a: usable tool skill records must be deduplicated without consuming a missing-args fallback");
|
|
242
|
+
assert.match(findCaseBody(handleEvent, "tool_execution_start"), /claimToolBoundaryRecord\(event, "log:start"\)\) addEvent\(/, "WS2a: tool start event-log records must be deduplicated by tool boundary");
|
|
243
|
+
assert.match(findCaseBody(handleEvent, "tool_execution_end"), /claimToolBoundaryRecord\(event, "log:end"\)\) addEvent\(/, "WS2a: tool end event-log records must be deduplicated by tool boundary");
|
|
244
|
+
|
|
245
|
+
// (6) Lifecycle boundaries reconcile chrome through one coalesced scheduler.
|
|
246
|
+
assert.match(findFunctionBody(app, "scheduleSemanticReconcile"), /mergeSemanticReconcileRequest\(semanticReconcilePending, dirty, tabContext\)[\s\S]*?semanticReconcileFrame !== null\) return;/, "WS2a: semantic reconciliation must coalesce partitioned requests to one pending flush");
|
|
247
|
+
assert.match(findFunctionBody(app, "mergeSemanticReconcileRequest"), /semanticReconcileContextKey\(tabContext\)[\s\S]*?pendingByContext\.set\(key, request\)/, "WS2a: semantic dirty flags must remain partitioned by tab generation");
|
|
248
|
+
assert.match(flushSemanticReconcile, /if \(dirty\.workflow\) reconcileGitWorkflowContinuation\(tabContext\.tabId\);[\s\S]*?if \(!isCurrentTabContext\(tabContext\)\) continue;/, "WS2a: originating workflow settlement must run before stale active-DOM work no-ops");
|
|
249
|
+
for (const [caseLabel, flag] of [["agent_start", "state: true"], ["agent_end", "messages: true"], ["message_end", "messages: true"], ["agent_settled", "messages: true"]]) {
|
|
250
|
+
assert.match(findCaseBody(handleEvent, caseLabel), new RegExp(`scheduleSemanticReconcile\\(\\{[\\s\\S]*?${flag}`), `WS2a: ${caseLabel} must reconcile chrome through the coalesced semantic scheduler`);
|
|
251
|
+
}
|
|
252
|
+
assert.match(findCaseBody(handleEvent, "agent_settled"), /usage: true,[\s\S]*?workflow: true,/, "WS2a: settlement must own the coalesced post-turn usage/workflow reconciliation");
|
|
253
|
+
|
|
204
254
|
if (futureFailures.length) {
|
|
205
255
|
assert.fail(`streaming/UI coupling invariants still failing (${futureFailures.length}):\n\n${futureFailures.map((failure, index) => `${index + 1}. ${failure}`).join("\n\n")}`);
|
|
206
256
|
}
|
|
@@ -76,7 +76,7 @@ assert.match(app, /function renderSubagentGate\(tab, gate\)[\s\S]*subagentGateIs
|
|
|
76
76
|
assert.match(app, /pruneDismissedSubagentGateKeys\(latestSubagents\?\.tabs, dismissedSubagentGateKeys\)/, "polling should prune stale dismissal keys");
|
|
77
77
|
assert.match(css, /\.subagent-gate-actions[\s\S]*\.subagent-gate-close[\s\S]*min-width:\s*1\.45rem[\s\S]*background:\s*transparent[\s\S]*\.subagent-gate-close:hover,[\s\S]*\.subagent-gate-close:focus-visible/, "the close control should remain minimal, compact, and keyboard-visible");
|
|
78
78
|
assert.match(serviceWorker, /"\/subagent-gate-visibility\.mjs"/, "the PWA app shell should cache the visibility module");
|
|
79
|
-
assert.match(server, /"
|
|
79
|
+
assert.match(server, /STATIC_PUBLIC_FILE_EXTENSIONS[\s\S]*"\.mjs"/, "the server should serve typed visibility modules from the public asset boundary");
|
|
80
80
|
assert.match(pkg.scripts.check, /node --check public\/subagent-gate-visibility\.mjs/, "the package check should syntax-check the visibility module");
|
|
81
81
|
|
|
82
82
|
console.log("subagent gate visibility tests passed");
|
|
@@ -33,7 +33,7 @@ assert.match(css, /\.subagent-launch-slot-role \{[^}]*padding: 0\.34rem/, "role
|
|
|
33
33
|
assert.match(css, /\.subagent-launch-slot-controls \{[\s\S]*grid-column: 1 \/ -1[\s\S]*grid-template-columns: repeat\(2, minmax\(0, 1fr\)\)/, "model and thinking controls should remain paired where side-panel space permits");
|
|
34
34
|
assert.match(css, /\.sr-only \{[\s\S]*clip-path: inset\(50%\)[\s\S]*white-space: nowrap/, "screen-reader announcements should stay visually hidden without leaving the accessibility tree");
|
|
35
35
|
assert.match(css, /\.subagent-launch-slot-remove \{[^}]*color: var\(--ctp-red\)/, "destructive slot removal should have a textual control and warning color");
|
|
36
|
-
assert.match(server, /"
|
|
36
|
+
assert.match(server, /STATIC_PUBLIC_FILE_EXTENSIONS[\s\S]*"\.mjs"/, "the server should serve typed browser modules from the public asset boundary");
|
|
37
37
|
assert.match(serviceWorker, /pi-webui-pwa-v\d+[\s\S]*"\/subagent-launch-slot-state\.mjs"/, "the refreshed PWA cache should include the browser module");
|
|
38
38
|
assert.match(pkg, /node --check public\/subagent-launch-slot-state\.mjs/, "package checks should syntax-check the browser state module");
|
|
39
39
|
|
|
@@ -82,7 +82,24 @@ try {
|
|
|
82
82
|
const projectKey = await resolveSubagentLaunchSlotProjectKey(nested);
|
|
83
83
|
assert.equal(projectKey, projectRoot, "nested tab cwd must resolve to the nearest canonical repository root");
|
|
84
84
|
const markerlessProjectKey = await resolveSubagentLaunchSlotProjectKey(settingsRoot);
|
|
85
|
-
assert.equal(markerlessProjectKey, settingsRoot, "a markerless tab cwd must not collapse to the
|
|
85
|
+
assert.equal(markerlessProjectKey, settingsRoot, "a markerless tab cwd must not collapse to the global Pi directory");
|
|
86
|
+
|
|
87
|
+
const piProjectRoot = path.join(settingsRoot, "pi-project");
|
|
88
|
+
const piProjectNested = path.join(piProjectRoot, "nested");
|
|
89
|
+
await mkdir(path.join(piProjectRoot, ".pi"), { recursive: true });
|
|
90
|
+
await mkdir(piProjectNested, { recursive: true });
|
|
91
|
+
assert.equal(await resolveSubagentLaunchSlotProjectKey(piProjectNested), piProjectRoot, "a project-local .pi marker must still define the project root");
|
|
92
|
+
|
|
93
|
+
const simulatedHome = path.join(settingsRoot, "simulated-home");
|
|
94
|
+
const simulatedGlobalPiRoot = path.join(simulatedHome, ".pi");
|
|
95
|
+
const simulatedMarkerlessCwd = path.join(simulatedHome, "workspace");
|
|
96
|
+
await mkdir(simulatedGlobalPiRoot, { recursive: true });
|
|
97
|
+
await mkdir(simulatedMarkerlessCwd, { recursive: true });
|
|
98
|
+
assert.equal(
|
|
99
|
+
await resolveSubagentLaunchSlotProjectKey(simulatedMarkerlessCwd, { globalPiRoot: simulatedGlobalPiRoot }),
|
|
100
|
+
simulatedMarkerlessCwd,
|
|
101
|
+
"the global Pi directory must not turn its parent into a project root",
|
|
102
|
+
);
|
|
86
103
|
|
|
87
104
|
const config = normalizeSubagentLaunchSlots({ user: { roles: validRoles } });
|
|
88
105
|
const inherited = subagentLaunchSlotScopeEntry(config, "project", projectKey);
|
|
@@ -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");
|