@firstpick/pi-package-webui 0.7.7 → 0.7.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.
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();
package/bin/pi-webui.mjs CHANGED
@@ -7654,7 +7654,7 @@ async function readBundledThemes() {
7654
7654
  function normalizeStaticPath(urlPath) {
7655
7655
  if (urlPath === "/") return "index.html";
7656
7656
  const name = urlPath.startsWith("/") ? urlPath.slice(1) : urlPath;
7657
- if (!["index.html", "app.js", "fast-output-live.mjs", "subagent-launch-slot-state.mjs", "subagent-gate-visibility.mjs", "workflow-status-stack.mjs", "voice-conversation.mjs", "aur-review-payload.mjs", "guided-git-command-state.mjs", "guided-git-review-state.mjs", "styles.css", "favicon.svg", "apple-touch-icon.png", "icon-192.png", "icon-512.png", "catppuccin-mocha-background.png", "matrix-background.webp", "manifest.webmanifest", "service-worker.js"].includes(name)) return undefined;
7657
+ if (!["index.html", "app.js", "issue-wizard-state.mjs", "issue-bot-client.mjs", "fast-output-live.mjs", "subagent-launch-slot-state.mjs", "subagent-gate-visibility.mjs", "workflow-status-stack.mjs", "voice-conversation.mjs", "aur-review-payload.mjs", "guided-git-command-state.mjs", "guided-git-review-state.mjs", "styles.css", "favicon.svg", "apple-touch-icon.png", "icon-192.png", "icon-512.png", "catppuccin-mocha-background.png", "matrix-background.webp", "manifest.webmanifest", "service-worker.js"].includes(name)) return undefined;
7658
7658
  return name;
7659
7659
  }
7660
7660
 
@@ -8410,13 +8410,13 @@ async function initializeRpcSupervisor() {
8410
8410
  });
8411
8411
  }
8412
8412
 
