@firstpick/pi-package-webui 0.7.7 → 0.7.9

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.
Files changed (50) hide show
  1. package/README.md +23 -0
  2. package/bin/pi-webui-rpc-supervisor.mjs +115 -21
  3. package/bin/pi-webui.mjs +447 -88
  4. package/lib/queue-mutation.mjs +109 -0
  5. package/lib/rpc-supervisor-client.mjs +18 -2
  6. package/lib/rpc-supervisor-protocol.mjs +11 -2
  7. package/lib/scoped-models.mjs +19 -0
  8. package/lib/webui-workspaces.mjs +265 -0
  9. package/package.json +4 -4
  10. package/public/app.js +2227 -195
  11. package/public/index.html +143 -2
  12. package/public/issue-bot-client.mjs +344 -0
  13. package/public/issue-wizard-state.mjs +443 -0
  14. package/public/service-worker.js +3 -1
  15. package/public/styles.css +787 -56
  16. package/public/voice-conversation.mjs +1 -1
  17. package/tests/boot-failure-diagnostics.test.mjs +3 -3
  18. package/tests/compaction-mutation-contract.test.mjs +166 -0
  19. package/tests/compaction-resume-harness.test.mjs +113 -2
  20. package/tests/compaction-static.test.mjs +5 -0
  21. package/tests/completion-signal-contract.test.mjs +156 -0
  22. package/tests/cwd-footer-reliability-static.test.mjs +112 -0
  23. package/tests/durable-rpc-supervisor-harness.test.mjs +25 -2
  24. package/tests/fast-mode-client-static.test.mjs +1 -1
  25. package/tests/file-selection-overlay-static.test.mjs +21 -0
  26. package/tests/file-viewer-search-static.test.mjs +65 -0
  27. package/tests/fixtures/compacting-pi.mjs +0 -0
  28. package/tests/fixtures/fake-pi.mjs +186 -49
  29. package/tests/footer-context-contrast-static.test.mjs +10 -0
  30. package/tests/git-panel-file-preview-static.test.mjs +20 -5
  31. package/tests/git-panel-render-stability-static.test.mjs +11 -1
  32. package/tests/http-endpoints-harness.test.mjs +160 -1
  33. package/tests/issue-bot-client.test.mjs +135 -0
  34. package/tests/issue-wizard-state.test.mjs +126 -0
  35. package/tests/mobile-static.test.mjs +61 -42
  36. package/tests/native-parity.test.mjs +3 -3
  37. package/tests/open-issue-wizard-static.test.mjs +75 -0
  38. package/tests/prompt-routing-tab-status.test.mjs +5 -0
  39. package/tests/queue-edit-reorder-static.test.mjs +101 -0
  40. package/tests/queue-mutation-contract.test.mjs +143 -0
  41. package/tests/rpc-supervisor-host.test.mjs +135 -2
  42. package/tests/rpc-supervisor-protocol.test.mjs +26 -0
  43. package/tests/scoped-models.test.mjs +42 -0
  44. package/tests/streaming-ui-coupling.test.mjs +3 -2
  45. package/tests/subagents-helper.test.mjs +216 -3
  46. package/tests/terminal-tab-workspace-static.test.mjs +101 -0
  47. package/tests/webui-workspaces-harness.test.mjs +223 -0
  48. package/tests/webui-workspaces.test.mjs +106 -0
  49. package/tests/workspace-save-load-static.test.mjs +69 -0
  50. package/webui-rpc-helper.mjs +300 -41
package/README.md CHANGED
@@ -471,6 +471,29 @@ Use the workflow process buttons to jump directly to **Initialize**, **Stage**,
471
471
 
472
472
  This requires `/git-staged-msg` and `/pr` from `@firstpick/pi-prompts-git-pr`; branch-name generation uses `/git-branch-name`. Creating the PR also requires an authenticated GitHub CLI (`gh`). Review the generated commit message, branch name, remote URL, and PR description before committing, pushing, or creating a PR.
473
473
 
