@firstpick/pi-package-webui 0.7.2 → 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 +38 -25
- package/bin/pi-webui.mjs +469 -106
- package/index.ts +10 -1
- package/lib/git-live-watcher.mjs +135 -0
- package/lib/git-message-artifacts.mjs +103 -0
- package/lib/git-workflow-preferences.mjs +10 -3
- package/lib/process-tree.mjs +3 -1
- package/lib/webui-output-mode.mjs +97 -0
- package/package.json +7 -6
- package/public/app.js +1170 -97
- package/public/fast-output-live.mjs +179 -0
- package/public/index.html +31 -5
- package/public/service-worker.js +2 -1
- package/public/styles.css +474 -12
- package/tests/app-runner-windows-conpty-harness.test.mjs +140 -0
- package/tests/danger-button-contrast-static.test.mjs +32 -0
- 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 +59 -0
- package/tests/fixtures/fast-mode-output-events.mjs +50 -0
- package/tests/footer-middle-truncation.test.mjs +118 -0
- package/tests/git-live-watcher.test.mjs +93 -0
- package/tests/git-message-artifacts.test.mjs +59 -0
- package/tests/git-panel-live-updates-static.test.mjs +54 -0
- package/tests/git-panel-render-stability-static.test.mjs +1 -1
- package/tests/git-workflow-preferences.test.mjs +8 -2
- package/tests/guided-git-message-reliability-static.test.mjs +38 -0
- package/tests/http-endpoints-harness.test.mjs +61 -5
- package/tests/image-payload-hardening-harness.test.mjs +115 -0
- package/tests/mobile-static.test.mjs +79 -20
- package/tests/pi-footer-calibration-static.test.mjs +55 -0
- package/tests/remote-auth-settings-harness.test.mjs +1 -1
- package/tests/runtime-error-visibility.test.mjs +63 -0
- package/tests/side-panel-context-menu-static.test.mjs +74 -0
- package/tests/webui-output-mode.test.mjs +73 -0
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { spawn, spawnSync } 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
|
+
if (process.platform !== "win32") {
|
|
11
|
+
console.log("app-runner-windows-conpty-harness.test.mjs skipped (Windows only)");
|
|
12
|
+
process.exit(0);
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
assert.equal(spawnSync("bash", ["--version"], { stdio: "ignore" }).status, 0, "Windows ConPTY test requires bash on PATH");
|
|
16
|
+
await import("node-pty");
|
|
17
|
+
|
|
18
|
+
const root = join(dirname(fileURLToPath(import.meta.url)), "..");
|
|
19
|
+
const serverScript = join(root, "bin", "pi-webui.mjs");
|
|
20
|
+
const fakePi = join(root, "tests", "fixtures", "fake-pi.mjs");
|
|
21
|
+
const port = 30000 + Math.floor(Math.random() * 20000);
|
|
22
|
+
|
|
23
|
+
async function request(pathname, { method = "GET", body, timeoutMs = 5_000 } = {}) {
|
|
24
|
+
const response = await fetch(`http://127.0.0.1:${port}${pathname}`, {
|
|
25
|
+
method,
|
|
26
|
+
headers: body === undefined ? undefined : { "content-type": "application/json" },
|
|
27
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
28
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
29
|
+
});
|
|
30
|
+
const payload = await response.json().catch(() => undefined);
|
|
31
|
+
return { status: response.status, body: payload };
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
async function waitFor(description, probe, { attempts = 100, intervalMs = 100 } = {}) {
|
|
35
|
+
let last;
|
|
36
|
+
for (let attempt = 0; attempt < attempts; attempt += 1) {
|
|
37
|
+
last = await probe();
|
|
38
|
+
if (last) return last;
|
|
39
|
+
await delay(intervalMs);
|
|
40
|
+
}
|
|
41
|
+
assert.fail(`${description} did not happen in time${last ? `; last=${JSON.stringify(last)}` : ""}`);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
async function rmWithRetry(target) {
|
|
45
|
+
for (let attempt = 0; attempt < 8; attempt += 1) {
|
|
46
|
+
try {
|
|
47
|
+
await rm(target, { recursive: true, force: true });
|
|
48
|
+
return;
|
|
49
|
+
} catch (error) {
|
|
50
|
+
if (attempt === 7 || !["EBUSY", "EPERM", "ENOTEMPTY"].includes(error?.code)) throw error;
|
|
51
|
+
await delay(150 * (attempt + 1));
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const cwd = await mkdtemp(path.join(tmpdir(), "pi-webui-conpty-"));
|
|
57
|
+
const settingsFile = path.join(cwd, "webui-settings.json");
|
|
58
|
+
await chmod(fakePi, 0o755);
|
|
59
|
+
await writeFile(path.join(cwd, "interactive-fixture"), [
|
|
60
|
+
"#!/usr/bin/env bash",
|
|
61
|
+
"set -euo pipefail",
|
|
62
|
+
"if [[ -t 0 && -t 1 ]]; then printf 'tty=yes\\n'; else printf 'tty=no\\n'; fi",
|
|
63
|
+
"read -r -p 'choice? ' answer",
|
|
64
|
+
"printf 'selected:%s\\n' \"$answer\"",
|
|
65
|
+
"",
|
|
66
|
+
].join("\n"));
|
|
67
|
+
|
|
68
|
+
const server = spawn(process.execPath, [serverScript, "--cwd", cwd, "--host", "127.0.0.1", "--port", String(port), "--pi", fakePi], {
|
|
69
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
70
|
+
env: { ...process.env, PI_WEBUI_SETTINGS_FILE: settingsFile },
|
|
71
|
+
windowsHide: true,
|
|
72
|
+
});
|
|
73
|
+
let serverOutput = "";
|
|
74
|
+
server.stdout.on("data", (chunk) => { serverOutput += String(chunk); });
|
|
75
|
+
server.stderr.on("data", (chunk) => { serverOutput += String(chunk); });
|
|
76
|
+
|
|
77
|
+
try {
|
|
78
|
+
await waitFor("server health", async () => {
|
|
79
|
+
if (server.exitCode !== null) return false;
|
|
80
|
+
try {
|
|
81
|
+
const health = await request("/api/health", { timeoutMs: 1_000 });
|
|
82
|
+
return health.status === 200 && health.body?.ok === true;
|
|
83
|
+
} catch {
|
|
84
|
+
return false;
|
|
85
|
+
}
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
const tabsResponse = await request("/api/tabs");
|
|
89
|
+
const tabId = tabsResponse.body?.data?.tabs?.[0]?.id || tabsResponse.body?.tabs?.[0]?.id;
|
|
90
|
+
assert.ok(tabId, `startup tab should exist, output:\n${serverOutput}`);
|
|
91
|
+
|
|
92
|
+
const saved = await request("/api/app-runner-config", {
|
|
93
|
+
method: "POST",
|
|
94
|
+
body: { tab: tabId, runner: { label: "Windows ConPTY bash", command: "bash", path: "interactive-fixture" } },
|
|
95
|
+
timeoutMs: 10_000,
|
|
96
|
+
});
|
|
97
|
+
assert.equal(saved.status, 200, `saving ConPTY runner should succeed: ${saved.body?.error || serverOutput}`);
|
|
98
|
+
const runner = saved.body?.data?.runners?.find((item) => item.custom === true && item.label === "Windows ConPTY bash");
|
|
99
|
+
assert.ok(runner?.id, "Windows ConPTY custom runner should be available");
|
|
100
|
+
|
|
101
|
+
let state = await request("/api/app-runner", {
|
|
102
|
+
method: "POST",
|
|
103
|
+
body: { tab: tabId, runnerId: runner.id },
|
|
104
|
+
timeoutMs: 10_000,
|
|
105
|
+
});
|
|
106
|
+
assert.equal(state.status, 200, `ConPTY runner should start: ${state.body?.error || serverOutput}`);
|
|
107
|
+
assert.equal(state.body?.data?.activeRun?.executionMode, "conpty", "Windows runner should use ConPTY");
|
|
108
|
+
|
|
109
|
+
await waitFor("TTY prompt", async () => {
|
|
110
|
+
state = await request(`/api/app-runners?tab=${encodeURIComponent(tabId)}`);
|
|
111
|
+
const output = [...(state.body?.data?.activeRun?.lines || []), state.body?.data?.activeRun?.pendingLine || ""].join("\n");
|
|
112
|
+
return /tty=yes/.test(output) && /choice\?/.test(output);
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
const input = await request("/api/app-runner/input", {
|
|
116
|
+
method: "POST",
|
|
117
|
+
body: { tab: tabId, text: "alpha", closeStdin: true },
|
|
118
|
+
timeoutMs: 10_000,
|
|
119
|
+
});
|
|
120
|
+
assert.equal(input.status, 200, `ConPTY input should be accepted: ${input.body?.error || serverOutput}`);
|
|
121
|
+
|
|
122
|
+
await waitFor("interactive runner completion", async () => {
|
|
123
|
+
state = await request(`/api/app-runners?tab=${encodeURIComponent(tabId)}`);
|
|
124
|
+
return state.body?.data?.activeRun?.status === "done";
|
|
125
|
+
});
|
|
126
|
+
const output = [...(state.body?.data?.activeRun?.lines || []), state.body?.data?.activeRun?.pendingLine || ""].join("\n");
|
|
127
|
+
assert.match(output, /selected:alpha/, "Windows ConPTY runner should receive WebUI input");
|
|
128
|
+
|
|
129
|
+
await request("/api/shutdown", { method: "POST" }).catch(() => undefined);
|
|
130
|
+
for (let attempt = 0; attempt < 50 && server.exitCode === null; attempt += 1) await delay(100);
|
|
131
|
+
assert.notEqual(server.exitCode, null, "server should exit after shutdown");
|
|
132
|
+
console.log("app-runner-windows-conpty-harness.test.mjs passed");
|
|
133
|
+
} finally {
|
|
134
|
+
if (server.exitCode === null) {
|
|
135
|
+
await request("/api/shutdown", { method: "POST", timeoutMs: 1_000 }).catch(() => undefined);
|
|
136
|
+
for (let attempt = 0; attempt < 20 && server.exitCode === null; attempt += 1) await delay(100);
|
|
137
|
+
if (server.exitCode === null) server.kill("SIGKILL");
|
|
138
|
+
}
|
|
139
|
+
await rmWithRetry(cwd);
|
|
140
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
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 css = await readFile(join(root, "public", "styles.css"), "utf8");
|
|
8
|
+
|
|
9
|
+
function ruleBody(selector) {
|
|
10
|
+
const escaped = selector.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
11
|
+
const match = css.match(new RegExp(`${escaped}\\s*\\{([^}]+)\\}`));
|
|
12
|
+
assert.ok(match, `${selector} should have a CSS rule`);
|
|
13
|
+
return match[1];
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const filledDanger = ruleBody("button.danger");
|
|
17
|
+
assert.match(filledDanger, /color:\s*var\(--button-primary-text\)/, "filled danger buttons should retain dark high-contrast text");
|
|
18
|
+
assert.match(filledDanger, /background:\s*linear-gradient\([^;]*var\(--ctp-red\)[^;]*var\(--ctp-peach\)/, "filled danger buttons should retain their danger gradient");
|
|
19
|
+
|
|
20
|
+
for (const selector of [
|
|
21
|
+
".git-side-panel-context-menu button.danger",
|
|
22
|
+
".aur-review-action.danger",
|
|
23
|
+
".git-operation-button.danger",
|
|
24
|
+
".git-file-action.danger",
|
|
25
|
+
]) {
|
|
26
|
+
const body = ruleBody(selector);
|
|
27
|
+
assert.match(body, /color:\s*var\(--ctp-red\)/, `${selector} should retain its red outline-button text`);
|
|
28
|
+
assert.match(body, /background:\s*rgba\(var\(--ctp-crust-rgb\),\s*0\.[0-9]+\)/, `${selector} should place red text on a neutral surface`);
|
|
29
|
+
assert.doesNotMatch(body, /background:[^;]*(?:--ctp-red|--ctp-peach)/, `${selector} must not place red text on a red danger background`);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
console.log("danger button contrast static tests passed");
|
|
@@ -0,0 +1,121 @@
|
|
|
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 { createFastModeOutputEvents } from "./fixtures/fast-mode-output-events.mjs";
|
|
6
|
+
|
|
7
|
+
const root = join(dirname(fileURLToPath(import.meta.url)), "..");
|
|
8
|
+
const [app, helper, html, worker, styles, packageRaw] = await Promise.all([
|
|
9
|
+
readFile(join(root, "public", "app.js"), "utf8"),
|
|
10
|
+
readFile(join(root, "public", "fast-output-live.mjs"), "utf8"),
|
|
11
|
+
readFile(join(root, "public", "index.html"), "utf8"),
|
|
12
|
+
readFile(join(root, "public", "service-worker.js"), "utf8"),
|
|
13
|
+
readFile(join(root, "public", "styles.css"), "utf8"),
|
|
14
|
+
readFile(join(root, "package.json"), "utf8"),
|
|
15
|
+
]);
|
|
16
|
+
|
|
17
|
+
function functionBody(source, name) {
|
|
18
|
+
const marker = `function ${name}(`;
|
|
19
|
+
const start = source.indexOf(marker);
|
|
20
|
+
assert.notEqual(start, -1, `${name} should be defined`);
|
|
21
|
+
let parenDepth = 0;
|
|
22
|
+
let open = -1;
|
|
23
|
+
for (let index = start + marker.length - 1; index < source.length; index += 1) {
|
|
24
|
+
if (source[index] === "(") parenDepth += 1;
|
|
25
|
+
else if (source[index] === ")") parenDepth -= 1;
|
|
26
|
+
else if (source[index] === "{" && parenDepth === 0) {
|
|
27
|
+
open = index;
|
|
28
|
+
break;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
assert.notEqual(open, -1, `${name} should open`);
|
|
32
|
+
let depth = 0;
|
|
33
|
+
for (let index = open; index < source.length; index += 1) {
|
|
34
|
+
if (source[index] === "{") depth += 1;
|
|
35
|
+
if (source[index] === "}") {
|
|
36
|
+
depth -= 1;
|
|
37
|
+
if (depth === 0) return source.slice(open + 1, index);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
assert.fail(`${name} should close`);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const connectEvents = functionBody(app, "connectEvents");
|
|
44
|
+
const compactUpdate = functionBody(app, "handleCompactMessageUpdate");
|
|
45
|
+
const compactFlush = functionBody(app, "flushCompactLiveOutput");
|
|
46
|
+
const compactToolShell = functionBody(app, "renderCompactToolShell");
|
|
47
|
+
const resetStream = functionBody(app, "resetStreamBubble");
|
|
48
|
+
const normalToCompact = functionBody(app, "transitionNormalLiveOutputToCompact");
|
|
49
|
+
const compactToNormal = functionBody(app, "transitionCompactLiveOutputToNormal");
|
|
50
|
+
const nativeSettingsDialog = functionBody(app, "openNativeSettingsDialog");
|
|
51
|
+
const nativeSettingsPayload = functionBody(app, "collectNativeSettingsPayload");
|
|
52
|
+
const outputModeMetadataText = functionBody(app, "webuiOutputModeMetadataText");
|
|
53
|
+
const sidebarOutputModeRefresh = functionBody(app, "refreshSidebarOutputMode");
|
|
54
|
+
const sidebarOutputModeApply = functionBody(app, "applySidebarOutputMode");
|
|
55
|
+
|
|
56
|
+
assert.match(app, /from "\.\/fast-output-live\.mjs"/, "browser should import the pure compact live helper");
|
|
57
|
+
assert.match(connectEvents, /outputMode:\s*eventSourceOutputModeRequest/, "all new EventSource connections should negotiate an explicit output mode");
|
|
58
|
+
assert.match(connectEvents, /outputModeProtocol:\s*"1"/, "all new EventSource connections should negotiate protocol 1");
|
|
59
|
+
assert.match(app, /function outputModeAcknowledgement[\s\S]*?outputMode\?\.protocolVersion !== 1[\s\S]*?function acceptOutputModeAcknowledgement[\s\S]*?outputModeAcknowledgement\(event\)[\s\S]*?connectEvents\(activeTabContext\(\), \{ requestedMode: "normal", fallbackAttempted: true \}\)/, "unacknowledged or old servers should receive one normal-mode fallback");
|
|
60
|
+
assert.match(app, /function compactOutputActive\(\) \{\s+return outputModeAcknowledged && activeOutputMode === "compact-v1";/, "compact rendering must remain acknowledgement-gated");
|
|
61
|
+
assert.match(app, /case "webui_output_mode":[\s\S]*?applyOutputModeControl\(event, tabContext\)/, "mode-control events should be handled before subsequent compact representation events");
|
|
62
|
+
assert.match(app, /function applyOutputModeControl[\s\S]*?finishCompactLiveOutput\(tabContext\)[\s\S]*?resetCompactLiveOutput\(\)/, "mode changes should synchronously flush then reset compact state at semantic boundaries");
|
|
63
|
+
assert.match(normalToCompact, /seedFastOutputLiveState\(\{ text: streamRawText, thinking: streamThinkingRawText \}\)/, "normal-to-compact controls should seed pre-switch text and thinking into the compact state");
|
|
64
|
+
assert.match(normalToCompact, /setStreamRawText\(""\)[\s\S]*?setStreamThinkingRawText\(""\)[\s\S]*?removeStreamBubble\(\)[\s\S]*?removeStreamingThinkingBubble\(\)[\s\S]*?flushCompactLiveOutput\(\)/, "normal-to-compact controls should remove stale normal bubbles and synchronously show the seeded compact state");
|
|
65
|
+
assert.match(compactToNormal, /fastOutputLiveTextAndThinking\(compactLiveState\)[\s\S]*?resetCompactLiveOutput\(\)[\s\S]*?setStreamRawText\(live\.text\)[\s\S]*?setStreamThinkingRawText\(live\.thinking\)[\s\S]*?renderStreamingAssistantText\(\)/, "compact-to-normal controls should transfer pre-switch live text/thinking before normal rendering resumes");
|
|
66
|
+
|
|
67
|
+
assert.doesNotMatch(compactUpdate, /event\.message|assistantMessageEvent\.partial|renderStreamingMarkdown|renderMarkdown|syncLiveTodoProgressWidgetFromText/, "compact deltas should consume direct fields without accumulated scans, markdown, or todo extraction");
|
|
68
|
+
assert.match(compactUpdate, /reduceFastOutputLiveEvent\(compactLiveState, event\)/, "compact deltas should use the pure reducer");
|
|
69
|
+
assert.match(compactUpdate, /shouldConsumeFastOutputLiveEvent\(reduced\)/, "recognized compact empty end variants should be consumed instead of reaching normal handlers with stripped snapshots");
|
|
70
|
+
assert.match(helper, /function shouldConsumeFastOutputLiveEvent\(reduction = \{\}\)[\s\S]*?"text-end"[\s\S]*?"thinking-end"[\s\S]*?"toolcall-end"/, "the reducer policy should consume only recognized compact end variants when no DOM state changes");
|
|
71
|
+
assert.match(compactFlush, /\.textContent = compactLiveState\.text/, "compact text must render through a stable plain-text node");
|
|
72
|
+
assert.match(compactFlush, /\.textContent = compactLiveState\.thinking/, "compact thinking must render through a stable plain-text node");
|
|
73
|
+
assert.doesNotMatch(compactFlush, /renderStreamingMarkdown|renderThinkingMarkdown|renderToolExecution|normalizeToolExecution/, "compact flushing must not invoke live rich renderers");
|
|
74
|
+
assert.doesNotMatch(compactToolShell, /normalizeToolExecution|toolExecutionRenderSignature|renderToolExecution|handleToolExecutionUpdate|JSON\.stringify/, "compact tool shells must defer rich bodies and raw serialization");
|
|
75
|
+
assert.match(app, /case "tool_execution_update":\s+if \(!compactOutputActive\(\)\) handleToolExecutionUpdate\(event\);/, "compact mode should not build intermediate rich tool updates");
|
|
76
|
+
assert.match(app, /case "tool_execution_end":[\s\S]*?compactLiveScheduler\.flushNow\(\)[\s\S]*?renderCompactToolShell\(event, \{ complete: true \}\)[\s\S]*?finishCompactLiveOutput\(tabContext\)/, "compact tool completion should remain lightweight and request final reconciliation");
|
|
77
|
+
assert.match(resetStream, /resetCompactLiveOutput\(\)/, "reset and tab changes should cancel compact pending work");
|
|
78
|
+
assert.match(app, /case "message_end": \{\s+if \(compactOutputActive\(\)\) finishCompactLiveOutput\(tabContext\);/, "message ends should synchronously flush compact output before reconciliation");
|
|
79
|
+
assert.match(app, /case "agent_end":\s+if \(compactOutputActive\(\)\) finishCompactLiveOutput\(tabContext\);/, "agent ends should synchronously flush compact output before reconciliation");
|
|
80
|
+
|
|
81
|
+
assert.match(app, /const SETTINGS_OUTPUT_MODE_OPTIONS = \[[\s\S]*?value: "normal"[\s\S]*?value: "compact-v1"/, "settings should offer normal and compact-v1 server defaults");
|
|
82
|
+
assert.match(nativeSettingsDialog, /api\("\/api\/webui-output-mode", \{ scoped: false \}\)/, "opening settings should load output-mode metadata from the separate server API");
|
|
83
|
+
assert.match(nativeSettingsDialog, /outputMode: nativeSettingSelect\("Output processing", outputModeMetadata\.persistedDefault, SETTINGS_OUTPUT_MODE_OPTIONS,[\s\S]*?\{ label: "server", tone: "startup" \}\)/, "Browser workflow should expose a server-badged output-processing selector");
|
|
84
|
+
assert.match(nativeSettingsDialog, /Compact reduces local output-processing and live fidelity, restores rich final output, and does not change model inference or token generation\. Changes use server barriers without restarting Pi\./, "settings copy should bound compact mode to local output processing and preserve inference semantics");
|
|
85
|
+
assert.match(nativeSettingsDialog, /nativeSettingsSection\("Browser workflow"[\s\S]*?controls\.outputMode/, "the output-mode selector should be placed in Browser workflow");
|
|
86
|
+
assert.match(outputModeMetadataText, /Persisted default:[\s\S]*?Effective mode:[\s\S]*?Source:/, "settings should display persisted default plus effective mode and source");
|
|
87
|
+
assert.match(outputModeMetadataText, /metadata\.overridden[\s\S]*?overrides the persisted setting/, "settings should display CLI/environment override state when it wins");
|
|
88
|
+
assert.match(nativeSettingsDialog, /Output-mode API unavailable:[\s\S]*?Showing the normal default; other settings can still be applied\./, "unavailable output-mode API should leave a visible nonfatal normal-default diagnostic");
|
|
89
|
+
assert.match(nativeSettingsDialog, /controls\.outputMode\.select\.disabled = !!outputModeApiDiagnostic/, "unavailable output-mode API should safely prevent an unpersistable mode change");
|
|
90
|
+
assert.match(nativeSettingsDialog, /method: "PUT",[\s\S]*?body: \{ outputModeDefault: controls\.outputMode\.select\.value \},[\s\S]*?scoped: false,[\s\S]*?const refreshedOutputMode = await api\("\/api\/webui-output-mode", \{ scoped: false \}\)/, "changed output defaults should PUT the server payload and then refresh metadata");
|
|
91
|
+
assert.doesNotMatch(nativeSettingsPayload, /outputMode(?:Default|Metadata|ApiDiagnostic|Changed)?/, "server-scoped output mode must stay out of the native SettingsManager payload");
|
|
92
|
+
assert.match(nativeSettingsDialog, /const response = await nativeCommandApi\("\/api\/settings", \{ method: "POST", body: \{ settings: payload, reload \} \}\);[\s\S]*?nativeSettingsChangedMessage\(response, reload\)/, "existing native settings apply behavior should remain intact");
|
|
93
|
+
|
|
94
|
+
assert.match(html, /data-side-panel-section="controls"[\s\S]*?id="outputProcessingControlsTitle">Output processing<[\s\S]*?<span class="control-scope-badge">Server<\/span>[\s\S]*?id="fastOutputModeSelect"[\s\S]*?<option value="normal">Normal<\/option>[\s\S]*?<option value="compact-v1">Fast<\/option>[\s\S]*?id="setFastOutputModeButton"[\s\S]*?id="fastOutputModeStatus"/, "Controls should expose a server-scoped normal/fast selector with apply button and live status");
|
|
95
|
+
assert.match(app, /fastOutputModeSelect: \$\("#fastOutputModeSelect"\)[\s\S]*?setFastOutputModeButton: \$\("#setFastOutputModeButton"\)[\s\S]*?fastOutputModeStatus: \$\("#fastOutputModeStatus"\)/, "sidebar fast-mode elements should be wired");
|
|
96
|
+
assert.match(sidebarOutputModeRefresh, /api\("\/api\/webui-output-mode", \{ scoped: false \}\)[\s\S]*?normalizeWebuiOutputModeMetadata\(response\.data\)/, "sidebar selector should load current server output-mode metadata");
|
|
97
|
+
assert.match(sidebarOutputModeApply, /method: "PUT"[\s\S]*?body: \{ outputModeDefault \}[\s\S]*?scoped: false[\s\S]*?await refreshSidebarOutputMode\(\)/, "sidebar selector should persist the selected mode and refresh effective metadata");
|
|
98
|
+
assert.match(sidebarOutputModeApply, /outputModeDefault === "compact-v1"[\s\S]*?Fast output mode enabled[\s\S]*?Normal output processing restored/, "sidebar apply feedback should distinguish enabling fast mode from restoring normal mode");
|
|
99
|
+
assert.match(sidebarOutputModeApply, /sidebarOutputModeDiagnostic = ""[\s\S]*?sidebarOutputModeNotice = `Failed to update fast mode:[\s\S]*?You can retry\.`[\s\S]*?sidebarOutputModeLoaded = true/, "a transient apply failure should remain visible without permanently disabling retry");
|
|
100
|
+
assert.match(app, /function renderSidebarOutputModeControl[\s\S]*?sidebarOutputModeNotice[\s\S]*?webuiOutputModeMetadataText\(sidebarOutputModeMetadata\)[\s\S]*?updateSidebarOutputModeApplyState\(\)/, "sidebar status should expose retry notices or persisted/effective/source metadata and apply state");
|
|
101
|
+
assert.match(styles, /\.toggle-control-hint\.warning\s*\{[\s\S]*?color: var\(--ctp-yellow\)/, "sidebar output-mode failures should use the warning palette");
|
|
102
|
+
assert.match(app, /fastOutputModeSelect\?\.addEventListener\("change", \(\) => \{[\s\S]*?sidebarOutputModeNotice = ""[\s\S]*?renderSidebarOutputModeControl\(\{ syncSelection: false \}\)[\s\S]*?setFastOutputModeButton\?\.addEventListener\("click", \(\) => applySidebarOutputMode\(\)/, "sidebar selection should clear transient failures and keep Apply retryable");
|
|
103
|
+
assert.match(app, /refreshSidebarOutputMode\(\)\.catch[\s\S]*?initializeTabs\(\)/, "sidebar output mode should initialize with the WebUI");
|
|
104
|
+
|
|
105
|
+
assert.match(helper, /FAST_OUTPUT_FLUSH_INTERVAL_MS = 100/, "the live scheduler should retain the exact 100 ms sustained-output bound");
|
|
106
|
+
assert.match(worker, /pi-webui-pwa-v35[\s\S]*?"\/fast-output-live\.mjs"/, "PWA cache identity and app shell should include the compact helper");
|
|
107
|
+
assert.match(html, /<script type="module" src="\/app\.js\?v=82"><\/script>/, "the PWA entry point should cache-bust browser wiring");
|
|
108
|
+
assert.match(JSON.parse(packageRaw).scripts.check, /node --check public\/fast-output-live\.mjs/, "package checks should parse the compact helper");
|
|
109
|
+
|
|
110
|
+
const events = createFastModeOutputEvents();
|
|
111
|
+
const deltas = events.filter((event) => event?.type === "message_update" && event.assistantMessageEvent?.type === "text_delta");
|
|
112
|
+
const normalScanChars = deltas.reduce((total, event) => total + JSON.stringify(event.message).length + JSON.stringify(event.assistantMessageEvent.partial).length, 0);
|
|
113
|
+
const compactScanChars = deltas.reduce((total, event) => total + event.assistantMessageEvent.delta.length, 0);
|
|
114
|
+
const scanRatio = normalScanChars / compactScanChars;
|
|
115
|
+
const normalFlushes = deltas.length;
|
|
116
|
+
const compactFlushes = Math.ceil(deltas.length / 5); // fixed 20 ms model: first + max one 100 ms flush
|
|
117
|
+
const ledger = { normalScanChars, compactScanChars, scanRatio: Number(scanRatio.toFixed(3)), normalFlushes, compactFlushes, normalDomWrites: normalFlushes, compactDomWrites: compactFlushes };
|
|
118
|
+
assert.ok(scanRatio >= 1.5, `compact browser scan ledger must improve by >= 1.5x: ${JSON.stringify(ledger)}`);
|
|
119
|
+
assert.ok(compactFlushes <= normalFlushes && ledger.compactDomWrites <= ledger.normalDomWrites, `compact modeled flush/DOM work must not increase: ${JSON.stringify(ledger)}`);
|
|
120
|
+
console.log(`fast-mode client ledger ${JSON.stringify(ledger)}`);
|
|
121
|
+
console.log("fast-mode-client-static.test.mjs passed");
|
|
@@ -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");
|