@firstpick/pi-package-webui 0.7.3 → 0.7.4
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 +33 -20
- package/bin/pi-webui.mjs +203 -39
- package/index.ts +10 -1
- package/lib/git-workflow-preferences.mjs +10 -3
- package/lib/webui-output-mode.mjs +97 -0
- package/package.json +5 -5
- package/public/app.js +688 -24
- package/public/fast-output-live.mjs +179 -0
- package/public/index.html +28 -3
- package/public/service-worker.js +2 -1
- package/public/styles.css +391 -16
- package/tests/fast-mode-client-static.test.mjs +121 -0
- package/tests/fast-mode-output-work.test.mjs +69 -0
- package/tests/fast-mode-sse-harness.test.mjs +204 -0
- package/tests/fast-output-live.test.mjs +106 -0
- package/tests/fixtures/fake-pi.mjs +58 -0
- package/tests/fixtures/fast-mode-output-events.mjs +50 -0
- package/tests/git-workflow-preferences.test.mjs +8 -2
- package/tests/http-endpoints-harness.test.mjs +9 -0
- package/tests/mobile-static.test.mjs +58 -14
- package/tests/remote-auth-settings-harness.test.mjs +1 -1
- package/tests/webui-output-mode.test.mjs +73 -0
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import { browserOutputEvent, encodeBrowserSseEvent } from "../lib/webui-output-mode.mjs";
|
|
4
|
+
import { createFastModeOutputEvents, fixedFastModeTraceMetadata } from "./fixtures/fast-mode-output-events.mjs";
|
|
5
|
+
|
|
6
|
+
function utf8Bytes(value) {
|
|
7
|
+
return Buffer.byteLength(value, "utf8");
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
function semanticPayload(encodedEvents) {
|
|
11
|
+
const semantics = { lifecycle: [], text: "", indices: [], finalMessage: null, toolEvents: [], errors: [] };
|
|
12
|
+
for (const encoded of encodedEvents) {
|
|
13
|
+
const event = JSON.parse(encoded);
|
|
14
|
+
if (event.type === "message_update") {
|
|
15
|
+
const update = event.assistantMessageEvent;
|
|
16
|
+
if (update?.type === "text_delta") {
|
|
17
|
+
semantics.text += update.delta;
|
|
18
|
+
semantics.indices.push(update.contentIndex ?? event.contentIndex ?? null);
|
|
19
|
+
}
|
|
20
|
+
continue;
|
|
21
|
+
}
|
|
22
|
+
if (["agent_start", "message_start", "message_end", "agent_end"].includes(event.type)) semantics.lifecycle.push(event.type);
|
|
23
|
+
if (event.type === "message_end") semantics.finalMessage = event.message;
|
|
24
|
+
if (["tool_execution_start", "tool_execution_end"].includes(event.type)) {
|
|
25
|
+
semantics.toolEvents.push({ type: event.type, toolCallId: event.toolCallId, toolName: event.toolName, isError: event.isError, result: event.result });
|
|
26
|
+
}
|
|
27
|
+
if (event.error !== undefined) semantics.errors.push({ type: event.type, error: event.error });
|
|
28
|
+
}
|
|
29
|
+
return semantics;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function runProductionSeam(outputMode) {
|
|
33
|
+
const events = createFastModeOutputEvents();
|
|
34
|
+
const original = structuredClone(events);
|
|
35
|
+
const R = events.reduce((total, event) => total + utf8Bytes(JSON.stringify(event)), 0);
|
|
36
|
+
const encoded = events.map((event) => encodeBrowserSseEvent(event, { outputMode })).filter((event) => event !== undefined);
|
|
37
|
+
const S = encoded.reduce((total, payload) => total + utf8Bytes(payload), 0);
|
|
38
|
+
assert.deepEqual(events, original, `${outputMode} production transformation must not mutate parsed/scoped events`);
|
|
39
|
+
return { R, S, encoded, semantic: semanticPayload(encoded) };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const normal = runProductionSeam("normal");
|
|
43
|
+
const compact = runProductionSeam("compact-v1");
|
|
44
|
+
const Wnormal = normal.R + 2 * normal.S;
|
|
45
|
+
const Wfast = compact.R + 2 * compact.S;
|
|
46
|
+
const ratio = Wnormal / Wfast;
|
|
47
|
+
const normalSemanticJson = JSON.stringify(normal.semantic);
|
|
48
|
+
const compactSemanticJson = JSON.stringify(compact.semantic);
|
|
49
|
+
const normalHash = createHash("sha256").update(normalSemanticJson).digest("hex");
|
|
50
|
+
const compactHash = createHash("sha256").update(compactSemanticJson).digest("hex");
|
|
51
|
+
|
|
52
|
+
assert.deepEqual(compact.semantic, normal.semantic, "normal and compact production outputs must retain ordered final semantics");
|
|
53
|
+
assert.equal(compactHash, normalHash, "canonical semantic payload hashes must match");
|
|
54
|
+
assert.ok(ratio >= 1.5, `expected Wnormal / Wfast >= 1.5, got ${ratio}`);
|
|
55
|
+
assert.equal(normal.semantic.text.length, fixedFastModeTraceMetadata().finalBytes, "the fixed trace should contain 512 × 32 bytes of assistant text");
|
|
56
|
+
assert.equal(normal.semantic.indices.length, fixedFastModeTraceMetadata().deltaCount);
|
|
57
|
+
assert.equal(browserOutputEvent(createFastModeOutputEvents()[2], { outputMode: "compact-v1" }).message, undefined, "the byte-work gate must call the production compact seam");
|
|
58
|
+
|
|
59
|
+
console.log(JSON.stringify({
|
|
60
|
+
fixture: fixedFastModeTraceMetadata(),
|
|
61
|
+
R: normal.R,
|
|
62
|
+
Snormal: normal.S,
|
|
63
|
+
Sfast: compact.S,
|
|
64
|
+
Wnormal,
|
|
65
|
+
Wfast,
|
|
66
|
+
ratio: Number(ratio.toFixed(6)),
|
|
67
|
+
semanticHash: normalHash,
|
|
68
|
+
}));
|
|
69
|
+
console.log("fast-mode-output-work.test.mjs passed");
|
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { spawn } from "node:child_process";
|
|
3
|
+
import { chmod, mkdtemp, rm, writeFile } from "node:fs/promises";
|
|
4
|
+
import { tmpdir } from "node:os";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
7
|
+
import { dirname, join } from "node:path";
|
|
8
|
+
import { fileURLToPath } from "node:url";
|
|
9
|
+
|
|
10
|
+
const root = join(dirname(fileURLToPath(import.meta.url)), "..");
|
|
11
|
+
const serverScript = join(root, "bin", "pi-webui.mjs");
|
|
12
|
+
const fakePi = join(root, "tests", "fixtures", "fake-pi.mjs");
|
|
13
|
+
|
|
14
|
+
function nextPort() {
|
|
15
|
+
return 32000 + Math.floor(Math.random() * 20000);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
async function request(port, pathname, { method = "GET", body, timeoutMs = 10_000 } = {}) {
|
|
19
|
+
const response = await fetch(`http://127.0.0.1:${port}${pathname}`, {
|
|
20
|
+
method,
|
|
21
|
+
headers: body === undefined ? undefined : { "content-type": "application/json" },
|
|
22
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
23
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
24
|
+
});
|
|
25
|
+
let payload;
|
|
26
|
+
try {
|
|
27
|
+
payload = await response.json();
|
|
28
|
+
} catch {
|
|
29
|
+
payload = undefined;
|
|
30
|
+
}
|
|
31
|
+
return { status: response.status, body: payload };
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
async function waitForHealth(port, child, output) {
|
|
35
|
+
for (let attempt = 0; attempt < 100; attempt += 1) {
|
|
36
|
+
if (child.exitCode !== null) break;
|
|
37
|
+
try {
|
|
38
|
+
const health = await request(port, "/api/health", { timeoutMs: 1_000 });
|
|
39
|
+
if (health.status === 200) return health;
|
|
40
|
+
} catch {
|
|
41
|
+
// Server startup is asynchronous.
|
|
42
|
+
}
|
|
43
|
+
await delay(50);
|
|
44
|
+
}
|
|
45
|
+
assert.fail(`server did not become healthy:\n${output()}`);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
async function openSse(port, tabId, query = "") {
|
|
49
|
+
const controller = new AbortController();
|
|
50
|
+
const response = await fetch(`http://127.0.0.1:${port}/api/events?tab=${encodeURIComponent(tabId)}${query}`, { signal: controller.signal });
|
|
51
|
+
assert.equal(response.status, 200, "SSE connection should open");
|
|
52
|
+
const client = { controller, events: [], waiters: new Set(), readerError: null };
|
|
53
|
+
const reader = response.body.getReader();
|
|
54
|
+
const decoder = new TextDecoder();
|
|
55
|
+
void (async () => {
|
|
56
|
+
let buffer = "";
|
|
57
|
+
try {
|
|
58
|
+
while (true) {
|
|
59
|
+
const { done, value } = await reader.read();
|
|
60
|
+
if (done) break;
|
|
61
|
+
buffer += decoder.decode(value, { stream: true });
|
|
62
|
+
let boundary;
|
|
63
|
+
while ((boundary = buffer.indexOf("\n\n")) >= 0) {
|
|
64
|
+
const block = buffer.slice(0, boundary);
|
|
65
|
+
buffer = buffer.slice(boundary + 2);
|
|
66
|
+
const data = block.split("\n").filter((line) => line.startsWith("data:")).map((line) => line.slice(5).trim()).join("\n");
|
|
67
|
+
if (!data) continue;
|
|
68
|
+
const event = JSON.parse(data);
|
|
69
|
+
client.events.push(event);
|
|
70
|
+
for (const wake of client.waiters) wake();
|
|
71
|
+
client.waiters.clear();
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
} catch (error) {
|
|
75
|
+
if (!controller.signal.aborted) client.readerError = error;
|
|
76
|
+
for (const wake of client.waiters) wake();
|
|
77
|
+
client.waiters.clear();
|
|
78
|
+
}
|
|
79
|
+
})();
|
|
80
|
+
return client;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
async function waitForEvent(client, predicate, { from = 0, timeoutMs = 8_000 } = {}) {
|
|
84
|
+
let index = from;
|
|
85
|
+
const deadline = Date.now() + timeoutMs;
|
|
86
|
+
while (Date.now() < deadline) {
|
|
87
|
+
while (index < client.events.length) {
|
|
88
|
+
const event = client.events[index++];
|
|
89
|
+
if (predicate(event)) return event;
|
|
90
|
+
}
|
|
91
|
+
if (client.readerError) throw client.readerError;
|
|
92
|
+
await new Promise((resolve, reject) => {
|
|
93
|
+
const timer = setTimeout(() => {
|
|
94
|
+
client.waiters.delete(wake);
|
|
95
|
+
reject(new Error("timed out waiting for SSE event"));
|
|
96
|
+
}, Math.max(1, deadline - Date.now()));
|
|
97
|
+
const wake = () => {
|
|
98
|
+
clearTimeout(timer);
|
|
99
|
+
client.waiters.delete(wake);
|
|
100
|
+
resolve();
|
|
101
|
+
};
|
|
102
|
+
client.waiters.add(wake);
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
throw new Error("timed out waiting for SSE event");
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
async function stopServer(server) {
|
|
109
|
+
for (const client of server.clients) client.controller.abort();
|
|
110
|
+
if (server.child?.exitCode === null && server.child?.signalCode === null) {
|
|
111
|
+
const exited = new Promise((resolve) => server.child.once("exit", resolve));
|
|
112
|
+
server.child.kill("SIGKILL");
|
|
113
|
+
await exited;
|
|
114
|
+
}
|
|
115
|
+
await rm(server.cwd, { recursive: true, force: true });
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const cwd = await mkdtemp(path.join(tmpdir(), "pi-webui-fast-mode-harness-"));
|
|
119
|
+
const settingsFile = path.join(cwd, "settings.json");
|
|
120
|
+
const port = nextPort();
|
|
121
|
+
let child;
|
|
122
|
+
const server = { child: null, cwd, clients: [] };
|
|
123
|
+
let output = "";
|
|
124
|
+
try {
|
|
125
|
+
await writeFile(settingsFile, `${JSON.stringify({ outputModeDefault: "normal" })}\n`);
|
|
126
|
+
await chmod(fakePi, 0o755);
|
|
127
|
+
child = spawn(process.execPath, [serverScript, "--cwd", cwd, "--host", "127.0.0.1", "--port", String(port), "--pi", fakePi], {
|
|
128
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
129
|
+
env: { ...process.env, PI_CODING_AGENT_DIR: path.join(cwd, "agent"), PI_WEBUI_SETTINGS_FILE: settingsFile },
|
|
130
|
+
});
|
|
131
|
+
server.child = child;
|
|
132
|
+
child.stdout.on("data", (chunk) => { output += String(chunk); });
|
|
133
|
+
child.stderr.on("data", (chunk) => { output += String(chunk); });
|
|
134
|
+
const health = await waitForHealth(port, child, () => output);
|
|
135
|
+
assert.deepEqual(health.body.outputMode, { persistedDefault: "normal", effectiveDefault: "normal", source: "persisted", overridden: false });
|
|
136
|
+
const tabId = (await request(port, "/api/tabs")).body?.data?.tabs?.[0]?.id;
|
|
137
|
+
assert.ok(tabId, "server should create an RPC tab");
|
|
138
|
+
|
|
139
|
+
const auto = await openSse(port, tabId, "&outputMode=auto&outputModeProtocol=1");
|
|
140
|
+
const compact = await openSse(port, tabId, "&outputMode=compact-v1&outputModeProtocol=1");
|
|
141
|
+
const legacy = await openSse(port, tabId, "&outputMode=auto");
|
|
142
|
+
server.clients.push(auto, compact, legacy);
|
|
143
|
+
assert.deepEqual((await waitForEvent(auto, (event) => event.type === "webui_connected")).outputMode, {
|
|
144
|
+
protocolVersion: 1, requestedMode: "auto", activeMode: "normal", serverDefault: "normal", serverDefaultSource: "persisted",
|
|
145
|
+
});
|
|
146
|
+
assert.equal((await waitForEvent(compact, (event) => event.type === "webui_connected")).outputMode.activeMode, "compact-v1");
|
|
147
|
+
assert.deepEqual((await waitForEvent(legacy, (event) => event.type === "webui_connected")).outputMode, {
|
|
148
|
+
protocolVersion: 0, requestedMode: "normal", activeMode: "normal", serverDefault: "normal", serverDefaultSource: "persisted",
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
const autoStart = auto.events.length;
|
|
152
|
+
const compactStart = compact.events.length;
|
|
153
|
+
const prompt = await request(port, "/api/prompt", { method: "POST", body: { tab: tabId, message: "fixture fast mode flow" } });
|
|
154
|
+
assert.equal(prompt.status, 200, `fixture prompt should run: ${prompt.body?.error || ""}`);
|
|
155
|
+
const normalDelta = await waitForEvent(auto, (event) => event.type === "message_update", { from: autoStart });
|
|
156
|
+
const compactDelta = await waitForEvent(compact, (event) => event.type === "message_update", { from: compactStart });
|
|
157
|
+
assert.ok(normalDelta.message && normalDelta.assistantMessageEvent.partial, "normal clients retain accumulated message snapshots");
|
|
158
|
+
assert.equal(compactDelta.message, undefined, "compact clients omit duplicate accumulated message snapshots");
|
|
159
|
+
assert.equal(compactDelta.assistantMessageEvent.partial, undefined, "compact clients omit duplicate partial snapshots");
|
|
160
|
+
await waitForEvent(auto, (event) => event.type === "tool_execution_update", { from: autoStart });
|
|
161
|
+
await waitForEvent(compact, (event) => event.type === "tool_execution_end", { from: compactStart });
|
|
162
|
+
await waitForEvent(compact, (event) => event.type === "agent_end", { from: compactStart });
|
|
163
|
+
assert.equal(compact.events.slice(compactStart).some((event) => event.type === "tool_execution_update"), false, "only compact intermediate tool updates are omitted");
|
|
164
|
+
assert.ok(compact.events.slice(compactStart).some((event) => event.type === "pi_stderr"), "diagnostics must pass through compact routing");
|
|
165
|
+
assert.ok(compact.events.slice(compactStart).some((event) => event.type === "extension_ui_request" && event.method === "confirm"), "extension dialogs must pass through compact routing");
|
|
166
|
+
|
|
167
|
+
const switchToCompactAt = auto.events.length;
|
|
168
|
+
const outputPut = await request(port, "/api/webui-output-mode", { method: "PUT", body: { outputModeDefault: "compact-v1" } });
|
|
169
|
+
assert.equal(outputPut.status, 200);
|
|
170
|
+
assert.deepEqual(outputPut.body.data, { persistedDefault: "compact-v1", effectiveDefault: "compact-v1", source: "persisted", overridden: false });
|
|
171
|
+
assert.equal((await waitForEvent(auto, (event) => event.type === "webui_output_mode", { from: switchToCompactAt })).activeMode, "compact-v1", "idle auto clients should switch immediately");
|
|
172
|
+
assert.equal(compact.events.slice(compactStart).some((event) => event.type === "webui_output_mode"), false, "explicit client choices never follow the server default");
|
|
173
|
+
|
|
174
|
+
const switchToNormalAt = auto.events.length;
|
|
175
|
+
await request(port, "/api/webui-output-mode", { method: "PUT", body: { outputModeDefault: "normal" } });
|
|
176
|
+
await waitForEvent(auto, (event) => event.type === "webui_output_mode" && event.activeMode === "normal", { from: switchToNormalAt });
|
|
177
|
+
const barrierStart = auto.events.length;
|
|
178
|
+
assert.equal((await request(port, "/api/prompt", { method: "POST", body: { tab: tabId, message: "fixture fast mode barrier" } })).status, 200);
|
|
179
|
+
await waitForEvent(auto, (event) => event.type === "message_update", { from: barrierStart });
|
|
180
|
+
assert.equal((await request(port, "/api/webui-output-mode", { method: "PUT", body: { outputModeDefault: "compact-v1" } })).status, 200);
|
|
181
|
+
const messageEnd = await waitForEvent(auto, (event) => event.type === "message_end", { from: barrierStart });
|
|
182
|
+
assert.ok(messageEnd.message, "the current semantic unit must retain its old normal representation");
|
|
183
|
+
const control = await waitForEvent(auto, (event) => event.type === "webui_output_mode" && event.activeMode === "compact-v1", { from: barrierStart });
|
|
184
|
+
assert.ok(auto.events.indexOf(messageEnd) < auto.events.indexOf(control), "control must follow the semantic barrier");
|
|
185
|
+
const afterBarrier = auto.events.length;
|
|
186
|
+
assert.equal((await request(port, "/api/prompt", { method: "POST", body: { tab: tabId, message: "fixture fast mode flow" } })).status, 200);
|
|
187
|
+
assert.equal((await waitForEvent(auto, (event) => event.type === "message_update", { from: afterBarrier })).message, undefined, "events after the control use compact representation");
|
|
188
|
+
|
|
189
|
+
const historyStart = auto.events.length;
|
|
190
|
+
assert.equal((await request(port, "/api/prompt", { method: "POST", body: { tab: tabId, message: "fixture fast mode history" } })).status, 200);
|
|
191
|
+
await waitForEvent(auto, (event) => event.type === "agent_end", { from: historyStart });
|
|
192
|
+
const detailed = await request(port, "/api/webui-status?detailed=1&events=200");
|
|
193
|
+
const summary = detailed.body?.data?.events?.findLast((event) => event.type === "message_update" && event.deltaCount === 512);
|
|
194
|
+
assert.deepEqual({ deltaCount: summary?.deltaCount, deltaChars: summary?.deltaChars, deltaUtf8Bytes: summary?.deltaUtf8Bytes }, { deltaCount: 512, deltaChars: 2048, deltaUtf8Bytes: 2048 }, "debug history should coalesce all canonical deltas without retaining content");
|
|
195
|
+
assert.equal(Object.hasOwn(summary || {}, "message"), false);
|
|
196
|
+
assert.equal(Object.hasOwn(summary || {}, "partial"), false);
|
|
197
|
+
|
|
198
|
+
const invalid = await request(port, "/api/webui-output-mode", { method: "PUT", body: { outputModeDefault: "fast" } });
|
|
199
|
+
assert.equal(invalid.status, 400, "configuration API should reject invalid persisted mode values");
|
|
200
|
+
} finally {
|
|
201
|
+
await stopServer(server);
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
console.log("fast-mode-sse-harness.test.mjs passed");
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import {
|
|
3
|
+
createFastOutputLiveState,
|
|
4
|
+
createSustainedFlushScheduler,
|
|
5
|
+
fastOutputLiveTextAndThinking,
|
|
6
|
+
reduceFastOutputLiveEvent,
|
|
7
|
+
seedFastOutputLiveState,
|
|
8
|
+
shouldConsumeFastOutputLiveEvent,
|
|
9
|
+
} from "../public/fast-output-live.mjs";
|
|
10
|
+
|
|
11
|
+
class FakeClock {
|
|
12
|
+
#now = 0;
|
|
13
|
+
#nextId = 1;
|
|
14
|
+
#timers = new Map();
|
|
15
|
+
|
|
16
|
+
now = () => this.#now;
|
|
17
|
+
setTimer = (callback, delay) => {
|
|
18
|
+
const id = this.#nextId++;
|
|
19
|
+
this.#timers.set(id, { callback, at: this.#now + delay });
|
|
20
|
+
return id;
|
|
21
|
+
};
|
|
22
|
+
clearTimer = (id) => this.#timers.delete(id);
|
|
23
|
+
advance(ms) {
|
|
24
|
+
this.#now += ms;
|
|
25
|
+
let due = [...this.#timers.entries()].filter(([, timer]) => timer.at <= this.#now).sort((a, b) => a[1].at - b[1].at);
|
|
26
|
+
while (due.length) {
|
|
27
|
+
for (const [id, timer] of due) {
|
|
28
|
+
this.#timers.delete(id);
|
|
29
|
+
timer.callback();
|
|
30
|
+
}
|
|
31
|
+
due = [...this.#timers.entries()].filter(([, timer]) => timer.at <= this.#now).sort((a, b) => a[1].at - b[1].at);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
let state = createFastOutputLiveState();
|
|
37
|
+
let reduction = reduceFastOutputLiveEvent(state, { type: "message_update", assistantMessageEvent: { type: "text_delta", delta: "A🦄" } });
|
|
38
|
+
state = reduction.state;
|
|
39
|
+
assert.equal(reduction.changed, true);
|
|
40
|
+
assert.equal(state.text, "A🦄", "raw Unicode text deltas should be retained exactly");
|
|
41
|
+
|
|
42
|
+
reduction = reduceFastOutputLiveEvent(state, { type: "message_update", assistantMessageEvent: { type: "thinking_delta", delta: "plan\n" } });
|
|
43
|
+
state = reduction.state;
|
|
44
|
+
assert.equal(state.thinking, "plan\n", "thinking deltas should use a separate raw accumulator");
|
|
45
|
+
|
|
46
|
+
reduction = reduceFastOutputLiveEvent(state, { type: "message_update", assistantMessageEvent: { type: "toolcall_delta", delta: "{\"path\":", toolCall: { id: "tool-1", name: "read" } } });
|
|
47
|
+
state = reduction.state;
|
|
48
|
+
reduction = reduceFastOutputLiveEvent(reduction.state, { type: "message_update", assistantMessageEvent: { type: "toolcall_end", toolCall: { id: "tool-1", name: "read", arguments: { path: "README.md" } } } });
|
|
49
|
+
assert.equal(reduction.state.toolCall.id, "tool-1");
|
|
50
|
+
assert.equal(reduction.state.toolCall.name, "read");
|
|
51
|
+
assert.equal(reduction.state.toolCall.arguments, '{"path":"README.md"}');
|
|
52
|
+
assert.equal(reduction.state.toolCall.complete, true, "self-contained tool end should preserve direct completion data");
|
|
53
|
+
|
|
54
|
+
reduction = reduceFastOutputLiveEvent(reduction.state, { type: "message_update", assistantMessageEvent: { type: "text_end", content: "final ✅" } });
|
|
55
|
+
assert.equal(reduction.state.text, "final ✅", "self-contained text ends should reconcile from direct compact fields");
|
|
56
|
+
assert.equal(reduceFastOutputLiveEvent(reduction.state, { type: "message_update", assistantMessageEvent: { type: "error", errorMessage: "preserve normal error handling" } }).changed, false, "unrecognized/error shapes should remain available to normal diagnostics");
|
|
57
|
+
|
|
58
|
+
// A1: seed normal live content before compact deltas replace its DOM bubble.
|
|
59
|
+
const seededFromNormal = seedFastOutputLiveState({ text: "before switch", thinking: "reasoning before switch" });
|
|
60
|
+
assert.deepEqual(fastOutputLiveTextAndThinking(seededFromNormal), { text: "before switch", thinking: "reasoning before switch" }, "normal live text/thinking should seed one compact live state");
|
|
61
|
+
const continuedCompact = reduceFastOutputLiveEvent(seededFromNormal, { type: "message_update", assistantMessageEvent: { type: "text_delta", delta: " + compact delta" } });
|
|
62
|
+
assert.equal(continuedCompact.state.text, "before switch + compact delta", "compact deltas should continue the seeded normal text in one state");
|
|
63
|
+
|
|
64
|
+
// A2: snapshot compact state before normal rich rendering resumes.
|
|
65
|
+
assert.deepEqual(fastOutputLiveTextAndThinking(continuedCompact.state), { text: "before switch + compact delta", thinking: "reasoning before switch" }, "compact live text/thinking should transfer intact to normal mode");
|
|
66
|
+
|
|
67
|
+
// A3: recognized empty compact end variants have stripped snapshots, so consume
|
|
68
|
+
// them rather than falling into normal handlers that expect those snapshots.
|
|
69
|
+
const emptyCompactTextEnd = reduceFastOutputLiveEvent(createFastOutputLiveState(), { type: "message_update", assistantMessageEvent: { type: "text_end", content: "", delta: "" } });
|
|
70
|
+
const emptyCompactThinkingEnd = reduceFastOutputLiveEvent(createFastOutputLiveState(), { type: "message_update", assistantMessageEvent: { type: "thinking_end", content: "", delta: "" } });
|
|
71
|
+
assert.equal(emptyCompactTextEnd.changed, false, "empty self-contained ends should not request a DOM write");
|
|
72
|
+
assert.equal(emptyCompactTextEnd.kind, "text-end");
|
|
73
|
+
assert.equal(emptyCompactThinkingEnd.changed, false, "empty thinking ends should not request a DOM write");
|
|
74
|
+
assert.equal(emptyCompactThinkingEnd.kind, "thinking-end");
|
|
75
|
+
assert.equal(shouldConsumeFastOutputLiveEvent(emptyCompactTextEnd), true, "recognized empty text end variants should be consumed safely");
|
|
76
|
+
assert.equal(shouldConsumeFastOutputLiveEvent(emptyCompactThinkingEnd), true, "recognized empty thinking end variants should be consumed safely");
|
|
77
|
+
assert.equal(shouldConsumeFastOutputLiveEvent({ changed: false, kind: "ignored" }), false, "unknown compact shapes should still fall through to normal diagnostics");
|
|
78
|
+
|
|
79
|
+
const clock = new FakeClock();
|
|
80
|
+
const flushes = [];
|
|
81
|
+
const scheduler = createSustainedFlushScheduler({
|
|
82
|
+
flush: () => flushes.push(clock.now()),
|
|
83
|
+
now: clock.now,
|
|
84
|
+
setTimer: clock.setTimer,
|
|
85
|
+
clearTimer: clock.clearTimer,
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
assert.equal(scheduler.request(), true, "the first pending output should flush immediately for liveness");
|
|
89
|
+
assert.deepEqual(flushes, [0]);
|
|
90
|
+
scheduler.request();
|
|
91
|
+
clock.advance(99);
|
|
92
|
+
assert.deepEqual(flushes, [0], "sustained output must wait for the 100 ms coalescing boundary");
|
|
93
|
+
clock.advance(1);
|
|
94
|
+
assert.deepEqual(flushes, [0, 100]);
|
|
95
|
+
scheduler.request();
|
|
96
|
+
clock.advance(25);
|
|
97
|
+
assert.equal(scheduler.flushNow(), true, "terminal boundaries synchronously flush pending output");
|
|
98
|
+
assert.deepEqual(flushes, [0, 100, 125]);
|
|
99
|
+
clock.advance(200);
|
|
100
|
+
assert.deepEqual(flushes, [0, 100, 125], "a terminal flush cancels its pending timer");
|
|
101
|
+
scheduler.request();
|
|
102
|
+
scheduler.cancel();
|
|
103
|
+
clock.advance(200);
|
|
104
|
+
assert.deepEqual(flushes, [0, 100, 125], "reset/tab/mode cancellation drops pending compact work");
|
|
105
|
+
|
|
106
|
+
console.log("fast-output-live.test.mjs passed");
|
|
@@ -307,6 +307,63 @@ function handleDocumentArtifactFixturePrompt(command, base) {
|
|
|
307
307
|
return true;
|
|
308
308
|
}
|
|
309
309
|
|
|
310
|
+
function fastModeMessageUpdate(delta, accumulated) {
|
|
311
|
+
const partial = { role: "assistant", content: [{ type: "text", text: accumulated }] };
|
|
312
|
+
return {
|
|
313
|
+
type: "message_update",
|
|
314
|
+
message: partial,
|
|
315
|
+
assistantMessageEvent: { type: "text_delta", delta, contentIndex: 0, partial },
|
|
316
|
+
};
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
function runFastModeFixtureFlow({ barrierOnly = false } = {}) {
|
|
320
|
+
const toolCallId = "fast-mode-tool";
|
|
321
|
+
const firstText = "fast mode first delta ";
|
|
322
|
+
const finalText = `${firstText}and final delta`;
|
|
323
|
+
const finish = () => {
|
|
324
|
+
emitEvent({ type: "message_end", message: { role: "assistant", content: [{ type: "text", text: finalText }] } });
|
|
325
|
+
emitEvent({ type: "agent_end" });
|
|
326
|
+
};
|
|
327
|
+
emitEvent({ type: "agent_start" });
|
|
328
|
+
emitEvent({ type: "message_start", message: { role: "assistant" } });
|
|
329
|
+
emitEvent(fastModeMessageUpdate(firstText, firstText));
|
|
330
|
+
if (barrierOnly) {
|
|
331
|
+
setTimeout(finish, 180);
|
|
332
|
+
return;
|
|
333
|
+
}
|
|
334
|
+
setTimeout(() => {
|
|
335
|
+
emitEvent({ type: "tool_execution_start", toolCallId, toolName: "read", args: { path: "fast-mode.txt" } });
|
|
336
|
+
emitEvent({ type: "tool_execution_update", toolCallId, toolName: "read", partialResult: { content: [{ type: "text", text: "intermediate tool work" }] } });
|
|
337
|
+
emitEvent({ type: "tool_execution_end", toolCallId, toolName: "read", isError: false, result: { content: [{ type: "text", text: "final tool result" }] } });
|
|
338
|
+
emitEvent({ type: "pi_stderr", text: "fast mode fixture diagnostic" });
|
|
339
|
+
emitEvent({ type: "extension_ui_request", id: "fast-mode-dialog", method: "confirm", title: "Fast mode dialog", message: "Preserve this dialog" });
|
|
340
|
+
emitEvent(fastModeMessageUpdate("and final delta", finalText));
|
|
341
|
+
finish();
|
|
342
|
+
}, 20);
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
function runFastModeHistoryFlow() {
|
|
346
|
+
let accumulated = "";
|
|
347
|
+
emitEvent({ type: "agent_start" });
|
|
348
|
+
emitEvent({ type: "message_start", message: { role: "assistant" } });
|
|
349
|
+
for (let index = 0; index < 512; index += 1) {
|
|
350
|
+
const delta = `h${String(index).padStart(3, "0")}`;
|
|
351
|
+
accumulated += delta;
|
|
352
|
+
emitEvent(fastModeMessageUpdate(delta, accumulated));
|
|
353
|
+
}
|
|
354
|
+
emitEvent({ type: "message_end", message: { role: "assistant", content: [{ type: "text", text: accumulated }] } });
|
|
355
|
+
emitEvent({ type: "agent_end" });
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
function handleFastModeFixturePrompt(command, base) {
|
|
359
|
+
const message = String(command.message || "").trim();
|
|
360
|
+
if (!["fixture fast mode flow", "fixture fast mode barrier", "fixture fast mode history"].includes(message)) return false;
|
|
361
|
+
respond({ ...base, data: { output: "fast mode fixture accepted" } });
|
|
362
|
+
if (message.endsWith("history")) runFastModeHistoryFlow();
|
|
363
|
+
else runFastModeFixtureFlow({ barrierOnly: message.endsWith("barrier") });
|
|
364
|
+
return true;
|
|
365
|
+
}
|
|
366
|
+
|
|
310
367
|
function handleTransportFixturePrompt(command, base) {
|
|
311
368
|
const message = String(command.message || "").trim();
|
|
312
369
|
if (message === "fixture stderr diagnostic") {
|
|
@@ -510,6 +567,7 @@ rl.on("line", (line) => {
|
|
|
510
567
|
}
|
|
511
568
|
case "prompt":
|
|
512
569
|
if (handleWebuiHelperPrompt(command, base)) return;
|
|
570
|
+
if (handleFastModeFixturePrompt(command, base)) return;
|
|
513
571
|
if (handleTransportFixturePrompt(command, base)) return;
|
|
514
572
|
if (handleSubagentFixturePrompt(command, base)) return;
|
|
515
573
|
if (handleDocumentArtifactFixturePrompt(command, base)) return;
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
const DELTA_COUNT = 512;
|
|
2
|
+
const DELTA_BYTES = 32;
|
|
3
|
+
|
|
4
|
+
function fixedDelta(index) {
|
|
5
|
+
return `d${String(index).padStart(4, "0")}${"x".repeat(DELTA_BYTES - 5)}`;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
function assistantSnapshot(text) {
|
|
9
|
+
return {
|
|
10
|
+
role: "assistant",
|
|
11
|
+
content: [{ type: "text", text }],
|
|
12
|
+
};
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function createFastModeOutputEvents() {
|
|
16
|
+
const events = [
|
|
17
|
+
{ type: "agent_start", tabId: "fast-mode-trace" },
|
|
18
|
+
{ type: "tool_execution_start", tabId: "fast-mode-trace", toolCallId: "trace-tool", toolName: "read", args: { path: "trace.txt" } },
|
|
19
|
+
{ type: "tool_execution_end", tabId: "fast-mode-trace", toolCallId: "trace-tool", toolName: "read", isError: false, result: { content: [{ type: "text", text: "trace result" }] } },
|
|
20
|
+
{ type: "pi_stdout_parse_error", tabId: "fast-mode-trace", error: "trace diagnostic" },
|
|
21
|
+
{ type: "message_start", tabId: "fast-mode-trace", message: { role: "assistant" } },
|
|
22
|
+
];
|
|
23
|
+
let accumulated = "";
|
|
24
|
+
for (let index = 0; index < DELTA_COUNT; index += 1) {
|
|
25
|
+
const delta = fixedDelta(index);
|
|
26
|
+
accumulated += delta;
|
|
27
|
+
const snapshot = assistantSnapshot(accumulated);
|
|
28
|
+
events.push({
|
|
29
|
+
type: "message_update",
|
|
30
|
+
tabId: "fast-mode-trace",
|
|
31
|
+
contentIndex: 0,
|
|
32
|
+
message: snapshot,
|
|
33
|
+
assistantMessageEvent: {
|
|
34
|
+
type: "text_delta",
|
|
35
|
+
delta,
|
|
36
|
+
contentIndex: 0,
|
|
37
|
+
partial: assistantSnapshot(accumulated),
|
|
38
|
+
},
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
events.push(
|
|
42
|
+
{ type: "message_end", tabId: "fast-mode-trace", message: assistantSnapshot(accumulated) },
|
|
43
|
+
{ type: "agent_end", tabId: "fast-mode-trace" },
|
|
44
|
+
);
|
|
45
|
+
return events;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function fixedFastModeTraceMetadata() {
|
|
49
|
+
return { deltaCount: DELTA_COUNT, deltaBytes: DELTA_BYTES, finalBytes: DELTA_COUNT * DELTA_BYTES };
|
|
50
|
+
}
|
|
@@ -31,14 +31,18 @@ const settingsFile = path.join(root, "settings.json");
|
|
|
31
31
|
try {
|
|
32
32
|
await writeFile(settingsFile, `${JSON.stringify({ version: 1, remoteAuthEnabled: true }, null, 2)}\n`, "utf8");
|
|
33
33
|
const migrated = await readWebuiSettings(settingsFile);
|
|
34
|
-
assert.equal(migrated.version,
|
|
34
|
+
assert.equal(migrated.version, 4);
|
|
35
35
|
assert.equal(migrated.remoteAuthEnabled, true, "legacy Remote PIN state should survive schema migration");
|
|
36
|
+
assert.equal(migrated.outputModeDefault, "normal", "legacy settings should default browser output to normal");
|
|
36
37
|
assert.equal(isGitWorkflowSetupComplete(migrated.gitWorkflow), false);
|
|
37
38
|
assert.equal(migrated.resourceDefaults.tools.enabledTools, null, "legacy settings should inherit Pi's normal tool defaults");
|
|
38
39
|
assert.equal(migrated.resourceDefaults.skills.enabledSkills, null, "legacy settings should inherit Pi's normal skill defaults");
|
|
39
40
|
assert.equal(migrated.gitWorkflow.stagingPolicy, "review");
|
|
40
41
|
assert.equal(migrated.gitWorkflow.generation.thinkingLevel, "low");
|
|
41
42
|
|
|
43
|
+
await writeFile(settingsFile, `${JSON.stringify({ version: 4, remoteAuthEnabled: true, outputModeDefault: "unsupported" }, null, 2)}\n`, "utf8");
|
|
44
|
+
assert.equal((await readWebuiSettings(settingsFile)).outputModeDefault, "normal", "invalid persisted output modes must fail closed to normal");
|
|
45
|
+
|
|
42
46
|
const saved = await writeGitWorkflowPreferences({
|
|
43
47
|
generation: { provider: "fake", modelId: "fake-model", thinkingLevel: "off", unavailablePolicy: "ask" },
|
|
44
48
|
commit: { language: "de", defaultVariant: "long", scope: "required" },
|
|
@@ -53,6 +57,7 @@ try {
|
|
|
53
57
|
assert.equal(saved.stagingPolicy, "preserve");
|
|
54
58
|
|
|
55
59
|
await writeWebuiSettings({
|
|
60
|
+
outputModeDefault: "compact-v1",
|
|
56
61
|
resourceDefaults: {
|
|
57
62
|
tools: { enabledTools: ["read", " write ", "read", ""] },
|
|
58
63
|
skills: { enabledSkills: ["repo-explorer", "code-security"] },
|
|
@@ -65,8 +70,9 @@ try {
|
|
|
65
70
|
assert.equal(partiallyUpdated.deliveryMode, "current");
|
|
66
71
|
|
|
67
72
|
const persisted = JSON.parse(await readFile(settingsFile, "utf8"));
|
|
68
|
-
assert.equal(persisted.version,
|
|
73
|
+
assert.equal(persisted.version, 4);
|
|
69
74
|
assert.equal(persisted.remoteAuthEnabled, true);
|
|
75
|
+
assert.equal(persisted.outputModeDefault, "compact-v1", "output-mode default should persist beside existing Web UI settings");
|
|
70
76
|
assert.equal(persisted.gitWorkflow.generation.provider, "fake");
|
|
71
77
|
assert.deepEqual(persisted.resourceDefaults.tools.enabledTools, ["read", "write"], "global tool defaults should be normalized and deduplicated");
|
|
72
78
|
assert.deepEqual(persisted.resourceDefaults.skills.enabledSkills, ["repo-explorer", "code-security"], "global skill defaults should persist beside other Web UI settings");
|
|
@@ -258,6 +258,15 @@ try {
|
|
|
258
258
|
assert.equal(gzipResponse.headers.get("content-encoding"), "gzip", "styles.css should fall back to gzip");
|
|
259
259
|
await gzipResponse.arrayBuffer();
|
|
260
260
|
|
|
261
|
+
// app.js statically imports the fast-output helper at startup. Verify the
|
|
262
|
+
// real server serves it so an omitted allowlist entry cannot disable the UI.
|
|
263
|
+
const fastOutputModuleResponse = await fetch(`http://127.0.0.1:${port}/fast-output-live.mjs`, {
|
|
264
|
+
signal: AbortSignal.timeout(5_000),
|
|
265
|
+
});
|
|
266
|
+
assert.equal(fastOutputModuleResponse.status, 200, "fast-output-live.mjs must be served for the Web UI entry point");
|
|
267
|
+
assert.match(fastOutputModuleResponse.headers.get("content-type") || "", /text\/javascript/, "fast-output-live.mjs should use a JavaScript MIME type");
|
|
268
|
+
assert.equal(await fastOutputModuleResponse.text(), await readFile(join(root, "public", "fast-output-live.mjs"), "utf8"), "served fast-output-live.mjs must match the source module");
|
|
269
|
+
|
|
261
270
|
// The browser voice loop is dynamically imported by app.js; a missing static
|
|
262
271
|
// allowlist entry would 404 the module and silently disable voice mode.
|
|
263
272
|
const voiceModuleResponse = await fetch(`http://127.0.0.1:${port}/voice-conversation.mjs`, {
|