8413
- function supervisedTabMetadata(tab) {
8413
+ function supervisedTabMetadata(tab, { cwd = tab.cwd } = {}) {
8414
8414
  return {
8415
8415
  index: tab.index,
8416
8416
  title: tab.title,
8417
8417
  titleSource: tab.titleSource,
8418
8418
  conversationStarted: tab.conversationStarted === true,
8419
- cwd: tab.cwd,
8419
+ cwd,
8420
8420
  sessionFile: tabRestorableSessionFile(tab),
8421
8421
  gitWorkspace: tab.gitWorkspace || null,
8422
8422
  createdAt: tab.createdAt,
@@ -8424,7 +8424,9 @@ function supervisedTabMetadata(tab) {
8424
8424
  }
8425
8425
 
8426
8426
  function scheduleSupervisorMetadataUpdate(tab) {
8427
- if (!(tab?.rpc instanceof SupervisorPiRpcProcess) || tab.supervisorMetadataUpdateQueued) return;
8427
+ if (!(tab?.rpc instanceof SupervisorPiRpcProcess)) return;
8428
+ if (tab.cwdChangeInProgress) return;
8429
+ if (tab.supervisorMetadataUpdateQueued) return;
8428
8430
  tab.supervisorMetadataUpdateQueued = true;
8429
8431
  queueMicrotask(() => {
8430
8432
  tab.supervisorMetadataUpdateQueued = false;
@@ -8538,6 +8540,7 @@ function createTabActivity(now = new Date().toISOString()) {
8538
8540
  return {
8539
8541
  status: "idle",
8540
8542
  isWorking: false,
8543
+ runStarted: false,
8541
8544
  completionSerial: 0,
8542
8545
  lastChangedAt: now,
8543
8546
  lastStartedAt: null,
@@ -9143,10 +9146,11 @@ async function cancelPendingExtensionUiRequests(tab) {
9143
9146
  return ids.length;
9144
9147
  }
9145
9148
 
9146
- function markTabWorking(tab, timestamp = new Date().toISOString()) {
9149
+ function markTabWorking(tab, timestamp = new Date().toISOString(), { runStarted = false } = {}) {
9147
9150
  const activity = tab.activity || createTabActivity(timestamp);
9148
9151
  activity.status = "working";
9149
9152
  activity.isWorking = true;
9153
+ activity.runStarted = activity.runStarted === true || runStarted === true;
9150
9154
  activity.lastStartedAt = timestamp;
9151
9155
  activity.lastChangedAt = timestamp;
9152
9156
  tab.activity = activity;
@@ -9156,6 +9160,7 @@ function markTabDone(tab, timestamp = new Date().toISOString()) {
9156
9160
  const activity = tab.activity || createTabActivity(timestamp);
9157
9161
  activity.status = "done";
9158
9162
  activity.isWorking = false;
9163
+ activity.runStarted = false;
9159
9164
  activity.completionSerial = (Number(activity.completionSerial) || 0) + 1;
9160
9165
  activity.lastCompletedAt = timestamp;
9161
9166
  activity.lastChangedAt = timestamp;
@@ -9166,6 +9171,7 @@ function markTabIdle(tab, timestamp = new Date().toISOString()) {
9166
9171
  const activity = tab.activity || createTabActivity(timestamp);
9167
9172
  activity.status = "idle";
9168
9173
  activity.isWorking = false;
9174
+ activity.runStarted = false;
9169
9175
  activity.lastChangedAt = timestamp;
9170
9176
  tab.activity = activity;
9171
9177
  }
@@ -9195,11 +9201,14 @@ function reconcileTabActivityFromState(tab, state, timestamp = new Date().toISOS
9195
9201
  return tabActivitySnapshot(tab);
9196
9202
  }
9197
9203
  if (stateHasVisibleWork(state)) {
9198
- if (!tab.activity?.isWorking) markTabWorking(tab, timestamp);
9204
+ if (!tab.activity?.isWorking || (state.isStreaming && !tab.activity?.runStarted)) {
9205
+ markTabWorking(tab, timestamp, { runStarted: state.isStreaming === true });
9206
+ }
9199
9207
  return tabActivitySnapshot(tab);
9200
9208
  }
9201
9209
  if (tab.activity?.isWorking && !activityRecentlyStarted(tab.activity)) {
9202
- markTabDone(tab, timestamp);
9210
+ if (tab.activity.runStarted) markTabDone(tab, timestamp);
9211
+ else markTabIdle(tab, timestamp);
9203
9212
  }
9204
9213
  return tabActivitySnapshot(tab);
9205
9214
  }
@@ -9231,27 +9240,30 @@ function updateTabActivityFromEvent(tab, event) {
9231
9240
  switch (event?.type) {
9232
9241
  case "agent_start":
9233
9242
  patchTabState(tab, { isStreaming: true });
9234
- markTabWorking(tab, timestamp);
9243
+ markTabWorking(tab, timestamp, { runStarted: true });
9235
9244
  break;
9236
9245
  case "compaction_start":
9237
9246
  patchTabState(tab, { isCompacting: true });
9238
9247
  markTabWorking(tab, timestamp);
9239
9248
  break;
9240
9249
  case "agent_end":
9250
+ // A low-level run ended, but Pi may still retry, compact, or process a follow-up.
9251
+ break;
9252
+ case "agent_settled":
9241
9253
  patchTabState(tab, { isStreaming: false });
9242
- markTabDone(tab, timestamp);
9254
+ if (tab.activity?.runStarted) markTabDone(tab, timestamp);
9255
+ else if (tab.activity?.isWorking) markTabIdle(tab, timestamp);
9243
9256
  break;
9244
9257
  case "compaction_end":
9245
9258
  patchTabState(tab, { isCompacting: false });
9246
- markTabDone(tab, timestamp);
9259
+ if (!tab.lastState?.isStreaming && !tab.activity?.runStarted) markTabIdle(tab, timestamp);
9247
9260
  break;
9248
9261
  case "queue_update":
9249
9262
  patchTabState(tab, { pendingMessageCount: (event.steering?.length || 0) + (event.followUp?.length || 0) });
9250
9263
  break;
9251
9264
  case "pi_process_exit":
9252
9265
  case "pi_process_error":
9253
- if (tab.activity?.isWorking) markTabDone(tab, timestamp);
9254
- else markTabIdle(tab, timestamp);
9266
+ markTabIdle(tab, timestamp);
9255
9267
  break;
9256
9268
  case "response":
9257
9269
  if (event.command === "get_state" && event.success !== false) {
@@ -9338,6 +9350,7 @@ function createTabRecord({ id, index, title, titleSource, conversationStarted, c
9338
9350
  bashQueueDraining: false,
9339
9351
  compactionQueue: [],
9340
9352
  compactionQueueDraining: false,
9353
+ cwdChangeInProgress: false,
9341
9354
  rpc,
9342
9355
  rpcUnsubscribe: undefined,
9343
9356
  sseClients: new Set(),
@@ -10264,9 +10277,23 @@ function responseWithTab(response, tab) {
10264
10277
  async function updateTabCwd(id, cwd) {
10265
10278
  const tab = tabs.get(id);
10266
10279
  if (!tab) throw makeHttpError(404, `Unknown Pi tab: ${id}`);
10280
+ if (tab.cwdChangeInProgress) throw makeHttpError(409, `${tab.title} is already changing its working folder`);
10281
+
10282
+ tab.cwdChangeInProgress = true;
10283
+ try {
10284
+ return await performTabCwdUpdate(tab, cwd);
10285
+ } finally {
10286
+ tab.cwdChangeInProgress = false;
10287
+ scheduleSupervisorMetadataUpdate(tab);
10288
+ }
10289
+ }
10267
10290
 
10291
+ async function performTabCwdUpdate(tab, cwd) {
10268
10292
  const nextCwd = await resolveCwd(cwd, tab.cwd);
10269
10293
  if (nextCwd === tab.cwd) return { tab, changed: false };
10294
+ if (tab.rpc instanceof SupervisorPiRpcProcess && !tab.rpc.supervisor.isCurrentVersion()) {
10295
+ throw makeHttpError(503, "The detached Pi supervisor is from an older WebUI build. Fully shut down Pi WebUI (not Restart), then start it again before changing working folders.");
10296
+ }
10270
10297
 
10271
10298
  // Capture the live session before stopping the old RPC so the conversation
10272
10299
  // survives the cwd restart, mirroring restartTabRpc. Best-effort: a dead RPC
@@ -10277,39 +10304,47 @@ async function updateTabCwd(id, cwd) {
10277
10304
  const piArgs = await buildPiArgsForTab(tab.index, tab.title, nextCwd);
10278
10305
  if (sessionFile && !options.noSession) piArgs.push("--session", sessionFile);
10279
10306
  const piCommand = await resolvePiCommand(piArgs);
10280
- gitLiveWatcher.unsubscribe(tab.id);
10281
10307
  const restartingEvent = { type: "webui_tab_restarting", tabId: tab.id, tabTitle: tab.title, cwd: nextCwd, sessionFile };
10282
10308
  broadcastTabEvent(tab, restartingEvent);
10283
10309
 
10284
10310
  const oldRpc = tab.rpc;
10285
- tab.rpcUnsubscribe?.();
10286
- tab.rpcUnsubscribe = undefined;
10287
10311
  rejectTabBashQueue(tab, new Error("Pi tab is restarting; queued bash commands were cancelled"));
10288
10312
  stopAppRunnerForTab(tab, "cwd changed", { force: true });
10289
-
10290
- tab.cwd = nextCwd;
10291
- resetTabActivity(tab);
10292
10313
  clearPendingExtensionUiRequests(tab);
10293
10314
  clearExtensionStatuses(tab);
10294
10315
  clearExtensionWidgets(tab);
10295
10316
  clearWebuiSubagents(tab);
10296
10317
  resetNaturalConversationMode(tab);
10318
+
10297
10319
  let rpc;
10298
- if (oldRpc instanceof SupervisorPiRpcProcess) {
10299
- const snapshot = await oldRpc.replace({
10300
- child: { command: piCommand.command, args: piCommand.args, cwd: tab.cwd },
10301
- metadata: supervisedTabMetadata(tab),
10302
- displayCommand: piCommand.displayCommand,
10303
- });
10304
- oldRpc.dispose();
10305
- rpc = new SupervisorPiRpcProcess({ supervisor: rpcSupervisor, tabId: tab.id, displayCommand: piCommand.displayCommand, cwd: tab.cwd, snapshot });
10306
- attachRpcToTab(tab, rpc);
10307
- } else {
10308
- oldRpc.stop();
10309
- rpc = new PiRpcProcess({ ...piCommand, cwd: tab.cwd, env: piRpcEnvironment() });
10310
- attachRpcToTab(tab, rpc);
10311
- rpc.start();
10320
+ let startDirectRpc = false;
10321
+ try {
10322
+ if (oldRpc instanceof SupervisorPiRpcProcess) {
10323
+ const snapshot = await oldRpc.replace({
10324
+ child: { command: piCommand.command, args: piCommand.args, cwd: nextCwd },
10325
+ metadata: supervisedTabMetadata(tab, { cwd: nextCwd }),
10326
+ displayCommand: piCommand.displayCommand,
10327
+ });
10328
+ oldRpc.dispose();
10329
+ rpc = new SupervisorPiRpcProcess({ supervisor: rpcSupervisor, tabId: tab.id, displayCommand: piCommand.displayCommand, cwd: nextCwd, snapshot });
10330
+ } else {
10331
+ oldRpc.stop();
10332
+ rpc = new PiRpcProcess({ ...piCommand, cwd: nextCwd, env: piRpcEnvironment() });
10333
+ startDirectRpc = true;
10334
+ }
10335
+ } catch (error) {
10336
+ const detail = sanitizeError(error);
10337
+ broadcastTabEvent(tab, { type: "webui_cwd_change_failed", tabId: tab.id, tabTitle: tab.title, cwd: nextCwd, error: detail });
10338
+ throw makeHttpError(502, `Could not restart ${tab.title} in ${displayPath(nextCwd)}: ${detail}`);
10312
10339
  }
10340
+
10341
+ tab.rpcUnsubscribe?.();
10342
+ tab.rpcUnsubscribe = undefined;
10343
+ tab.cwd = nextCwd;
10344
+ resetTabActivity(tab);
10345
+ attachRpcToTab(tab, rpc);
10346
+ if (startDirectRpc) rpc.start();
10347
+ gitLiveWatcher.unsubscribe(tab.id);
10313
10348
  // Non-fatal: a failed start surfaces through pi_process_error/exit events.
10314
10349
  await primeTabRpc(tab).catch(() => {});
10315
10350
 
@@ -9,6 +9,7 @@ import {
9
9
  encodeFrame,
10
10
  frameReader,
11
11
  newRequestId,
12
+ protocolCurrent,
12
13
  } from "./rpc-supervisor-protocol.mjs";
13
14
  import {
14
15
  acquireStartupLock,
@@ -47,6 +48,14 @@ function liveStateError(state) {
47
48
  });
48
49
  }
49
50
 
51
+ function supervisorRestartRequiredError(state, operation) {
52
+ const version = state?.version;
53
+ const remote = Number.isInteger(version?.major) && Number.isInteger(version?.minor) ? `${version.major}.${version.minor}` : "unknown";
54
+ return Object.assign(new Error(`The detached RPC supervisor protocol ${remote} is older than this WebUI build and cannot ${operation}. Fully shut down Pi WebUI (not Restart), then start it again.`), {
55
+ code: "RPC_SUPERVISOR_RESTART_REQUIRED",
56
+ });
57
+ }
58
+
50
59
  function openSocket(socketPath, timeoutMs = DEFAULT_CONNECT_TIMEOUT_MS) {
51
60
  return new Promise((resolve, reject) => {
52
61
  const socket = createConnection(socketPath);
@@ -184,6 +193,7 @@ export class RpcSupervisorClient {
184
193
  }
185
194
 
186
195
  isConnected() { return this.connected && this.attached; }
196
+ isCurrentVersion() { return protocolCurrent(this.state.version); }
187
197
 
188
198
  request(type, payload = {}, { requestId = newRequestId() } = {}) {
189
199
  if (!this.attached) return Promise.reject(new Error("RPC supervisor client is not attached"));
@@ -199,9 +209,15 @@ export class RpcSupervisorClient {
199
209
  return result.promise;
200
210
  }
201
211
 
202
- createTab({ tabId, metadata, child }, options) { return this.request("create", { tabId, metadata, child }, options); }
212
+ createTab({ tabId, metadata, child }, options) {
213
+ if (!this.isCurrentVersion()) return Promise.reject(supervisorRestartRequiredError(this.state, "create a Pi tab"));
214
+ return this.request("create", { tabId, metadata, child }, options);
215
+ }
203
216
  updateTab(tabId, metadata, options) { return this.request("update", { tabId, metadata }, options); }
204
- replaceTab({ tabId, metadata, child }, options) { return this.request("replace", { tabId, metadata, child }, options); }
217
+ replaceTab({ tabId, metadata, child }, options) {
218
+ if (!this.isCurrentVersion()) return Promise.reject(supervisorRestartRequiredError(this.state, "replace a Pi tab"));
219
+ return this.request("replace", { tabId, metadata, child }, options);
220
+ }
205
221
  closeTab(tabId, options) { return this.request("close", { tabId }, options); }
206
222
  command(tabId, command, { requestId = newRequestId(), timeoutMs } = {}) {
207
223
  return this.request("command", { tabId, command, ...(timeoutMs ? { timeoutMs } : {}) }, { requestId });
@@ -1,7 +1,7 @@
1
1
  import { randomUUID, timingSafeEqual } from "node:crypto";
2
2
  import { StringDecoder } from "node:string_decoder";
3
3
 
4
- export const RPC_SUPERVISOR_PROTOCOL = Object.freeze({ major: 1, minor: 0 });
4
+ export const RPC_SUPERVISOR_PROTOCOL = Object.freeze({ major: 1, minor: 2 });
5
5
  // Pi permits one bounded JSONL record this large. IPC envelopes need a small
6
6
  // additional allowance so a single valid Pi record can always be forwarded.
7
7
  export const PI_RPC_JSONL_LINE_MAX_BYTES = 32 * 1024 * 1024;
@@ -13,6 +13,10 @@ export const RPC_SUPERVISOR_EVENT_RING_LIMIT = 512;
13
13
  export const RPC_SUPERVISOR_EVENT_RING_MAX_BYTES = 4 * 1024 * 1024;
14
14
  export const RPC_SUPERVISOR_REQUEST_DEDUPE_LIMIT = 2048;
15
15
  export const RPC_SUPERVISOR_TAB_LIMIT = 64;
16
+ // Each configured extension, skill, prompt, and theme contributes a flag/value
17
+ // pair. Real WebUI profiles can exceed 256 arguments before a --session pair
18
+ // is appended during reload, CWD changes, or forks.
19
+ export const RPC_SUPERVISOR_CHILD_ARG_LIMIT = 1024;
16
20
  export const RPC_SUPERVISOR_METADATA_MAX_BYTES = 64 * 1024;
17
21
  export const RPC_SUPERVISOR_ID_MAX_LENGTH = 128;
18
22
  // This applies only to persisted metadata, state, and journals. Live Pi RPC
@@ -81,6 +85,11 @@ export function protocolCompatible(remote) {
81
85
  return parsed.major === RPC_SUPERVISOR_PROTOCOL.major;
82
86
  }
83
87
 
88
+ export function protocolCurrent(remote) {
89
+ const parsed = version(remote);
90
+ return parsed.major === RPC_SUPERVISOR_PROTOCOL.major && parsed.minor === RPC_SUPERVISOR_PROTOCOL.minor;
91
+ }
92
+
84
93
  export function assertProtocolCompatible(remote) {
85
94
  if (!protocolCompatible(remote)) {
86
95
  const parsed = version(remote);
@@ -156,7 +165,7 @@ function validateChild(value, label = "child") {
156
165
  object(value, label);
157
166
  onlyKeys(value, new Set(["command", "args", "cwd"]), label);
158
167
  const command = string(value.command, `${label}.command`, { max: 4096 });
159
- if (!Array.isArray(value.args) || value.args.length > 256) fail(`${label}.args must be an array with at most 256 entries`);
168
+ if (!Array.isArray(value.args) || value.args.length > RPC_SUPERVISOR_CHILD_ARG_LIMIT) fail(`${label}.args must be an array with at most ${RPC_SUPERVISOR_CHILD_ARG_LIMIT} entries`);
160
169
  const args = value.args.map((arg, index) => string(arg, `${label}.args[${index}]`, { min: 0, max: 64 * 1024 }));
161
170
  const cwd = string(value.cwd, `${label}.cwd`, { max: 16 * 1024 });
162
171
  return { command, args, cwd };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@firstpick/pi-package-webui",
3
- "version": "0.7.7",
3
+ "version": "0.7.8",
4
4
  "description": "Pi Web UI companion package with a local browser UI CLI plus /webui-start and /webui-status commands.",
5
5
  "license": "MIT",
6
6
  "homepage": "https://github.com/Firstp1ck/pi-coding-agent-forge/tree/main/pi-package-webui#readme",
@@ -51,11 +51,11 @@
51
51
  "pi-webui": "./bin/pi-webui.mjs"
52
52
  },
53
53
  "scripts": {
54
- "check": "node --check public/app.js && node --check public/workflow-status-stack.mjs && node --check public/fast-output-live.mjs && node --check public/subagent-launch-slot-state.mjs && node --check public/subagent-gate-visibility.mjs && node --check public/voice-conversation.mjs && node --check public/aur-review-payload.mjs && node --check public/guided-git-command-state.mjs && node --check public/guided-git-review-state.mjs && node --check bin/pi-webui.mjs && node --check bin/pi-webui-rpc-supervisor.mjs && node --check lib/rpc-supervisor-protocol.mjs && node --check lib/rpc-supervisor-state.mjs && node --check lib/rpc-supervisor-client.mjs && node --check webui-rpc-helper.mjs && node --check lib/subagent-launch-slots.mjs && node --check lib/git-live-watcher.mjs && node --check lib/git-message-artifacts.mjs && node --check lib/trust-boundaries.mjs && node --check lib/native-command-adapter.mjs && node --check lib/session-actions.mjs && node --check lib/auth-actions.mjs && node --check lib/temp-artifacts.mjs && node tests/run-all.mjs",
54
+ "check": "node --check public/app.js && node --check public/issue-wizard-state.mjs && node --check public/issue-bot-client.mjs && node --check public/workflow-status-stack.mjs && node --check public/fast-output-live.mjs && node --check public/subagent-launch-slot-state.mjs && node --check public/subagent-gate-visibility.mjs && node --check public/voice-conversation.mjs && node --check public/aur-review-payload.mjs && node --check public/guided-git-command-state.mjs && node --check public/guided-git-review-state.mjs && node --check bin/pi-webui.mjs && node --check bin/pi-webui-rpc-supervisor.mjs && node --check lib/rpc-supervisor-protocol.mjs && node --check lib/rpc-supervisor-state.mjs && node --check lib/rpc-supervisor-client.mjs && node --check webui-rpc-helper.mjs && node --check lib/subagent-launch-slots.mjs && node --check lib/git-live-watcher.mjs && node --check lib/git-message-artifacts.mjs && node --check lib/trust-boundaries.mjs && node --check lib/native-command-adapter.mjs && node --check lib/session-actions.mjs && node --check lib/auth-actions.mjs && node --check lib/temp-artifacts.mjs && node tests/run-all.mjs",
55
55
  "test": "node tests/run-all.mjs"
56
56
  },
57
57
  "dependencies": {
58
- "@earendil-works/pi-coding-agent": "^0.82.0",
58
+ "@earendil-works/pi-coding-agent": "^0.82.1",
59
59
  "@firstpick/pi-utils": "^0.2.5",
60
60
  "mermaid": "^11.15.0",
61
61
  "typebox": "^1.3.6"
@@ -72,7 +72,7 @@
72
72
  "@firstpick/pi-extension-stats": "^0.2.9",
73
73
  "@firstpick/pi-extension-todo-progress": "^0.2.9",
74
74
  "@firstpick/pi-extension-tools": "^0.1.7",
75
- "@firstpick/pi-extension-workflows": "^0.1.6",
75
+ "@firstpick/pi-extension-workflows": "^0.1.7",
76
76
  "@firstpick/pi-package-remote-webui": "^0.1.8",
77
77
  "@firstpick/pi-prompts-git-pr": "^0.1.5",
78
78
  "@firstpick/pi-themes-bundle": "^0.1.5",