474
+ ## Open Issue bot
475
+
476
+ The **Open Issue** Control Deck action always keeps **Copy complete issue** available. Automated submission is intentionally disabled by default and sends no request unless a deployment supplies the public configuration below before `app.js` loads. These are public routing values only—never put a Cloudflare secret, OpenAI key, GitHub App credential, status capability, or repository-write token in this object.
477
+
478
+ ```html
479
+ <script>
480
+ window.__PI_WEBUI_ISSUE_BOT_CONFIG__ = Object.freeze({
481
+ enabled: true,
482
+ gatewayBaseUrl: "https://issue-intake.example.com",
483
+ turnstileSiteKey: "public-turnstile-site-key",
484
+ privateSecurityReportUrl: "https://github.com/OWNER/REPOSITORY/security/advisories/new"
485
+ });
486
+ </script>
487
+ ```
488
+
489
+ Replace the disabled object in the deployed `public/index.html`, or inject the same object in the hosting HTML before the package's default configuration block. The client accepts only an HTTPS gateway/base URL without credentials, query, or fragment; a syntactically invalid or incomplete configuration fails closed and leaves the button disabled. `turnstileSiteKey` and the private-report URL are public values. The configured intake must allow the exact WebUI `Origin`; do not use a wildcard CORS policy. If a Content Security Policy is present, permit `https://challenges.cloudflare.com` for the Turnstile script/frame requests as documented by Turnstile.
490
+
491
+ When enabled, each click obtains a fresh Turnstile token and UUID-v4, then posts only `{ schemaVersion, idempotencyKey, turnstileToken, issue }` to `POST /v1/submissions`. `issue` is the selected structured wizard state (`categoryId`, `componentId`, `templateId`, `summary`, and declared fields); editable canonical title/body, repository, labels, verdicts, callback URLs, and credentials are never sent. The returned status capability remains only in an opaque in-memory refresh handle for the open dialog. Nothing in this flow uses `localStorage`, `sessionStorage`, cookies, or draft persistence.
492
+
493
+ The dialog shows queued/checking/created/rejected/review/unavailable/unknown status in a persistent live region. It polls the capability endpoint with bounded exponential delays (initial server delay, capped at 10 seconds) for at most two minutes, then offers **Refresh status** rather than continuing in the background. Closing the dialog aborts Turnstile, admission, or polling. A created result must be a validated `https://github.com/<owner>/<repo>/issues/<number>` link and opens with `noopener noreferrer`. Sensitive-content outcomes show only the configured private-report destination; the wizard never echoes the submitted security text. Rejection, review, unavailable, unknown, and polling-timeout paths retain the copy fallback.
494
+
495
+ Keep this browser configuration disabled until the gateway's exact-origin CORS policy, Turnstile hostname/action checks, private reporting URL, staging canary, quotas, and both gateway kill-switch decisions have passed review. Browser enablement does not bypass `ISSUE_BOT_ADMISSION_ENABLED` or `ISSUE_BOT_CREATE_ENABLED`; production creation remains a separate operator approval.
496
+
474
497
  ## Mobile and PWA notes
475
498
 
476
499
  - The mobile composer starts as a compact `Ask Pi…` input and grows as you type.
