@firstpick/pi-package-webui 0.6.6 → 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.
@@ -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,8 +113,14 @@ 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");
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();
120
+ await mkdir(artifactDir, { recursive: true });
121
+ await writeFile(artifactDownload, Buffer.from("fixture docx download bytes"));
122
+ await writeFile(artifactPage, Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]));
123
+ await writeFile(artifactManifest, JSON.stringify({ artifact: { schema: "pi.artifact/v1", kind: "document", id: "fixture-document-artifact", revisionId: "fixture-revision", title: "fixture.docx", mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document", pageCount: 1, manifestPath: artifactManifest, downloadPath: artifactDownload, expiresAt: artifactExpiresAt }, sourcePath: "/private/source.docx", sourceSha256: "a".repeat(64), renderer: { engine: "fixture" }, pages: [{ pageNum: 1, width: 10, height: 20, outputPath: artifactPage }], warnings: [] }));
82
124
  await chmod(fakePi, 0o755);
83
125
  await mkdir(fakeOpenBinDir, { recursive: true });
84
126
  await writeFile(openCommandScript, `#!/usr/bin/env node\nimport { appendFile } from "node:fs/promises";\nawait appendFile(process.env.PI_WEBUI_OPEN_LOG, "custom-open\\t" + process.argv.slice(2).join("\\t") + "\\n", "utf8");\n`, "utf8");
@@ -123,6 +165,10 @@ const child = spawn(process.execPath, [serverScript, "--cwd", cwd, "--host", "0.
123
165
  PI_WEBUI_SETTINGS_FILE: settingsFile,
124
166
  ...(process.platform === "linux" ? {} : { PI_WEBUI_OPEN_COMMAND: openCommandScript }),
125
167
  PI_WEBUI_OPEN_LOG: openCommandLog,
168
+ PI_WEBUI_ARTIFACT_ROOTS: artifactRoot,
169
+ FAKE_PI_ARTIFACT_MANIFEST: artifactManifest,
170
+ FAKE_PI_ARTIFACT_DOWNLOAD: artifactDownload,
171
+ FAKE_PI_LOG_FILE: fakePiCommandLog,
126
172
  FAKE_PI_VOICE_SCRIPTS: "1",
127
173
  PI_VOICE_STT_URL: `http://127.0.0.1:${voiceProviderPort}/stt`,
128
174
  PI_VOICE_TTS_URL: `http://127.0.0.1:${voiceProviderPort}/tts`,
@@ -217,6 +263,108 @@ try {
217
263
  const tabId = tabList[0].id;
218
264
  assert.ok(tabId, "tab should have an id");
219
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
+
342
+ const artifactFixture = await request("127.0.0.1", "/api/prompt", { method: "POST", body: { tab: tabId, message: "fixture document artifact" } });
343
+ assert.equal(artifactFixture.status, 200, "document artifact fixture should be accepted");
344
+ const artifactMessages = await request("127.0.0.1", `/api/messages?tab=${encodeURIComponent(tabId)}`);
345
+ const artifactToolResult = artifactMessages.body?.data?.messages?.findLast?.((message) => message?.role === "toolResult" && message?.toolName === "docx_render");
346
+ const publicArtifact = artifactToolResult?.details?.artifact;
347
+ assert.equal(publicArtifact?.schema, "pi.artifact/v1", "document artifact should survive transcript sanitization");
348
+ assert.ok(publicArtifact?.manifestUrl, "document artifact should receive a manifest URL");
349
+ assert.ok(publicArtifact?.downloadUrl, "document artifact should receive a download URL");
350
+ assert.equal(JSON.stringify(artifactToolResult).includes(harnessSideEffectsRoot), false, "browser transcript must not expose artifact host paths");
351
+ const artifactManifestResponse = await fetch(`http://127.0.0.1:${port}${publicArtifact.manifestUrl}`, { signal: AbortSignal.timeout(5_000) });
352
+ assert.equal(artifactManifestResponse.status, 200, "artifact manifest token should resolve for its tab");
353
+ const artifactManifestPayload = await artifactManifestResponse.json();
354
+ assert.equal(artifactManifestPayload.data.pages[0].pageNum, 1);
355
+ assert.equal(JSON.stringify(artifactManifestPayload).includes(harnessSideEffectsRoot), false, "artifact manifest response must not expose host paths");
356
+ const artifactPageResponse = await fetch(`http://127.0.0.1:${port}${artifactManifestPayload.data.pages[0].imageUrl}`, { signal: AbortSignal.timeout(5_000) });
357
+ assert.equal(artifactPageResponse.status, 200, "artifact page token should resolve");
358
+ assert.equal(artifactPageResponse.headers.get("content-type"), "image/png");
359
+ const artifactRangeResponse = await fetch(`http://127.0.0.1:${port}${publicArtifact.downloadUrl}`, { headers: { range: "bytes=0-6" }, signal: AbortSignal.timeout(5_000) });
360
+ assert.equal(artifactRangeResponse.status, 206, "artifact downloads should support bounded byte ranges");
361
+ assert.equal(artifactRangeResponse.headers.get("content-range"), `bytes 0-6/${(await stat(artifactDownload)).size}`);
362
+ const otherArtifactTab = await request("127.0.0.1", "/api/tabs", { method: "POST", body: { cwd, title: "artifact-isolation" } });
363
+ const wrongTabManifestUrl = new URL(publicArtifact.manifestUrl, `http://127.0.0.1:${port}`); wrongTabManifestUrl.searchParams.set("tab", otherArtifactTab.body?.data?.tab?.id);
364
+ assert.equal((await fetch(wrongTabManifestUrl, { signal: AbortSignal.timeout(5_000) })).status, 404, "artifact tokens must be tab-bound");
365
+ await request("127.0.0.1", `/api/tabs/${encodeURIComponent(otherArtifactTab.body?.data?.tab?.id)}`, { method: "DELETE" });
366
+ await request("127.0.0.1", "/api/prompt", { method: "POST", body: { tab: tabId, message: "fixture document artifact clear" } });
367
+
220
368
  const subagentFixtureStart = await request("127.0.0.1", "/api/prompt", { method: "POST", body: { tab: tabId, message: "fixture subagents running" } });
221
369
  assert.equal(subagentFixtureStart.status, 200, "subagent fixture status should be accepted");
222
370
  let subagentsResponse;
@@ -507,6 +655,25 @@ try {
507
655
  assert.equal(gitRemote.body?.ok, true, "remote endpoint should add origin without pushing");
508
656
  assert.equal(gitRemote.body?.data?.remoteUrl, "https://github.com/Firstp1ck/pi-webui-http-harness.git");
509
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
+
510
677
  await writeFile(path.join(cwd, "single.txt"), "created\n");
511
678
  const gitAddCreated = await request("127.0.0.1", "/api/git-workflow/add", { method: "POST", body: { tab: tabId } });
512
679
  assert.equal(gitAddCreated.status, 200);
@@ -555,6 +722,7 @@ try {
555
722
  const dir = path.join(gitFixturesRoot, name);
556
723
  await mkdir(dir, { recursive: true });
557
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`);
558
726
  runGitFixture(["config", "user.name", "Pi WebUI Test"], dir, `${name} fixture should set user name`);
559
727
  runGitFixture(["config", "user.email", "pi-webui-test@example.invalid"], dir, `${name} fixture should set user email`);
560
728
  await writeFile(path.join(dir, "file.txt"), "base\n");
@@ -648,6 +816,20 @@ try {
648
816
  assert.equal(operationSnapshot.body?.data?.conflicts?.[0]?.status, "UU");
649
817
  assert.equal(operationSnapshot.body?.data?.conflicts?.[0]?.preview?.hasMarkers, true, "conflict preview should detect conflict markers");
650
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
+
651
833
  const continueBlocked = await request("127.0.0.1", "/api/git-operation/continue", { method: "POST", body: { tab: mergeTab } });
652
834
  assert.equal(continueBlocked.status, 200);
653
835
  assert.equal(continueBlocked.body?.ok, false, "continue with unmerged paths must fail");