@firstpick/pi-package-webui 0.6.7 → 0.6.8

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.
@@ -0,0 +1,162 @@
1
+ import assert from "node:assert/strict";
2
+ import { spawn } from "node:child_process";
3
+ import { chmod, mkdtemp, readFile, 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
+ const port = 30000 + Math.floor(Math.random() * 20000);
14
+
15
+ async function request(pathname, { method = "GET", body, timeoutMs = 5_000 } = {}) {
16
+ const response = await fetch(`http://127.0.0.1:${port}${pathname}`, {
17
+ method,
18
+ headers: body === undefined ? undefined : { "content-type": "application/json" },
19
+ body: body === undefined ? undefined : JSON.stringify(body),
20
+ signal: AbortSignal.timeout(timeoutMs),
21
+ });
22
+ const payload = await response.json().catch(() => undefined);
23
+ return { status: response.status, body: payload };
24
+ }
25
+
26
+ async function waitFor(description, probe, { attempts = 80, intervalMs = 100 } = {}) {
27
+ let last;
28
+ for (let attempt = 0; attempt < attempts; attempt += 1) {
29
+ last = await probe();
30
+ if (last) return last;
31
+ await delay(intervalMs);
32
+ }
33
+ assert.fail(`${description} did not happen in time${last ? `; last=${JSON.stringify(last)}` : ""}`);
34
+ }
35
+
36
+ function isProcessRunning(pid) {
37
+ if (!Number.isInteger(pid) || pid <= 0) return false;
38
+ try {
39
+ process.kill(pid, 0);
40
+ return true;
41
+ } catch (error) {
42
+ return error?.code === "EPERM";
43
+ }
44
+ }
45
+
46
+ function killFixtureProcess(pid) {
47
+ if (!isProcessRunning(pid)) return;
48
+ try {
49
+ process.kill(pid, "SIGKILL");
50
+ } catch {
51
+ // Best-effort cleanup after a failed assertion.
52
+ }
53
+ }
54
+
55
+ const cwd = await mkdtemp(path.join(tmpdir(), "pi-webui-app-runner-tree-"));
56
+ const settingsFile = path.join(cwd, "webui-settings.json");
57
+ await chmod(fakePi, 0o755);
58
+ await writeFile(path.join(cwd, "tree-child.mjs"), "setInterval(() => {}, 1000);\n");
59
+ await writeFile(path.join(cwd, "tree-parent.mjs"), [
60
+ "import { spawn } from 'node:child_process';",
61
+ "import { writeFileSync } from 'node:fs';",
62
+ "import { fileURLToPath } from 'node:url';",
63
+ "const childPath = fileURLToPath(new URL('./tree-child.mjs', import.meta.url));",
64
+ "const child = spawn(process.execPath, [childPath], { stdio: 'ignore', windowsHide: true });",
65
+ "writeFileSync('tree-child.pid', `${child.pid}\\n`);",
66
+ "console.log(`tree runner ready ${child.pid}`);",
67
+ "setInterval(() => {}, 1000);",
68
+ "",
69
+ ].join("\n"));
70
+
71
+ const server = spawn(process.execPath, [serverScript, "--cwd", cwd, "--host", "127.0.0.1", "--port", String(port), "--pi", fakePi], {
72
+ stdio: ["ignore", "pipe", "pipe"],
73
+ env: {
74
+ ...process.env,
75
+ PI_WEBUI_SETTINGS_FILE: settingsFile,
76
+ PI_WEBUI_APP_RUNNER_PTY: "off",
77
+ },
78
+ windowsHide: true,
79
+ });
80
+ let serverOutput = "";
81
+ let runnerPid = 0;
82
+ let treeChildPid = 0;
83
+ server.stdout.on("data", (chunk) => { serverOutput += String(chunk); });
84
+ server.stderr.on("data", (chunk) => { serverOutput += String(chunk); });
85
+
86
+ try {
87
+ await waitFor("server health", async () => {
88
+ if (server.exitCode !== null) return false;
89
+ try {
90
+ const health = await request("/api/health", { timeoutMs: 1_000 });
91
+ return health.status === 200 && health.body?.ok === true ? health : false;
92
+ } catch {
93
+ return false;
94
+ }
95
+ }, { attempts: 100, intervalMs: 120 });
96
+
97
+ const tabsResponse = await request("/api/tabs");
98
+ const tabId = tabsResponse.body?.data?.tabs?.[0]?.id || tabsResponse.body?.tabs?.[0]?.id;
99
+ assert.ok(tabId, `startup tab should exist, output:\n${serverOutput}`);
100
+
101
+ const saved = await request("/api/app-runner-config", {
102
+ method: "POST",
103
+ body: { tab: tabId, runner: { label: "Process tree node", command: process.execPath, path: "tree-parent.mjs" } },
104
+ timeoutMs: 10_000,
105
+ });
106
+ assert.equal(saved.status, 200, `saving a process-tree runner should succeed: ${saved.body?.error || serverOutput}`);
107
+ const runner = saved.body?.data?.runners?.find((item) => item.custom === true && item.label === "Process tree node");
108
+ assert.ok(runner?.id, "process-tree custom runner should appear in detected app runners");
109
+
110
+ let state = await request("/api/app-runner", {
111
+ method: "POST",
112
+ body: { tab: tabId, runnerId: runner.id },
113
+ timeoutMs: 10_000,
114
+ });
115
+ assert.equal(state.status, 200, `process-tree runner should start: ${state.body?.error || serverOutput}`);
116
+ runnerPid = Number(state.body?.data?.activeRun?.pid) || 0;
117
+
118
+ await waitFor("runner parent and child startup", async () => {
119
+ state = await request(`/api/app-runners?tab=${encodeURIComponent(tabId)}`);
120
+ try {
121
+ treeChildPid = Number.parseInt((await readFile(path.join(cwd, "tree-child.pid"), "utf8")).trim(), 10);
122
+ } catch {
123
+ treeChildPid = 0;
124
+ }
125
+ const output = [
126
+ ...(state.body?.data?.activeRun?.lines || []),
127
+ state.body?.data?.activeRun?.pendingLine || "",
128
+ ].join("\n");
129
+ return isProcessRunning(treeChildPid) && /tree runner ready/.test(output) ? true : false;
130
+ });
131
+
132
+ const stopped = await request("/api/app-runner/stop", {
133
+ method: "POST",
134
+ body: { tab: tabId },
135
+ timeoutMs: 10_000,
136
+ });
137
+ assert.equal(stopped.status, 200, `process-tree stop should return ok: ${stopped.body?.error || serverOutput}`);
138
+ const stopOutput = (stopped.body?.data?.activeRun?.lines || []).join("\n");
139
+ if (process.platform === "win32") assert.match(stopOutput, /terminating Windows process tree/);
140
+ else assert.match(stopOutput, /sending Ctrl\+C/);
141
+
142
+ await waitFor("runner and descendant termination", async () => {
143
+ state = await request(`/api/app-runners?tab=${encodeURIComponent(tabId)}`);
144
+ const status = state.body?.data?.activeRun?.status;
145
+ return status && status !== "running" && !isProcessRunning(treeChildPid) ? true : false;
146
+ });
147
+ assert.equal(isProcessRunning(treeChildPid), false, "stopping an app runner must not orphan its server child");
148
+
149
+ await request("/api/shutdown", { method: "POST" }).catch(() => undefined);
150
+ for (let attempt = 0; attempt < 50 && server.exitCode === null; attempt += 1) await delay(100);
151
+ assert.notEqual(server.exitCode, null, "server should exit after /api/shutdown");
152
+ console.log("app-runner-process-tree-harness.test.mjs passed");
153
+ } finally {
154
+ if (server.exitCode === null) {
155
+ await request("/api/shutdown", { method: "POST", timeoutMs: 1_000 }).catch(() => undefined);
156
+ for (let attempt = 0; attempt < 20 && server.exitCode === null; attempt += 1) await delay(100);
157
+ if (server.exitCode === null) server.kill("SIGKILL");
158
+ }
159
+ killFixtureProcess(runnerPid);
160
+ killFixtureProcess(treeChildPid);
161
+ await rm(cwd, { recursive: true, force: true });
162
+ }
@@ -0,0 +1,65 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import { CODEX_TOKEN_REFRESH_SKEW_MS, resolveCodexUsageAuth } from "../lib/codex-usage-auth.mjs";
4
+
5
+ function fakeRuntime(initial, refresh) {
6
+ let credential = structuredClone(initial);
7
+ let tail = Promise.resolve();
8
+ const credentials = {
9
+ async read() { return structuredClone(credential); },
10
+ modify(_providerId, update) {
11
+ const operation = tail.then(async () => {
12
+ const next = await update(structuredClone(credential));
13
+ if (next !== undefined) credential = structuredClone(next);
14
+ return structuredClone(credential);
15
+ });
16
+ tail = operation.then(() => undefined, () => undefined);
17
+ return operation;
18
+ },
19
+ };
20
+ return {
21
+ credentials,
22
+ getProvider() { return { auth: { oauth: { refresh } } }; },
23
+ async getAuth() { throw new Error("OAuth tests must not use ordinary auth resolution"); },
24
+ };
25
+ }
26
+
27
+ const NOW = 2_000_000_000_000;
28
+ const oauth = (access, expires) => ({ type: "oauth", access, refresh: "fake-refresh", expires, accountId: "acct_test" });
29
+
30
+ test("a 401 forces refresh of an otherwise unexpired Codex credential", async () => {
31
+ let refreshCalls = 0;
32
+ const runtime = fakeRuntime(oauth("rejected", NOW + 60 * 60 * 1000), async (current) => {
33
+ refreshCalls += 1;
34
+ return { ...current, access: "replacement", expires: NOW + 2 * 60 * 60 * 1000 };
35
+ });
36
+ const result = await resolveCodexUsageAuth(runtime, "openai-codex", { forceRefresh: true, now: NOW });
37
+ assert.equal(refreshCalls, 1);
38
+ assert.equal(result.accessToken, "replacement");
39
+ assert.equal(result.refreshed, true);
40
+ });
41
+
42
+ test("Codex OAuth refresh uses the five-minute proactive skew", async () => {
43
+ let refreshCalls = 0;
44
+ const nearExpiry = fakeRuntime(oauth("near", NOW + CODEX_TOKEN_REFRESH_SKEW_MS - 1), async (current) => {
45
+ refreshCalls += 1;
46
+ return { ...current, access: "near-refreshed", expires: NOW + 60 * 60 * 1000 };
47
+ });
48
+ assert.equal((await resolveCodexUsageAuth(nearExpiry, "openai-codex", { now: NOW })).accessToken, "near-refreshed");
49
+ assert.equal(refreshCalls, 1);
50
+
51
+ const farExpiry = fakeRuntime(oauth("far", NOW + CODEX_TOKEN_REFRESH_SKEW_MS + 1), async () => {
52
+ refreshCalls += 1;
53
+ throw new Error("must not refresh");
54
+ });
55
+ assert.equal((await resolveCodexUsageAuth(farExpiry, "openai-codex", { now: NOW })).accessToken, "far");
56
+ assert.equal(refreshCalls, 1);
57
+ });
58
+
59
+ test("forced refresh never returns the same rejected credential", async () => {
60
+ const runtime = fakeRuntime(oauth("rejected", NOW + 60 * 60 * 1000), async (current) => ({ ...current }));
61
+ await assert.rejects(
62
+ resolveCodexUsageAuth(runtime, "openai-codex", { forceRefresh: true, now: NOW }),
63
+ /rejected credential/,
64
+ );
65
+ });
@@ -26,6 +26,16 @@ let activeBash = 0;
26
26
  let peakBash = 0;
27
27
  let thinkingLevel = "off";
28
28
  let conversationEnabled = false;
29
+ const fakeTools = [
30
+ { name: "read", description: "Read files", sourceInfo: { source: "builtin", scope: "temporary", origin: "top-level" } },
31
+ { name: "bash", description: "Run shell commands", sourceInfo: { source: "builtin", scope: "temporary", origin: "top-level" } },
32
+ ];
33
+ const fakeSkills = [
34
+ { name: "repo-explorer", description: "Explore repositories" },
35
+ { name: "code-security", description: "Review code security" },
36
+ ];
37
+ let enabledToolNames = new Set(fakeTools.map((tool) => tool.name));
38
+ let enabledSkillNames = new Set(fakeSkills.map((skill) => skill.name));
29
39
 
30
40
  const voiceScriptsEnabled = process.env.FAKE_PI_VOICE_SCRIPTS === "1";
31
41
  const commandLogFile = process.env.FAKE_PI_LOG_FILE || "";
@@ -202,11 +212,29 @@ function handleWebuiHelperPrompt(command, base) {
202
212
  respond({ ...base, data: { output: "webui-helper handled" } });
203
213
  switch (request.action) {
204
214
  case "tools-state":
205
- respondHelper({ requestId, ok: true, data: { tools: [], activeTools: [] } });
215
+ respondHelper({ requestId, ok: true, data: { tools: fakeTools.map((tool) => ({ ...tool, enabled: enabledToolNames.has(tool.name) })) } });
216
+ return true;
217
+ case "tools-set": {
218
+ if (Array.isArray(request.payload?.enabledTools)) enabledToolNames = new Set(request.payload.enabledTools.map(String));
219
+ else if (Array.isArray(request.payload?.disabledTools)) {
220
+ const disabled = new Set(request.payload.disabledTools.map(String));
221
+ enabledToolNames = new Set(fakeTools.map((tool) => tool.name).filter((name) => !disabled.has(name)));
222
+ }
223
+ respondHelper({ requestId, ok: true, data: { tools: fakeTools.map((tool) => ({ ...tool, enabled: enabledToolNames.has(tool.name) })) } });
206
224
  return true;
225
+ }
207
226
  case "skills-state":
208
- respondHelper({ requestId, ok: true, data: { skills: [] } });
227
+ respondHelper({ requestId, ok: true, data: { skills: fakeSkills.map((skill) => ({ ...skill, enabled: enabledSkillNames.has(skill.name) })) } });
228
+ return true;
229
+ case "skills-set": {
230
+ if (Array.isArray(request.payload?.enabledSkills)) enabledSkillNames = new Set(request.payload.enabledSkills.map(String));
231
+ else if (Array.isArray(request.payload?.disabledSkills)) {
232
+ const disabled = new Set(request.payload.disabledSkills.map(String));
233
+ enabledSkillNames = new Set(fakeSkills.map((skill) => skill.name).filter((name) => !disabled.has(name)));
234
+ }
235
+ respondHelper({ requestId, ok: true, data: { skills: fakeSkills.map((skill) => ({ ...skill, enabled: enabledSkillNames.has(skill.name) })) } });
209
236
  return true;
237
+ }
210
238
  case "subagent-output":
211
239
  respondHelper({
212
240
  requestId,
@@ -276,6 +304,34 @@ function handleSubagentFixturePrompt(command, base) {
276
304
  return true;
277
305
  }
278
306
 
307
+ function handleWorkflowFixturePrompt(command, base) {
308
+ const message = String(command.message || "").trim();
309
+ if (!/^fixture workflow inspector (running|completed|clear)$/.test(message)) return false;
310
+ const status = message.split(" ").at(-1);
311
+ const now = new Date().toISOString();
312
+ const runs = status === "clear" ? [] : [{
313
+ runId: "fixture-workflow-run",
314
+ workflowKey: "fixture-workflow",
315
+ workflowName: "Fixture Workflow",
316
+ status,
317
+ sourceType: "javascript",
318
+ input: { topic: "rpc" },
319
+ script: "export const meta = { name: 'fixture-workflow', description: 'Fixture Workflow' }\nreturn 1",
320
+ startedAt: now,
321
+ updatedAt: now,
322
+ ...(status === "completed" ? { finishedAt: now, result: "fixture complete" } : {}),
323
+ phases: [{
324
+ phaseId: "audit", name: "Audit", status,
325
+ agents: [{ callId: "fixture-call", callIndex: 1, taskId: "inspect", label: "inspect", name: "Inspect", status, prompt: "Inspect fixture", options: { tools: ["read"] }, recentEvents: [{ type: "stdout", timestamp: now, line: "read fixture" }], ...(status === "completed" ? { result: "inspected", usage: { input: 2, output: 1 } } : {}) }],
326
+ }],
327
+ controls: { canPause: status === "running", canResume: status === "completed", canAbort: status === "running", canRetry: status === "completed", canSave: status === "completed" },
328
+ }];
329
+ const payload = { type: "firstpick.pi-extension-workflows.inspector", version: 1, updatedAt: now, mode: { enabled: true, behavior: "persistent", phase: "armed" }, runs };
330
+ respond({ ...base, data: { output: `fake workflow inspector ${status} emitted` } });
331
+ emitEvent({ type: "extension_ui_request", id: randomUUID(), method: "setWidget", widgetKey: "workflow:rpc", widgetLines: [`WORKFLOW_RPC_PAYLOAD ${JSON.stringify(payload)}`] });
332
+ return true;
333
+ }
334
+
279
335
  function handleTalkPrompt(command, base) {
280
336
  const message = String(command.message || "").trim();
281
337
  const match = message.match(/^\/(talk|voice|conversation)(?:\s+(\S+))?/i);
@@ -355,6 +411,7 @@ rl.on("line", (line) => {
355
411
  { name: "talk", source: "extension", description: "Toggle Natural Conversation Mode" },
356
412
  { name: "voice", source: "extension", description: "Natural Conversation Mode alias" },
357
413
  { name: "conversation", source: "extension", description: "Natural Conversation Mode alias" },
414
+ { name: "workflow", source: "extension", description: "Run and inspect JavaScript workflows" },
358
415
  ],
359
416
  },
360
417
  });
@@ -380,6 +437,7 @@ rl.on("line", (line) => {
380
437
  if (handleWebuiHelperPrompt(command, base)) return;
381
438
  if (handleSubagentFixturePrompt(command, base)) return;
382
439
  if (handleDocumentArtifactFixturePrompt(command, base)) return;
440
+ if (handleWorkflowFixturePrompt(command, base)) return;
383
441
  if (handleTalkPrompt(command, base)) return;
384
442
  if (handleVoiceScriptPrompt(command, base)) return;
385
443
  respond({ ...base, data: { output: "fake prompt accepted" } });
@@ -0,0 +1,42 @@
1
+ import assert from "node:assert/strict";
2
+ import {
3
+ classifyGitPathFailure,
4
+ classifyWindowsReservedGitPath,
5
+ findWindowsReservedGitPath,
6
+ windowsReservedGitPathFailure,
7
+ } from "../lib/git-command-errors.mjs";
8
+
9
+ assert.deepEqual(classifyWindowsReservedGitPath("NUL"), {
10
+ path: "NUL",
11
+ component: "NUL",
12
+ deviceName: "NUL",
13
+ });
14
+ assert.deepEqual(classifyWindowsReservedGitPath("nested/aux.txt"), {
15
+ path: "nested/aux.txt",
16
+ component: "aux.txt",
17
+ deviceName: "AUX",
18
+ });
19
+ assert.equal(classifyWindowsReservedGitPath("frontend/null-state.ts"), null);
20
+ assert.equal(classifyWindowsReservedGitPath("COM10.log"), null);
21
+ assert.equal(findWindowsReservedGitPath(["normal.txt", "nested/LPT1.log", "later.txt"])?.path, "nested/LPT1.log");
22
+ assert.equal(findWindowsReservedGitPath("normal.txt\0folder/PRN\0")?.path, "folder/PRN");
23
+
24
+ const exactFailure = classifyGitPathFailure({
25
+ exitCode: 128,
26
+ stderr: [
27
+ "error: short read while indexing NUL",
28
+ "error: NUL: failed to insert into database",
29
+ "error: unable to index file 'NUL'",
30
+ "fatal: adding files failed",
31
+ ].join("\n"),
32
+ });
33
+ assert.equal(exactFailure?.code, "INVALID_WORKTREE_PATH");
34
+ assert.equal(exactFailure?.error, 'Git cannot index the Windows-reserved path "NUL".');
35
+ assert.match(exactFailure?.hint || "", /Delete or rename "NUL"/);
36
+ assert.match(exactFailure?.hint || "", /earlier failed git add may already have staged files/);
37
+
38
+ assert.equal(classifyGitPathFailure({ exitCode: 128, stderr: "fatal: not a git repository" }), null);
39
+ assert.equal(classifyGitPathFailure({ exitCode: 1, stderr: "error: unable to index file 'ordinary.txt'" }), null);
40
+ assert.equal(windowsReservedGitPathFailure("ordinary.txt"), null);
41
+
42
+ console.log("git command error tests passed");
@@ -10,6 +10,7 @@ import {
10
10
  readWebuiSettings,
11
11
  supportedGitWorkflowThinkingLevels,
12
12
  writeGitWorkflowPreferences,
13
+ writeWebuiSettings,
13
14
  } from "../lib/git-workflow-preferences.mjs";
14
15
 
15
16
  assert.deepEqual(supportedGitWorkflowThinkingLevels({ reasoning: false }), ["off"]);
@@ -30,9 +31,11 @@ const settingsFile = path.join(root, "settings.json");
30
31
  try {
31
32
  await writeFile(settingsFile, `${JSON.stringify({ version: 1, remoteAuthEnabled: true }, null, 2)}\n`, "utf8");
32
33
  const migrated = await readWebuiSettings(settingsFile);
33
- assert.equal(migrated.version, 2);
34
+ assert.equal(migrated.version, 3);
34
35
  assert.equal(migrated.remoteAuthEnabled, true, "legacy Remote PIN state should survive schema migration");
35
36
  assert.equal(isGitWorkflowSetupComplete(migrated.gitWorkflow), false);
37
+ assert.equal(migrated.resourceDefaults.tools.enabledTools, null, "legacy settings should inherit Pi's normal tool defaults");
38
+ assert.equal(migrated.resourceDefaults.skills.enabledSkills, null, "legacy settings should inherit Pi's normal skill defaults");
36
39
  assert.equal(migrated.gitWorkflow.stagingPolicy, "review");
37
40
  assert.equal(migrated.gitWorkflow.generation.thinkingLevel, "low");
38
41
 
@@ -49,15 +52,24 @@ try {
49
52
  assert.equal(saved.commit.defaultVariant, "long");
50
53
  assert.equal(saved.stagingPolicy, "preserve");
51
54
 
55
+ await writeWebuiSettings({
56
+ resourceDefaults: {
57
+ tools: { enabledTools: ["read", " write ", "read", ""] },
58
+ skills: { enabledSkills: ["repo-explorer", "code-security"] },
59
+ },
60
+ }, settingsFile);
61
+
52
62
  const partiallyUpdated = await writeGitWorkflowPreferences({ deliveryMode: "current" }, settingsFile);
53
63
  assert.equal(partiallyUpdated.generation.modelId, "fake-model", "partial updates should preserve the selected model");
54
64
  assert.equal(partiallyUpdated.commit.language, "de", "partial updates should preserve nested commit preferences");
55
65
  assert.equal(partiallyUpdated.deliveryMode, "current");
56
66
 
57
67
  const persisted = JSON.parse(await readFile(settingsFile, "utf8"));
58
- assert.equal(persisted.version, 2);
68
+ assert.equal(persisted.version, 3);
59
69
  assert.equal(persisted.remoteAuthEnabled, true);
60
70
  assert.equal(persisted.gitWorkflow.generation.provider, "fake");
71
+ assert.deepEqual(persisted.resourceDefaults.tools.enabledTools, ["read", "write"], "global tool defaults should be normalized and deduplicated");
72
+ assert.deepEqual(persisted.resourceDefaults.skills.enabledSkills, ["repo-explorer", "code-security"], "global skill defaults should persist beside other Web UI settings");
61
73
  assert.match(gitWorkflowPreferencesSummary(await readGitWorkflowPreferences(settingsFile)), /fake\/fake-model/);
62
74
  if (process.platform !== "win32") assert.equal((await stat(settingsFile)).mode & 0o777, 0o600);
63
75
 
@@ -38,6 +38,42 @@ async function request(host, pathname, { method = "GET", body, timeoutMs = 5_000
38
38
  return { status: response.status, body: payload };
39
39
  }
40
40
 
41
+ async function waitForSseEvent(tabId, predicate, trigger) {
42
+ const controller = new AbortController();
43
+ const timeout = setTimeout(() => controller.abort(new Error("timed out waiting for SSE event")), 8_000);
44
+ let triggerResult;
45
+ try {
46
+ const response = await fetch(`http://127.0.0.1:${port}/api/events?tab=${encodeURIComponent(tabId)}`, { signal: controller.signal });
47
+ assert.equal(response.status, 200, "SSE connection should open");
48
+ const triggerPromise = trigger ? Promise.resolve().then(trigger) : Promise.resolve(undefined);
49
+ const reader = response.body.getReader();
50
+ const decoder = new TextDecoder();
51
+ let buffer = "";
52
+ while (true) {
53
+ const { done, value } = await reader.read();
54
+ if (done) break;
55
+ buffer += decoder.decode(value, { stream: true });
56
+ let boundary;
57
+ while ((boundary = buffer.indexOf("\n\n")) >= 0) {
58
+ const block = buffer.slice(0, boundary);
59
+ buffer = buffer.slice(boundary + 2);
60
+ const data = block.split("\n").filter((line) => line.startsWith("data:")).map((line) => line.slice(5).trim()).join("\n");
61
+ if (!data) continue;
62
+ const event = JSON.parse(data);
63
+ if (predicate(event)) {
64
+ triggerResult = await triggerPromise;
65
+ controller.abort();
66
+ return { event, triggerResult };
67
+ }
68
+ }
69
+ }
70
+ throw new Error("SSE stream ended before the expected event");
71
+ } finally {
72
+ clearTimeout(timeout);
73
+ controller.abort();
74
+ }
75
+ }
76
+
41
77
  async function rmWithRetry(target) {
42
78
  let lastError;
43
79
  for (let attempt = 0; attempt < 8; attempt++) {
@@ -77,6 +113,7 @@ const cwd = await mkdtemp(path.join(tmpdir(), "pi-webui-http-harness-"));
77
113
  const harnessSideEffectsRoot = await mkdtemp(path.join(tmpdir(), "pi-webui-http-harness-side-effects-"));
78
114
  const settingsFile = path.join(harnessSideEffectsRoot, "webui-settings.json");
79
115
  const openCommandLog = path.join(harnessSideEffectsRoot, "open-default.log");
116
+ const fakePiCommandLog = path.join(harnessSideEffectsRoot, "fake-pi-commands.jsonl");
80
117
  const openCommandScript = path.join(harnessSideEffectsRoot, "fake-open-default.mjs");
81
118
  const fakeOpenBinDir = path.join(harnessSideEffectsRoot, "bin");
82
119
  const artifactRoot = path.join(harnessSideEffectsRoot, "artifacts"), artifactDir = path.join(artifactRoot, "fixture-document-artifact"), artifactManifest = path.join(artifactDir, "manifest.json"), artifactDownload = path.join(artifactDir, "document.docx"), artifactPage = path.join(artifactDir, "page-1.png"), artifactExpiresAt = new Date(Date.now() + 60 * 60 * 1000).toISOString();
@@ -131,6 +168,7 @@ const child = spawn(process.execPath, [serverScript, "--cwd", cwd, "--host", "0.
131
168
  PI_WEBUI_ARTIFACT_ROOTS: artifactRoot,
132
169
  FAKE_PI_ARTIFACT_MANIFEST: artifactManifest,
133
170
  FAKE_PI_ARTIFACT_DOWNLOAD: artifactDownload,
171
+ FAKE_PI_LOG_FILE: fakePiCommandLog,
134
172
  FAKE_PI_VOICE_SCRIPTS: "1",
135
173
  PI_VOICE_STT_URL: `http://127.0.0.1:${voiceProviderPort}/stt`,
136
174
  PI_VOICE_TTS_URL: `http://127.0.0.1:${voiceProviderPort}/tts`,
@@ -225,6 +263,82 @@ try {
225
263
  const tabId = tabList[0].id;
226
264
  assert.ok(tabId, "tab should have an id");
227
265
 
266
+ const sessionToolsBefore = await request("127.0.0.1", `/api/tools?tab=${encodeURIComponent(tabId)}&scope=session`);
267
+ assert.equal(sessionToolsBefore.status, 200);
268
+ assert.equal(sessionToolsBefore.body?.data?.scope, "session");
269
+ assert.deepEqual(sessionToolsBefore.body?.data?.tools?.map((tool) => [tool.name, tool.enabled]), [["read", true], ["bash", true]]);
270
+
271
+ const globalToolsBefore = await request("127.0.0.1", `/api/tools?tab=${encodeURIComponent(tabId)}&scope=global`);
272
+ assert.equal(globalToolsBefore.status, 200);
273
+ assert.equal(globalToolsBefore.body?.data?.configured, false, "global tools should initially inherit the current runtime defaults");
274
+
275
+ const saveGlobalTools = await request("127.0.0.1", "/api/tools", {
276
+ method: "POST",
277
+ body: { tab: tabId, scope: "global", enabledTools: ["read"] },
278
+ });
279
+ assert.equal(saveGlobalTools.status, 200);
280
+ assert.equal(saveGlobalTools.body?.data?.configured, true);
281
+ assert.deepEqual(saveGlobalTools.body?.data?.tools?.map((tool) => [tool.name, tool.enabled]), [["read", true], ["bash", false]]);
282
+
283
+ const settingsWithUnavailableResources = JSON.parse(await readFile(settingsFile, "utf8"));
284
+ settingsWithUnavailableResources.resourceDefaults.tools.enabledTools.push("future-tool");
285
+ settingsWithUnavailableResources.resourceDefaults.skills.enabledSkills = ["future-skill"];
286
+ await writeFile(settingsFile, `${JSON.stringify(settingsWithUnavailableResources, null, 2)}\n`, "utf8");
287
+
288
+ const sessionToolsAfterGlobal = await request("127.0.0.1", `/api/tools?tab=${encodeURIComponent(tabId)}&scope=session`);
289
+ assert.deepEqual(sessionToolsAfterGlobal.body?.data?.tools?.map((tool) => [tool.name, tool.enabled]), [["read", true], ["bash", true]], "saving a global tool default must not rewrite the current session");
290
+
291
+ const saveSessionTools = await request("127.0.0.1", "/api/tools", {
292
+ method: "POST",
293
+ body: { tab: tabId, scope: "session", enabledTools: ["bash"] },
294
+ });
295
+ assert.equal(saveSessionTools.status, 200);
296
+ assert.deepEqual(saveSessionTools.body?.data?.tools?.map((tool) => [tool.name, tool.enabled]), [["read", false], ["bash", true]]);
297
+ const globalToolsAfterSession = await request("127.0.0.1", `/api/tools?tab=${encodeURIComponent(tabId)}&scope=global`);
298
+ assert.deepEqual(globalToolsAfterSession.body?.data?.tools?.map((tool) => [tool.name, tool.enabled]), [["read", true], ["bash", false]], "session tool changes must not rewrite the global default");
299
+
300
+ const saveGlobalSkills = await request("127.0.0.1", "/api/skills", {
301
+ method: "POST",
302
+ body: { tab: tabId, scope: "global", enabledSkills: ["repo-explorer"] },
303
+ });
304
+ assert.equal(saveGlobalSkills.status, 200);
305
+ assert.deepEqual(saveGlobalSkills.body?.data?.skills?.map((skill) => [skill.name, skill.enabled]), [["repo-explorer", true], ["code-security", false]]);
306
+ const sessionSkillsAfterGlobal = await request("127.0.0.1", `/api/skills?tab=${encodeURIComponent(tabId)}&scope=session`);
307
+ assert.deepEqual(sessionSkillsAfterGlobal.body?.data?.skills?.map((skill) => [skill.name, skill.enabled]), [["repo-explorer", true], ["code-security", true]], "saving a global skill default must not rewrite the current session");
308
+
309
+ const persistedResourceDefaults = JSON.parse(await readFile(settingsFile, "utf8"));
310
+ assert.deepEqual(persistedResourceDefaults.resourceDefaults?.tools?.enabledTools, ["read", "future-tool"], "saving visible tool choices should preserve defaults for tools unavailable in the active tab");
311
+ assert.deepEqual(persistedResourceDefaults.resourceDefaults?.skills?.enabledSkills, ["repo-explorer", "future-skill"], "saving visible skill choices should preserve defaults for skills unavailable in the active tab");
312
+ const invalidResourceScope = await request("127.0.0.1", `/api/tools?tab=${encodeURIComponent(tabId)}&scope=project`);
313
+ assert.equal(invalidResourceScope.status, 400, "resource selectors should reject unsupported scope values");
314
+
315
+ const workflowRpc = await waitForSseEvent(
316
+ tabId,
317
+ (event) => event.type === "extension_ui_request" && event.method === "setWidget" && event.widgetKey === "workflow:rpc",
318
+ () => request("127.0.0.1", "/api/prompt", { method: "POST", body: { tab: tabId, message: "fixture workflow inspector running" } }),
319
+ );
320
+ assert.equal(workflowRpc.triggerResult.status, 200, "workflow RPC fixture prompt should be accepted");
321
+ assert.equal(workflowRpc.event.widgetLines?.[0]?.startsWith("WORKFLOW_RPC_PAYLOAD "), true, "real Pi RPC events should transport the versioned Workflow inspector payload");
322
+ const workflowPayload = JSON.parse(workflowRpc.event.widgetLines[0].slice("WORKFLOW_RPC_PAYLOAD ".length));
323
+ assert.equal(workflowPayload.version, 1);
324
+ assert.equal(workflowPayload.runs[0].status, "running");
325
+ assert.equal(workflowPayload.runs[0].phases[0].agents[0].prompt, "Inspect fixture");
326
+
327
+ const workflowReplay = await waitForSseEvent(
328
+ tabId,
329
+ (event) => event.type === "extension_ui_request" && event.method === "setWidget" && event.widgetKey === "workflow:rpc",
330
+ );
331
+ assert.equal(workflowReplay.event.replayed, true, "server reconnect should replay the latest Workflow inspector widget");
332
+ assert.equal(JSON.parse(workflowReplay.event.widgetLines[0].slice("WORKFLOW_RPC_PAYLOAD ".length)).runs[0].runId, "fixture-workflow-run");
333
+
334
+ const workflowCompleted = await waitForSseEvent(
335
+ tabId,
336
+ (event) => event.type === "extension_ui_request" && event.method === "setWidget" && event.widgetKey === "workflow:rpc" && event.widgetLines?.[0]?.includes('"status":"completed"'),
337
+ () => request("127.0.0.1", "/api/prompt", { method: "POST", body: { tab: tabId, message: "fixture workflow inspector completed" } }),
338
+ );
339
+ assert.equal(workflowCompleted.triggerResult.status, 200);
340
+ assert.equal(JSON.parse(workflowCompleted.event.widgetLines[0].slice("WORKFLOW_RPC_PAYLOAD ".length)).runs[0].controls.canRetry, true);
341
+
228
342
  const artifactFixture = await request("127.0.0.1", "/api/prompt", { method: "POST", body: { tab: tabId, message: "fixture document artifact" } });
229
343
  assert.equal(artifactFixture.status, 200, "document artifact fixture should be accepted");
230
344
  const artifactMessages = await request("127.0.0.1", `/api/messages?tab=${encodeURIComponent(tabId)}`);
@@ -541,6 +655,25 @@ try {
541
655
  assert.equal(gitRemote.body?.ok, true, "remote endpoint should add origin without pushing");
542
656
  assert.equal(gitRemote.body?.data?.remoteUrl, "https://github.com/Firstp1ck/pi-webui-http-harness.git");
543
657
 
658
+ if (process.platform === "win32") {
659
+ const ordinaryPath = path.join(cwd, "preflight-should-not-stage.txt");
660
+ const reservedPath = path.toNamespacedPath(path.join(cwd, "NUL"));
661
+ await writeFile(ordinaryPath, "ordinary untracked file\n");
662
+ await writeFile(reservedPath, "accidental device-name file\n");
663
+ try {
664
+ const reservedAdd = await request("127.0.0.1", "/api/git-workflow/add", { method: "POST", body: { tab: tabId } });
665
+ assert.equal(reservedAdd.status, 200);
666
+ assert.equal(reservedAdd.body?.ok, false, "git add endpoint should reject Windows-reserved paths before staging");
667
+ assert.equal(reservedAdd.body?.code, "INVALID_WORKTREE_PATH");
668
+ assert.match(String(reservedAdd.body?.error || ""), /Windows-reserved path "NUL"/);
669
+ assert.match(String(reservedAdd.body?.hint || ""), /Delete or rename "NUL"/);
670
+ assert.equal(runGitFixture(["diff", "--cached", "--name-only"], cwd, "reserved-path preflight should leave the index untouched"), "");
671
+ } finally {
672
+ await rm(reservedPath, { force: true });
673
+ await rm(ordinaryPath, { force: true });
674
+ }
675
+ }
676
+
544
677
  await writeFile(path.join(cwd, "single.txt"), "created\n");
545
678
  const gitAddCreated = await request("127.0.0.1", "/api/git-workflow/add", { method: "POST", body: { tab: tabId } });
546
679
  assert.equal(gitAddCreated.status, 200);
@@ -589,6 +722,7 @@ try {
589
722
  const dir = path.join(gitFixturesRoot, name);
590
723
  await mkdir(dir, { recursive: true });
591
724
  runGitFixture(["init", "-b", "main", dir], gitFixturesRoot, `${name} fixture should initialize`);
725
+ runGitFixture(["config", "core.autocrlf", "false"], dir, `${name} fixture should keep line endings deterministic`);
592
726
  runGitFixture(["config", "user.name", "Pi WebUI Test"], dir, `${name} fixture should set user name`);
593
727
  runGitFixture(["config", "user.email", "pi-webui-test@example.invalid"], dir, `${name} fixture should set user email`);
594
728
  await writeFile(path.join(dir, "file.txt"), "base\n");
@@ -682,6 +816,20 @@ try {
682
816
  assert.equal(operationSnapshot.body?.data?.conflicts?.[0]?.status, "UU");
683
817
  assert.equal(operationSnapshot.body?.data?.conflicts?.[0]?.preview?.hasMarkers, true, "conflict preview should detect conflict markers");
684
818
 
819
+ const conflictAgent = await request("127.0.0.1", "/api/git-operation/resolve-with-agent", { method: "POST", body: { tab: mergeTab }, timeoutMs: 20_000 });
820
+ assert.equal(conflictAgent.status, 200);
821
+ assert.equal(conflictAgent.body?.ok, true, `conflict handoff should open an agent tab: ${conflictAgent.body?.error || ""}`);
822
+ assert.notEqual(conflictAgent.body?.data?.tab?.id, mergeTab, "conflict handoff should create a separate tab");
823
+ assert.equal(conflictAgent.body?.data?.tab?.cwd, mergeRepo, "conflict agent should use the conflicted repository root");
824
+ assert.equal(conflictAgent.body?.data?.tab?.title, "Resolve merge conflicts");
825
+ assert.deepEqual(conflictAgent.body?.data?.operation?.conflicts, [{ path: "file.txt", status: "UU" }]);
826
+ const loggedCommands = (await readFile(fakePiCommandLog, "utf8")).trim().split(/\r?\n/).filter(Boolean).map((line) => JSON.parse(line));
827
+ const handoffPrompt = loggedCommands.findLast((entry) => entry.direction === "command" && entry.type === "prompt" && /Resolve the current Git merge conflicts/.test(entry.message || ""));
828
+ assert.ok(handoffPrompt, "conflict agent should receive a resolution prompt");
829
+ assert.match(handoffPrompt.message, /Conflicted files:\n- UU "file\.txt"/, "handoff prompt should identify each conflicted path and status");
830
+ assert.match(handoffPrompt.message, /Do not continue, skip, abort, commit, reset, or push the merge/, "handoff prompt should keep operation completion under user control");
831
+ assert.match(handoffPrompt.message, /git diff --name-only --diff-filter=U is empty/, "handoff prompt should require unmerged-path verification");
832
+
685
833
  const continueBlocked = await request("127.0.0.1", "/api/git-operation/continue", { method: "POST", body: { tab: mergeTab } });
686
834
  assert.equal(continueBlocked.status, 200);
687
835
  assert.equal(continueBlocked.body?.ok, false, "continue with unmerged paths must fail");