@@ -35,6 +35,12 @@ import {
35
35
  const ATTACH_TIMEOUT_MS = 2_500;
36
36
  const EMPTY_IDLE_GRACE_MS = 1_500;
37
37
  const CHILD_STOP_GRACE_MS = 3_000;
38
+ const CHILD_STDIN_WRITE_TIMEOUT_MS = 2_000;
39
+ const REQUEST_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
40
+
41
+ function requestIdForErrorFrame(frame) {
42
+ return typeof frame?.requestId === "string" && REQUEST_ID_PATTERN.test(frame.requestId) ? frame.requestId : undefined;
43
+ }
38
44
 
39
45
  function cliOptions(argv) {
40
46
  const options = { agentDir: defaultAgentDir(), port: undefined, runtimeDir: undefined };
@@ -161,7 +167,10 @@ class SupervisorHost {
161
167
  this.clients.add(client);
162
168
  this.cancelIdleExit();
163
169
  const consume = frameReader(
164
- (frame) => this.handleFrame(client, frame).catch((error) => this.sendError(client, undefined, error)),
170
+ // Validation can fail before handleFrame has a normalized request. Echo a
171
+ // syntactically safe raw request ID so the client rejects the matching
172
+ // promise instead of leaving create/replace requests pending forever.
173
+ (frame) => this.handleFrame(client, frame).catch((error) => this.sendError(client, requestIdForErrorFrame(frame), error)),
165
174
  (error) => { this.sendError(client, undefined, error); socket.destroy(); },
166
175
  );
167
176
  socket.on("data", consume);
@@ -287,14 +296,45 @@ class SupervisorHost {
287
296
  catch (error) { this.sendError(client, request.requestId, error); }
288
297
  }
289
298
 
299
+ queueTabMutation(tabId, operation) {
300
+ const tab = this.requireTab(tabId);
301
+ const previous = tab.mutationTail || Promise.resolve();
302
+ const result = previous.catch(() => {}).then(() => {
303
+ if (this.tabs.get(tabId) !== tab) throw new Error(`Managed tab is no longer available: ${tabId}`);
304
+ return operation();
305
+ });
306
+ tab.mutationTail = result.catch(() => {});
307
+ return result;
308
+ }
309
+
310
+ queueTabCommand(tabId, operation) {
311
+ const tab = this.requireTab(tabId);
312
+ const previous = tab.mutationTail || Promise.resolve();
313
+ let response;
314
+ const admission = previous.catch(() => {}).then(() => {
315
+ if (this.tabs.get(tabId) !== tab) throw new Error(`Managed tab is no longer available: ${tabId}`);
316
+ // command() registers the pending response and writes to stdin
317
+ // synchronously before returning its response promise. Release the FIFO
318
+ // barrier at that point so extension-ui writes and later bounded probes
319
+ // are not blocked by the full Pi response lifetime.
320
+ response = operation();
321
+ });
322
+ tab.mutationTail = admission.catch(() => {});
323
+ return admission.then(() => response);
324
+ }
325
+
290
326
  async perform(request) {
291
327
  switch (request.type) {
292
328
  case "create": return this.create(request);
293
- case "update": return this.update(request);
294
- case "replace": return this.replace(request);
295
- case "close": return this.closeTab(request.tabId);
296
- case "command": return this.command(request);
297
- case "write": return this.write(request);
329
+ case "update": return this.queueTabMutation(request.tabId, () => this.update(request));
330
+ case "replace": return this.queueTabMutation(request.tabId, () => this.replace(request));
331
+ case "close": return this.queueTabMutation(request.tabId, () => this.closeTab(request.tabId));
332
+ // Commands take a FIFO admission position, but their full response must
333
+ // not hold the queue: prompts can wait for extension-ui writes. Metadata
334
+ // refreshes can also arrive continuously, so chasing a moving tail would
335
+ // starve get_state and leave a CWD PATCH permanently in progress.
336
+ case "command": return this.queueTabCommand(request.tabId, () => this.command(request));
337
+ case "write": return this.queueTabMutation(request.tabId, () => this.write(request));
298
338
  case "ack": return { cursor: request.cursor };
299
339
  case "prepare_handoff": return { epoch: this.epoch, latestSeq: this.sequence.toString(), tabs: [...this.tabs.values()].map(tabSnapshot) };
300
340
  case "detach": return { detached: true };
@@ -308,10 +348,15 @@ class SupervisorHost {
308
348
  async create({ tabId, metadata, child }) {
309
349
  if (this.tabs.has(tabId)) throw new Error(`Managed tab already exists: ${tabId}`);
310
350
  if (this.tabs.size >= RPC_SUPERVISOR_TAB_LIMIT) throw new Error(`Managed tab limit is ${RPC_SUPERVISOR_TAB_LIMIT}`);
311
- const tab = { id: tabId, metadata, child: null, pending: new Map(), startedAt: new Date().toISOString() };
351
+ const tab = { id: tabId, metadata, child: null, pending: new Map(), startedAt: new Date().toISOString(), mutationTail: Promise.resolve() };
312
352
  this.tabs.set(tabId, tab);
313
- try { await this.spawnChild(tab, child); }
314
- catch (error) { this.tabs.delete(tabId); throw error; }
353
+ try {
354
+ const candidate = await this.spawnChildCandidate(child);
355
+ this.commitChild(tab, candidate);
356
+ } catch (error) {
357
+ this.tabs.delete(tabId);
358
+ throw error;
359
+ }
315
360
  await this.persist("create");
316
361
  return tabSnapshot(tab);
317
362
  }
@@ -326,8 +371,9 @@ class SupervisorHost {
326
371
  async replace({ tabId, metadata, child }) {
327
372
  const tab = this.requireTab(tabId);
328
373
  await this.stopChild(tab, "replace");
374
+ const candidate = await this.spawnChildCandidate(child);
329
375
  if (metadata !== undefined) tab.metadata = metadata;
330
- await this.spawnChild(tab, child);
376
+ this.commitChild(tab, candidate);
331
377
  await this.persist("replace");
332
378
  return tabSnapshot(tab);
333
379
  }
@@ -347,7 +393,7 @@ class SupervisorHost {
347
393
  return tab;
348
394
  }
349
395
 
350
- async spawnChild(tab, child) {
396
+ async spawnChildCandidate(child) {
351
397
  const cwd = await realpath(child.cwd).catch(() => child.cwd);
352
398
  const processChild = spawn(child.command, child.args, {
353
399
  cwd,
@@ -356,19 +402,41 @@ class SupervisorHost {
356
402
  detached: process.platform !== "win32",
357
403
  windowsHide: true,
358
404
  });
405
+ await new Promise((resolve, reject) => {
406
+ processChild.once("spawn", resolve);
407
+ processChild.once("error", reject);
408
+ });
409
+ return { processChild, cwd, startedAt: new Date().toISOString() };
410
+ }
411
+
412
+ commitChild(tab, { processChild, cwd, startedAt }) {
359
413
  tab.child = processChild;
360
- tab.startedAt = new Date().toISOString();
414
+ tab.startedAt = startedAt;
361
415
  processChild.on("error", (error) => {
416
+ if (tab.child !== processChild) return;
362
417
  this.emit(tab.id, { type: "pi_process_error", error: publicError(error) });
363
418
  this.rejectPending(tab, error);
364
419
  });
365
420
  processChild.on("exit", (code, signal) => {
421
+ if (tab.child !== processChild) return;
366
422
  this.emit(tab.id, { type: "pi_process_exit", code, signal });
367
423
  this.rejectPending(tab, new Error(`Pi RPC process exited${code === null ? "" : ` with code ${code}`}${signal ? ` (${signal})` : ""}`));
368
424
  if (!this.closing) this.persist("child exit").catch(() => {});
369
425
  });
370
- this.readJsonl(processChild.stdout, (line) => this.handlePiLine(tab, line), tab.id);
371
- this.readText(processChild.stderr, (text) => { if (text) this.emit(tab.id, { type: "pi_stderr", text }); });
426
+ // ChildProcess does not forward stdin pipe errors to its own `error`
427
+ // event. A timed-out/backpressured one-way write followed by replacement
428
+ // can otherwise emit an unhandled EPIPE and crash the detached supervisor.
429
+ processChild.stdin.on("error", (error) => {
430
+ if (tab.child !== processChild || !tabRunning(tab)) return;
431
+ this.emit(tab.id, { type: "pi_stdin_error", error: publicError(error) });
432
+ this.rejectPending(tab, error);
433
+ });
434
+ this.readJsonl(processChild.stdout, (line) => {
435
+ if (tab.child === processChild) this.handlePiLine(tab, line);
436
+ }, tab.id);
437
+ this.readText(processChild.stderr, (text) => {
438
+ if (text && tab.child === processChild) this.emit(tab.id, { type: "pi_stderr", text });
439
+ });
372
440
  // The executable/arguments are launch details, not WebUI event data; never
373
441
  // publish them because command-line credentials must stay private.
374
442
  this.emit(tab.id, { type: "pi_process_start", pid: processChild.pid, cwd });
@@ -453,15 +521,29 @@ class SupervisorHost {
453
521
  const tab = this.requireTab(tabId);
454
522
  if (!tabRunning(tab) || !tab.child?.stdin?.writable) throw new Error("Pi RPC process is not running");
455
523
  // Unlike `command`, this preserves the supplied Pi RPC object exactly and
456
- // resolves after stdin accepts it; no response ID is injected or awaited.
524
+ // never waits for a Pi response. Keep FIFO ordering until Node flushes the
525
+ // record, but bound that wait: a backpressured/unresponsive child must not
526
+ // poison the tab mutation queue and block reload, CWD changes, or startup
527
+ // probes for a forked tab forever.
457
528
  return new Promise((resolve, reject) => {
529
+ let settled = false;
530
+ let timer = null;
531
+ const finish = (error) => {
532
+ if (settled) return;
533
+ settled = true;
534
+ if (timer) clearTimeout(timer);
535
+ if (error) reject(error);
536
+ else resolve({ written: true });
537
+ };
538
+ timer = setTimeout(() => finish(Object.assign(
539
+ new Error(`Timed out flushing a one-way Pi RPC write after ${CHILD_STDIN_WRITE_TIMEOUT_MS}ms`),
540
+ { code: "RPC_SUPERVISOR_CHILD_WRITE_TIMEOUT" },
541
+ )), CHILD_STDIN_WRITE_TIMEOUT_MS);
542
+ timer.unref?.();
458
543
  try {
459
- tab.child.stdin.write(`${JSON.stringify(command)}\n`, (error) => {
460
- if (error) reject(error);
461
- else resolve({ written: true });
462
- });
544
+ tab.child.stdin.write(`${JSON.stringify(command)}\n`, finish);
463
545
  } catch (error) {
464
- reject(error);
546
+ finish(error);
465
547
  }
466
548
  });
467
549
  }
@@ -484,6 +566,11 @@ class SupervisorHost {
484
566
  terminateProcessTree(child, "SIGKILL");
485
567
  await exitPromise(child, 1_000);
486
568
  }
569
+ if (tabRunning(tab)) {
570
+ throw Object.assign(new Error(`Pi RPC process ${child.pid || "unknown"} did not stop for ${reason}`), {
571
+ code: "RPC_SUPERVISOR_CHILD_STOP_TIMEOUT",
572
+ });
573
+ }
487
574
  this.rejectPending(tab, new Error(`Pi RPC process stopped for ${reason}`));
488
575
  }
489
576
 
@@ -502,7 +589,14 @@ class SupervisorHost {
502
589
  if (this.closing) return;
503
590
  this.closing = true;
504
591
  this.cancelIdleExit();
505
- await Promise.all([...this.tabs.values()].map((tab) => this.stopChild(tab, reason).catch(() => {})));
592
+ const stopResults = await Promise.allSettled([...this.tabs.values()].map((tab) => this.stopChild(tab, reason)));
593
+ const stopFailures = stopResults.filter((result) => result.status === "rejected");
594
+ if (stopFailures.length) {
595
+ this.closing = false;
596
+ await this.persist("shutdown blocked by live child").catch(() => {});
597
+ console.error(`RPC supervisor shutdown blocked: ${stopFailures.map((result) => publicError(result.reason)).join("; ")}`);
598
+ return false;
599
+ }
506
600
  await this.persistQueue.catch(() => {});
507
601
  this.tabs.clear();
508
602
  for (const client of this.clients) client.socket.destroy();