@firstpick/pi-package-webui 0.8.0 → 0.8.1

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 (51) hide show
  1. package/README.md +22 -5
  2. package/bin/pi-webui.mjs +434 -100
  3. package/lib/npm-command.mjs +81 -0
  4. package/lib/queue-mutation.mjs +6 -0
  5. package/lib/workspace-files-live-watcher.mjs +138 -0
  6. package/package.json +8 -3
  7. package/public/app.js +2816 -314
  8. package/public/index.html +112 -27
  9. package/public/mobile-shell-state.mjs +166 -0
  10. package/public/service-worker.js +60 -13
  11. package/public/styles.css +1049 -371
  12. package/public/subagent-gate-visibility.mjs +16 -0
  13. package/public/subagent-launch-slot-state.mjs +16 -0
  14. package/public/transcript-renderer.mjs +433 -0
  15. package/tests/boot-failure-diagnostics.test.mjs +3 -3
  16. package/tests/browser/interaction-continuity.spec.mjs +739 -0
  17. package/tests/browser/mobile-foundation.spec.mjs +352 -0
  18. package/tests/browser/optimistic-prompt.spec.mjs +130 -0
  19. package/tests/chat-scroll-intent-static.test.mjs +6 -1
  20. package/tests/codex-fast-mode-static.test.mjs +8 -5
  21. package/tests/compact-sections-static.test.mjs +20 -2
  22. package/tests/compaction-mutation-contract.test.mjs +18 -4
  23. package/tests/compaction-static.test.mjs +1 -0
  24. package/tests/completion-signal-contract.test.mjs +13 -2
  25. package/tests/fast-mode-client-static.test.mjs +7 -4
  26. package/tests/fixtures/fake-pi.mjs +181 -2
  27. package/tests/git-panel-gitignore-static.test.mjs +104 -0
  28. package/tests/http-endpoints-harness.test.mjs +228 -2
  29. package/tests/interaction-state-stability-static.test.mjs +254 -0
  30. package/tests/mobile-continuity-tablet-static.test.mjs +55 -0
  31. package/tests/mobile-foundation-static.test.mjs +69 -0
  32. package/tests/mobile-phone-experience-static.test.mjs +65 -0
  33. package/tests/mobile-shell-state.test.mjs +69 -0
  34. package/tests/mobile-static.test.mjs +244 -38
  35. package/tests/mobile-transcript-cache-characterization.test.mjs +34 -0
  36. package/tests/npm-command.test.mjs +64 -1
  37. package/tests/open-issue-wizard-static.test.mjs +2 -1
  38. package/tests/queue-edit-reorder-static.test.mjs +9 -1
  39. package/tests/queue-mutation-contract.test.mjs +22 -0
  40. package/tests/service-worker-lifecycle.test.mjs +120 -0
  41. package/tests/sse-backpressure-harness.test.mjs +98 -0
  42. package/tests/streaming-ui-coupling.test.mjs +7 -1
  43. package/tests/subagent-gate-visibility.test.mjs +18 -2
  44. package/tests/subagent-launch-slot-state.test.mjs +32 -0
  45. package/tests/subagent-launch-slots-static.test.mjs +8 -2
  46. package/tests/subagents-helper.test.mjs +90 -0
  47. package/tests/terminal-tab-workspace-static.test.mjs +1 -1
  48. package/tests/update-commands.test.mjs +4 -0
  49. package/tests/workspace-files-live-updates-static.test.mjs +76 -0
  50. package/tests/workspace-files-live-watcher.test.mjs +95 -0
  51. package/webui-rpc-helper.mjs +175 -3
package/bin/pi-webui.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import { spawn } from "node:child_process";
3
3
  import { createHash, randomInt, randomUUID, timingSafeEqual } from "node:crypto";
4
- import { createReadStream, readFileSync, realpathSync, statSync } from "node:fs";
4
+ import { constants as fsConstants, createReadStream, readFileSync, realpathSync, statSync } from "node:fs";
5
5
  import { createServer } from "node:http";
6
6
  import { createRequire } from "node:module";
7
7
  import { access, copyFile, lstat, mkdir, open, readFile, readdir, realpath, rename, rm, stat, writeFile } from "node:fs/promises";
@@ -39,7 +39,7 @@ import {
39
39
  windowsReservedGitPathFailure,
40
40
  } from "../lib/git-command-errors.mjs";
41
41
  import { piUpdateCommandSteps, piUpdateCommandText, piUpdateHelpSupportsAll } from "../lib/update-commands.mjs";
42
- import { resolveNpmCommandInvocation } from "../lib/npm-command.mjs";
42
+ import { prependedPathEnvironment, resolveCommandDirectory, resolveNpmCommandInvocation, resolvePiCommandInvocation } from "../lib/npm-command.mjs";
43
43
  import {
44
44
  GIT_WORKFLOW_DEFAULT_VARIANTS,
45
45
  GIT_WORKFLOW_DELIVERY_MODES,
@@ -110,6 +110,7 @@ import {
110
110
  removeGitWorktree,
111
111
  } from "../lib/git-worktrees.mjs";
112
112
  import { createGitLiveWatcher } from "../lib/git-live-watcher.mjs";
113
+ import { createWorkspaceFilesLiveWatcher } from "../lib/workspace-files-live-watcher.mjs";
113
114
  import {
114
115
  gitMessageArtifactPairReadiness,
115
116
  readStableGitMessageArtifactPair,
@@ -154,6 +155,9 @@ const WEBUI_SUBAGENT_GATE_LIMIT = 32;
154
155
  const WEBUI_SUBAGENT_GATE_ATTEMPT_LIMIT = 100;
155
156
  const WEBUI_SUBAGENT_OUTPUT_LINE_LIMIT = 120;
156
157
  const WEBUI_SUBAGENT_OUTPUT_LINE_LENGTH = 1000;
158
+ const WEBUI_SUBAGENT_TELEMETRY_TOKEN_LIMIT = 1_000_000_000;
159
+ const WEBUI_SUBAGENT_TELEMETRY_CONTEXT_WINDOW_LIMIT = 16_000_000;
160
+ const WEBUI_SUBAGENT_TELEMETRY_SPEED_LIMIT = 1_000_000;
157
161
  const PI_CODING_AGENT_PACKAGE = "@earendil-works/pi-coding-agent";
158
162
  const WEBUI_PACKAGE = packageJson.name || "@firstpick/pi-package-webui";
159
163
  const PI_LATEST_VERSION_URL = process.env.PI_WEBUI_PI_LATEST_VERSION_URL || "https://pi.dev/api/latest-version";
@@ -250,6 +254,7 @@ const UPLOAD_TEMP_TTL_MS = 24 * 60 * 60 * 1000;
250
254
  const NATIVE_EXPORT_TEMP_TTL_MS = 60 * 60 * 1000;
251
255
  const TEMP_ARTIFACT_SWEEP_INTERVAL_MS = 60 * 60 * 1000;
252
256
  const AUTO_TAB_TITLE_MAX_LENGTH = 44;
257
+ const AUTO_TAB_TITLE_DISPLAY_MAX_LENGTH = 160;
253
258
  const AUTO_TAB_TITLE_WORD_LIMIT = 8;
254
259
  const AUTO_TAB_TITLE_STOP_WORDS = new Set([
255
260
  "a",
@@ -1269,12 +1274,33 @@ function sendRemoteAuthRequired(req, res, url) {
1269
1274
  sendJson(res, 401, { ok: false, error: "Remote PIN required", remoteAuthRequired: true }, { "www-authenticate": "PiRemotePin" });
1270
1275
  }
1271
1276
 
1277
+ // Browser SSE does not have a replay queue. A client that stops draining is
1278
+ // therefore removed on the first backpressure signal instead of accumulating
1279
+ // an unbounded queue or selectively dropping/reordering semantic events.
1280
+ // Reconnection remains authoritative through the existing tab/state refresh.
1281
+ function evictSlowSseClient(client) {
1282
+ if (!client || client.evicted) return;
1283
+ client.evicted = true;
1284
+ client.tab?.sseClients?.delete(client);
1285
+ try {
1286
+ client.res?.destroy();
1287
+ } catch {
1288
+ // A closed browser socket needs no further cleanup.
1289
+ }
1290
+ }
1291
+
1272
1292
  function sendSse(client, event) {
1273
1293
  const res = client?.res || client;
1274
1294
  const payload = encodeBrowserSseEvent(event, { outputMode: client?.activeMode || OUTPUT_MODE_NORMAL });
1275
- if (payload === undefined) return false;
1276
- res.write(`data: ${payload}\n\n`);
1277
- return true;
1295
+ if (payload === undefined || !res || res.destroyed || client?.evicted) return false;
1296
+ try {
1297
+ const accepted = res.write(`data: ${payload}\n\n`);
1298
+ if (!accepted && client?.res) evictSlowSseClient(client);
1299
+ return accepted;
1300
+ } catch {
1301
+ if (client?.res) evictSlowSseClient(client);
1302
+ return false;
1303
+ }
1278
1304
  }
1279
1305
 
1280
1306
  function rpcSuccess(command, data = {}) {
@@ -1621,7 +1647,7 @@ function generatedTabTitleFromPrompt(message) {
1621
1647
  const words = cleaned.split(/\s+/).map((word) => word.replace(/^[^\w]+|[^\w]+$/g, "")).filter(Boolean);
1622
1648
  const meaningfulWords = words.filter((word) => !AUTO_TAB_TITLE_STOP_WORDS.has(word.toLowerCase()));
1623
1649
  const selectedWords = (meaningfulWords.length >= 3 ? meaningfulWords : words).slice(0, AUTO_TAB_TITLE_WORD_LIMIT);
1624
- return truncateTabTitle(titleCaseTabTitle(selectedWords.join(" ")));
1650
+ return truncateTabTitle(titleCaseTabTitle(selectedWords.join(" ")), AUTO_TAB_TITLE_DISPLAY_MAX_LENGTH);
1625
1651
  }
1626
1652
 
1627
1653
  function uniqueTabTitle(title, currentTab, maxLength = AUTO_TAB_TITLE_MAX_LENGTH) {
@@ -5511,6 +5537,117 @@ function normalizeGitRelativePath(root, relativePath) {
5511
5537
  return path.relative(root, resolved).split(path.sep).join("/");
5512
5538
  }
5513
5539
 
5540
+ const GITIGNORE_MAX_BYTES = 5 * 1024 * 1024;
5541
+ const gitignoreMutationQueues = new Map();
5542
+
5543
+ function serializeGitignoreMutation(root, mutation) {
5544
+ const previous = gitignoreMutationQueues.get(root) || Promise.resolve();
5545
+ const current = previous.catch(() => {}).then(mutation);
5546
+ gitignoreMutationQueues.set(root, current);
5547
+ return current.finally(() => {
5548
+ if (gitignoreMutationQueues.get(root) === current) gitignoreMutationQueues.delete(root);
5549
+ });
5550
+ }
5551
+
5552
+ function gitignoreEntryForTarget(root, requestedPath, kind) {
5553
+ if (kind !== "file" && kind !== "folder") throw makeHttpError(400, "Gitignore target kind must be file or folder");
5554
+ if (typeof requestedPath !== "string" || requestedPath.length === 0) throw makeHttpError(400, "Gitignore target path is required");
5555
+ if (/[\0-\x1f\x7f]/.test(requestedPath)) throw makeHttpError(400, "Gitignore target path cannot contain control characters");
5556
+
5557
+ const slashPath = requestedPath.replace(/\\/g, "/");
5558
+ if (path.posix.isAbsolute(slashPath) || path.win32.isAbsolute(requestedPath) || /^[A-Za-z]:/.test(requestedPath)) {
5559
+ throw makeHttpError(400, "Gitignore target path must be repository-relative");
5560
+ }
5561
+ const segments = slashPath.split("/").filter(Boolean);
5562
+ if (!segments.length || segments.some((segment) => segment === "." || segment === "..")) {
5563
+ throw makeHttpError(400, "Gitignore target path cannot be the repository root or contain traversal segments");
5564
+ }
5565
+
5566
+ const normalized = segments.join("/");
5567
+ const target = path.resolve(root, ...segments);
5568
+ const relative = path.relative(root, target);
5569
+ if (!relative || relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
5570
+ throw makeHttpError(400, "Gitignore target path must stay inside the repository");
5571
+ }
5572
+ const escaped = normalized.replace(/([*?\[\] ])/g, "\\$1");
5573
+ return { path: normalized, kind, entry: `/${escaped}${kind === "folder" ? "/" : ""}` };
5574
+ }
5575
+
5576
+ function sameFileIdentity(first, second) {
5577
+ return first?.dev === second?.dev && first?.ino === second?.ino;
5578
+ }
5579
+
5580
+ function gitignoreHasExactEntry(content, entry) {
5581
+ const existing = content.toString("latin1").split(/\r\n|\n|\r/);
5582
+ return existing.includes(Buffer.from(entry, "utf8").toString("latin1"));
5583
+ }
5584
+
5585
+ async function appendGitignoreEntry(root, entry) {
5586
+ const target = path.join(root, ".gitignore");
5587
+ for (let attempt = 0; attempt < 2; attempt++) {
5588
+ let before;
5589
+ try {
5590
+ before = await lstat(target);
5591
+ } catch (error) {
5592
+ if (error?.code !== "ENOENT") throw error;
5593
+ before = null;
5594
+ }
5595
+
5596
+ if (!before) {
5597
+ let handle;
5598
+ try {
5599
+ handle = await open(target, fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_EXCL | (fsConstants.O_NOFOLLOW || 0), 0o666);
5600
+ await handle.writeFile(`${entry}\n`, "utf8");
5601
+ return true;
5602
+ } catch (error) {
5603
+ if (error?.code === "EEXIST" && attempt === 0) continue;
5604
+ throw error;
5605
+ } finally {
5606
+ await handle?.close();
5607
+ }
5608
+ }
5609
+
5610
+ if (before.isSymbolicLink() || !before.isFile()) throw makeHttpError(409, "Repository .gitignore must be a regular file and cannot be a symbolic link");
5611
+ if (before.nlink !== 1) throw makeHttpError(409, "Repository .gitignore must have exactly one hard link; replace linked copies with a regular file before retrying");
5612
+
5613
+ let handle;
5614
+ try {
5615
+ handle = await open(target, fsConstants.O_RDWR | fsConstants.O_APPEND | (fsConstants.O_NOFOLLOW || 0));
5616
+ const opened = await handle.stat();
5617
+ if (!opened.isFile() || !sameFileIdentity(before, opened)) throw makeHttpError(409, "Repository .gitignore changed while it was being opened");
5618
+ if (opened.nlink !== 1) throw makeHttpError(409, "Repository .gitignore must have exactly one hard link; replace linked copies with a regular file before retrying");
5619
+ if (opened.size > GITIGNORE_MAX_BYTES) throw makeHttpError(409, `Repository .gitignore exceeds the ${formatBytes(GITIGNORE_MAX_BYTES)} safe modification limit`);
5620
+ const content = await handle.readFile();
5621
+ if (gitignoreHasExactEntry(content, entry)) return false;
5622
+ const newline = content.includes(Buffer.from("\r\n")) ? "\r\n" : "\n";
5623
+ const lastByte = content.length ? content[content.length - 1] : null;
5624
+ const separator = content.length && lastByte !== 0x0a && lastByte !== 0x0d ? newline : "";
5625
+ await handle.writeFile(`${separator}${entry}${newline}`, "utf8");
5626
+ return true;
5627
+ } catch (error) {
5628
+ if (error?.code === "ENOENT" && attempt === 0) continue;
5629
+ if (error?.code === "ELOOP") throw makeHttpError(409, "Repository .gitignore cannot be a symbolic link");
5630
+ throw error;
5631
+ } finally {
5632
+ await handle?.close();
5633
+ }
5634
+ }
5635
+ }
5636
+
5637
+ async function addGitignoreEntry(cwd, body = {}) {
5638
+ try {
5639
+ const root = await realpath(await getGitRoot(cwd));
5640
+ const target = gitignoreEntryForTarget(root, body.path, body.kind);
5641
+ const added = await serializeGitignoreMutation(root, () => appendGitignoreEntry(root, target.entry));
5642
+ return { root, ...target, added, changes: await readGitChanges(root) };
5643
+ } catch (error) {
5644
+ if (error?.statusCode) throw error;
5645
+ const wrapped = makeHttpError(500, formatCliError(error));
5646
+ if (error?.code) wrapped.code = error.code;
5647
+ throw wrapped;
5648
+ }
5649
+ }
5650
+
5514
5651
  async function readGitUntrackedEntry(root, file, { maxBytes = Number.POSITIVE_INFINITY } = {}) {
5515
5652
  const normalized = normalizeGitRelativePath(root, file);
5516
5653
  const filePath = resolveGitRelativePath(root, normalized);
@@ -7771,7 +7908,7 @@ async function readBundledThemes() {
7771
7908
  function normalizeStaticPath(urlPath) {
7772
7909
  if (urlPath === "/") return "index.html";
7773
7910
  const name = urlPath.startsWith("/") ? urlPath.slice(1) : urlPath;
7774
- 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;
7911
+ if (!["index.html", "app.js", "mobile-shell-state.mjs", "issue-wizard-state.mjs", "issue-bot-client.mjs", "fast-output-live.mjs", "transcript-renderer.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;
7775
7912
  return name;
7776
7913
  }
7777
7914
 
@@ -8361,17 +8498,17 @@ async function resolvedPiCliScript() {
8361
8498
  return "";
8362
8499
  }
8363
8500
 
8501
+ function resolveSelectedPiCommand(piArgs) {
8502
+ const invocation = resolvePiCommandInvocation(options.piBin, piArgs);
8503
+ return {
8504
+ command: invocation.command,
8505
+ args: invocation.args,
8506
+ displayCommand: formatCommandForDisplay(invocation.command, invocation.args),
8507
+ };
8508
+ }
8509
+
8364
8510
  async function resolvePiCommand(piArgs) {
8365
- if (options.piBinExplicit) {
8366
- if (isNodeScriptCommand(options.piBin)) {
8367
- return {
8368
- command: process.execPath,
8369
- args: [options.piBin, ...piArgs],
8370
- displayCommand: `${process.execPath} ${options.piBin} ${piArgs.join(" ")}`,
8371
- };
8372
- }
8373
- return { command: options.piBin, args: piArgs, displayCommand: `${options.piBin} ${piArgs.join(" ")}` };
8374
- }
8511
+ if (options.piBinExplicit) return resolveSelectedPiCommand(piArgs);
8375
8512
 
8376
8513
  const bundledCli = await resolvedPiCliScript();
8377
8514
  if (bundledCli) {
@@ -8382,7 +8519,7 @@ async function resolvePiCommand(piArgs) {
8382
8519
  };
8383
8520
  }
8384
8521
 
8385
- return { command: options.piBin, args: piArgs, displayCommand: `${options.piBin} ${piArgs.join(" ")}` };
8522
+ return resolveSelectedPiCommand(piArgs);
8386
8523
  }
8387
8524
 
8388
8525
  const tabs = new Map();
@@ -8660,6 +8797,10 @@ function createTabActivity(now = new Date().toISOString()) {
8660
8797
  status: "idle",
8661
8798
  isWorking: false,
8662
8799
  runStarted: false,
8800
+ // Opaque server-issued identity for the current/recent parent turn. It is
8801
+ // deliberately separate from subagent/workflow IDs and contains no prompt,
8802
+ // title, cwd, or user-derived data.
8803
+ runId: null,
8663
8804
  completionSerial: 0,
8664
8805
  lastChangedAt: now,
8665
8806
  lastStartedAt: null,
@@ -9029,8 +9170,10 @@ function queueMutationRequest(body) {
9029
9170
  } else if (request.operation.type === "move") {
9030
9171
  request.operation.from = queueMutationIndex(operation.from, "operation.from");
9031
9172
  request.operation.to = queueMutationIndex(operation.to, "operation.to");
9173
+ } else if (request.operation.type === "delete") {
9174
+ request.operation.index = queueMutationIndex(operation.index, "operation.index");
9032
9175
  } else {
9033
- throw makeHttpError(400, "Queue mutation operation type must be edit or move");
9176
+ throw makeHttpError(400, "Queue mutation operation type must be edit, move, or delete");
9034
9177
  }
9035
9178
  if (source === "webui-compaction") {
9036
9179
  if (!Number.isSafeInteger(body.revision) || body.revision < 0) throw makeHttpError(400, "Compaction queue mutation requires a non-negative revision");
@@ -9116,13 +9259,18 @@ function mutateCompactionFollowUpQueue(tab, request) {
9116
9259
  if (operation.type === "edit") {
9117
9260
  if (operation.index >= slots.length || current.followUp[operation.index] !== operation.expectedText) return failed("invalid-request");
9118
9261
  queue[slots[operation.index]].command.message = operation.text;
9119
- } else {
9262
+ } else if (operation.type === "move") {
9120
9263
  if (operation.from >= slots.length || operation.to >= slots.length || operation.from === operation.to
9121
9264
  || current.followUp[operation.from] !== operation.expectedText) return failed("invalid-request");
9122
9265
  const followUps = slots.map((index) => queue[index]);
9123
9266
  const [moved] = followUps.splice(operation.from, 1);
9124
9267
  followUps.splice(operation.to, 0, moved);
9125
9268
  slots.forEach((slot, index) => { queue[slot] = followUps[index]; });
9269
+ } else if (operation.type === "delete") {
9270
+ if (operation.index >= slots.length || current.followUp[operation.index] !== operation.expectedText) return failed("invalid-request");
9271
+ queue.splice(slots[operation.index], 1);
9272
+ } else {
9273
+ return failed("invalid-request");
9126
9274
  }
9127
9275
 
9128
9276
  advanceCompactionQueueRevision(tab);
@@ -9394,6 +9542,7 @@ async function cancelPendingExtensionUiRequests(tab) {
9394
9542
 
9395
9543
  function markTabWorking(tab, timestamp = new Date().toISOString(), { runStarted = false } = {}) {
9396
9544
  const activity = tab.activity || createTabActivity(timestamp);
9545
+ if (!activity.isWorking || !activity.runId) activity.runId = randomUUID();
9397
9546
  activity.status = "working";
9398
9547
  activity.isWorking = true;
9399
9548
  activity.runStarted = activity.runStarted === true || runStarted === true;
@@ -9413,10 +9562,24 @@ function markTabDone(tab, timestamp = new Date().toISOString()) {
9413
9562
  tab.activity = activity;
9414
9563
  }
9415
9564
 
9565
+ function markTabFailed(tab, timestamp = new Date().toISOString()) {
9566
+ const activity = tab.activity || createTabActivity(timestamp);
9567
+ activity.status = "failed";
9568
+ activity.isWorking = false;
9569
+ activity.runStarted = false;
9570
+ activity.completionSerial = (Number(activity.completionSerial) || 0) + 1;
9571
+ activity.lastCompletedAt = timestamp;
9572
+ activity.lastChangedAt = timestamp;
9573
+ tab.activity = activity;
9574
+ }
9575
+
9416
9576
  function markTabIdle(tab, timestamp = new Date().toISOString()) {
9417
9577
  const activity = tab.activity || createTabActivity(timestamp);
9418
9578
  activity.status = "idle";
9419
9579
  activity.isWorking = false;
9580
+ // An idle pre-start operation never became a parent turn. Completed turns
9581
+ // retain their opaque ID so a later Activity view can resolve recent work.
9582
+ if (!activity.runStarted) activity.runId = null;
9420
9583
  activity.runStarted = false;
9421
9584
  activity.lastChangedAt = timestamp;
9422
9585
  tab.activity = activity;
@@ -9486,19 +9649,30 @@ function updateTabActivityFromEvent(tab, event) {
9486
9649
  switch (event?.type) {
9487
9650
  case "agent_start":
9488
9651
  patchTabState(tab, { isStreaming: true });
9652
+ tab.pendingTurnFailure = false;
9489
9653
  markTabWorking(tab, timestamp, { runStarted: true });
9490
9654
  break;
9491
9655
  case "compaction_start":
9492
9656
  patchTabState(tab, { isCompacting: true });
9493
9657
  markTabWorking(tab, timestamp);
9494
9658
  break;
9495
- case "agent_end":
9659
+ case "agent_end": {
9496
9660
  // A low-level run ended, but Pi may still retry, compact, or process a follow-up.
9661
+ const assistant = Array.isArray(event.messages) ? event.messages.findLast((item) => item?.role === "assistant") : null;
9662
+ if (event.willRetry === true) tab.pendingTurnFailure = false;
9663
+ else if (assistant?.stopReason === "error") tab.pendingTurnFailure = true;
9664
+ break;
9665
+ }
9666
+ case "message_end":
9667
+ if (event.message?.role === "assistant" && event.message.stopReason === "error") tab.pendingTurnFailure = true;
9497
9668
  break;
9498
9669
  case "agent_settled":
9499
9670
  patchTabState(tab, { isStreaming: false });
9500
- if (tab.activity?.runStarted) markTabDone(tab, timestamp);
9501
- else if (tab.activity?.isWorking) markTabIdle(tab, timestamp);
9671
+ if (tab.activity?.runStarted) {
9672
+ if (tab.pendingTurnFailure) markTabFailed(tab, timestamp);
9673
+ else markTabDone(tab, timestamp);
9674
+ } else if (tab.activity?.isWorking) markTabIdle(tab, timestamp);
9675
+ tab.pendingTurnFailure = false;
9502
9676
  break;
9503
9677
  case "compaction_end":
9504
9678
  patchTabState(tab, { isCompacting: false });
@@ -9508,8 +9682,14 @@ function updateTabActivityFromEvent(tab, event) {
9508
9682
  patchTabState(tab, { pendingMessageCount: (event.steering?.length || 0) + (event.followUp?.length || 0) });
9509
9683
  break;
9510
9684
  case "pi_process_exit":
9685
+ if (tab.activity?.runStarted && (Number(event.code) !== 0 || event.signal)) markTabFailed(tab, timestamp);
9686
+ else markTabIdle(tab, timestamp);
9687
+ tab.pendingTurnFailure = false;
9688
+ break;
9511
9689
  case "pi_process_error":
9512
- markTabIdle(tab, timestamp);
9690
+ if (tab.activity?.runStarted) markTabFailed(tab, timestamp);
9691
+ else markTabIdle(tab, timestamp);
9692
+ tab.pendingTurnFailure = false;
9513
9693
  break;
9514
9694
  case "response":
9515
9695
  if (event.command === "get_state" && event.success !== false) {
@@ -9591,6 +9771,8 @@ function createTabRecord({ id, index, title, titleSource, conversationStarted, c
9591
9771
  extensionStatuses: new Map(),
9592
9772
  extensionWidgets: new Map(),
9593
9773
  webuiSubagents: null,
9774
+ subagentDisplayTitle: undefined,
9775
+ subagentDisplayTitlePromise: undefined,
9594
9776
  webuiHelperRequests: new Map(),
9595
9777
  webuiHelperResponseIds: new Set(),
9596
9778
  bashQueue: [],
@@ -9602,6 +9784,7 @@ function createTabRecord({ id, index, title, titleSource, conversationStarted, c
9602
9784
  rpc,
9603
9785
  rpcUnsubscribe: undefined,
9604
9786
  sseClients: new Set(),
9787
+ browserPromptRequests: new Map(),
9605
9788
  };
9606
9789
  resetNaturalConversationMode(tab);
9607
9790
  resetCodexFastMode(tab);
@@ -9639,6 +9822,7 @@ async function createTab({ id: requestedId, index, title, titleSource, conversat
9639
9822
 
9640
9823
  attachRpcToTab(tab, rpc);
9641
9824
  tabs.set(id, tab);
9825
+ workspaceFilesLiveWatcher.subscribe(tab.id, tab.cwd);
9642
9826
  try {
9643
9827
  if (rpc instanceof SupervisorPiRpcProcess) {
9644
9828
  const snapshot = await rpcSupervisor.createTab({
@@ -9656,6 +9840,7 @@ async function createTab({ id: requestedId, index, title, titleSource, conversat
9656
9840
  tab.rpcUnsubscribe?.();
9657
9841
  rpc.dispose?.();
9658
9842
  gitLiveWatcher.unsubscribe(id);
9843
+ workspaceFilesLiveWatcher.unsubscribe(id);
9659
9844
  tabs.delete(id);
9660
9845
  throw new Error(`Pi RPC process failed while starting ${tabTitle}: ${sanitizeError(error)}`);
9661
9846
  }
@@ -9701,12 +9886,14 @@ async function hydrateManagedTabs(snapshot) {
9701
9886
  });
9702
9887
  attachRpcToTab(tab, rpc);
9703
9888
  tabs.set(tab.id, tab);
9889
+ workspaceFilesLiveWatcher.subscribe(tab.id, tab.cwd);
9704
9890
  hydrated.push(tab);
9705
9891
  }
9706
9892
  } catch (error) {
9707
9893
  for (const tab of hydrated) {
9708
9894
  tab.rpcUnsubscribe?.();
9709
9895
  tab.rpc.dispose?.();
9896
+ workspaceFilesLiveWatcher.unsubscribe(tab.id);
9710
9897
  tabs.delete(tab.id);
9711
9898
  }
9712
9899
  throw error;
@@ -9748,16 +9935,37 @@ function listTabs() {
9748
9935
  return [...tabs.values()].map(tabMeta);
9749
9936
  }
9750
9937
 
9751
- function webuiSubagentsData() {
9938
+ async function resolveSubagentDisplayTitle(tab) {
9939
+ const fallback = tab?.title || "";
9940
+ if (!tab || tab.titleSource !== "auto") return fallback;
9941
+ if (tab.subagentDisplayTitle) return tab.subagentDisplayTitle;
9942
+ if (!tab.subagentDisplayTitlePromise) {
9943
+ tab.subagentDisplayTitlePromise = safeRpcResponse(tab, { type: "get_messages" }, TAB_ACTIVITY_STATE_RECONCILE_TIMEOUT_MS)
9944
+ .then((response) => {
9945
+ const firstUserMessage = (Array.isArray(response.data?.messages) ? response.data.messages : []).find((message) => message?.role === "user");
9946
+ const title = generatedTabTitleFromPrompt(extractSessionTextContent(firstUserMessage?.content)) || fallback;
9947
+ tab.subagentDisplayTitle = title;
9948
+ return title;
9949
+ })
9950
+ .catch(() => {
9951
+ tab.subagentDisplayTitle = fallback;
9952
+ return fallback;
9953
+ });
9954
+ }
9955
+ return tab.subagentDisplayTitlePromise;
9956
+ }
9957
+
9958
+ async function webuiSubagentsData() {
9752
9959
  const sortedTabs = [...tabs.values()].sort((a, b) => a.index - b.index || a.title.localeCompare(b.title));
9753
- const tabSummaries = sortedTabs.map((tab) => {
9960
+ const tabSummaries = await Promise.all(sortedTabs.map(async (tab) => {
9754
9961
  const status = tab.webuiSubagents || { version: 1, available: false, updatedAt: null, receivedAt: null, runs: [], gates: [] };
9755
9962
  const runs = Array.isArray(status.runs) ? status.runs : [];
9756
9963
  const gates = Array.isArray(status.gates) ? status.gates : [];
9964
+ const tabTitle = runs.length || gates.length ? await resolveSubagentDisplayTitle(tab) : tab.title;
9757
9965
  return {
9758
9966
  tabId: tab.id,
9759
9967
  tabIndex: tab.index,
9760
- tabTitle: tab.title,
9968
+ tabTitle,
9761
9969
  cwd: tab.cwd,
9762
9970
  sessionName: normalizeWebuiSubagentText(tab.lastState?.sessionName || tab.title, 160),
9763
9971
  sessionFile: tabRestorableSessionFile(tab) || null,
@@ -9772,7 +9980,7 @@ function webuiSubagentsData() {
9772
9980
  runningAgents: runs.reduce((count, run) => count + run.agents.filter((agent) => agent.status === "running").length, 0),
9773
9981
  gateCount: gates.length,
9774
9982
  };
9775
- });
9983
+ }));
9776
9984
  return {
9777
9985
  version: 1,
9778
9986
  updatedAt: Date.now(),
@@ -9859,6 +10067,29 @@ function normalizeWebuiSubagentTranscript(value) {
9859
10067
  return messages;
9860
10068
  }
9861
10069
 
10070
+ function normalizeWebuiSubagentTelemetry(value, fallback = {}) {
10071
+ const telemetry = value && typeof value === "object" && !Array.isArray(value) ? value : null;
10072
+ const number = (candidate, limit = WEBUI_SUBAGENT_TELEMETRY_TOKEN_LIMIT) => (
10073
+ typeof candidate === "number" && Number.isFinite(candidate) && candidate >= 0 && candidate <= limit ? candidate : null
10074
+ );
10075
+ const model = normalizeWebuiSubagentText(telemetry?.model, 240)
10076
+ || normalizeWebuiSubagentText(fallback.model, 240)
10077
+ || null;
10078
+ const effort = normalizeWebuiSubagentText(telemetry?.effort, 40)
10079
+ || normalizeWebuiSubagentText(fallback.effort, 40)
10080
+ || null;
10081
+ return {
10082
+ promptInjectionTokens: number(telemetry?.promptInjectionTokens),
10083
+ inputTokens: number(telemetry?.inputTokens),
10084
+ outputTokens: number(telemetry?.outputTokens),
10085
+ tokenSpeed: number(telemetry?.tokenSpeed, WEBUI_SUBAGENT_TELEMETRY_SPEED_LIMIT),
10086
+ contextTokens: number(telemetry?.contextTokens),
10087
+ contextWindow: number(telemetry?.contextWindow, WEBUI_SUBAGENT_TELEMETRY_CONTEXT_WINDOW_LIMIT),
10088
+ model,
10089
+ effort,
10090
+ };
10091
+ }
10092
+
9862
10093
  function normalizeWebuiSubagentOutput(value, selection) {
9863
10094
  if (!value || typeof value !== "object" || value.version !== 1) throw makeHttpError(502, "Invalid subagent output response from Web UI helper");
9864
10095
  const rawAgent = value.agent && typeof value.agent === "object" ? value.agent : {};
@@ -9893,6 +10124,10 @@ function normalizeWebuiSubagentOutput(value, selection) {
9893
10124
  tokens: Number.isFinite(rawAgent.tokens) ? rawAgent.tokens : undefined,
9894
10125
  model: normalizeWebuiSubagentText(rawAgent.model, 240) || selection.agent.model || undefined,
9895
10126
  thinking: normalizeWebuiSubagentText(rawAgent.thinking, 40) || selection.agent.thinking || undefined,
10127
+ telemetry: normalizeWebuiSubagentTelemetry(rawAgent.telemetry, {
10128
+ model: normalizeWebuiSubagentText(rawAgent.model, 240) || selection.agent.model,
10129
+ effort: normalizeWebuiSubagentText(rawAgent.thinking, 40) || selection.agent.thinking,
10130
+ }),
9896
10131
  recentTools,
9897
10132
  recentOutput,
9898
10133
  transcript,
@@ -10243,31 +10478,37 @@ async function piUpdateCommandSupportsAll(command) {
10243
10478
  async function resolvePiUpdateCommands({ all = false } = {}) {
10244
10479
  let resolveCommand;
10245
10480
  let labelPrefix = "";
10481
+ let useBundledPi = false;
10246
10482
 
10247
10483
  if (options.piBinExplicit) {
10248
10484
  resolveCommand = (args) => resolvePiCommand(args);
10249
10485
  } else {
10250
- const pathPi = await runCommand(options.piBin, ["--version"], { timeoutMs: 3000, maxOutputLength: 4000 });
10486
+ const selectedPi = resolveSelectedPiCommand(["--version"]);
10487
+ const pathPi = await runCommand(selectedPi.command, selectedPi.args, { timeoutMs: 3000, maxOutputLength: 4000 });
10251
10488
  if (pathPi.exitCode === 0 && !pathPi.timedOut && !pathPi.error) {
10252
- resolveCommand = async (args) => ({
10253
- command: options.piBin,
10254
- args,
10255
- displayCommand: formatCommandForDisplay(options.piBin, args),
10256
- });
10489
+ resolveCommand = async (args) => resolveSelectedPiCommand(args);
10257
10490
  } else {
10258
10491
  resolveCommand = (args) => resolvePiCommand(args);
10259
10492
  labelPrefix = "bundled ";
10493
+ useBundledPi = true;
10260
10494
  }
10261
10495
  }
10262
10496
 
10263
10497
  const supportsAll = all && await piUpdateCommandSupportsAll(await resolveCommand(["update", "--help"]));
10264
10498
  const steps = piUpdateCommandSteps({ all, supportsAll });
10265
- return Promise.all(steps.map(async (step) => ({
10266
- ...(await resolveCommand(step.args)),
10267
- label: `${labelPrefix}${step.label}`,
10268
- timeoutMs: PI_UPDATE_TIMEOUT_MS,
10269
- maxOutputLength: PI_UPDATE_OUTPUT_MAX_CHARS,
10270
- })));
10499
+ return Promise.all(steps.map(async (step) => {
10500
+ const command = await resolveCommand(step.args);
10501
+ const selectedPiDirectory = useBundledPi || isNodeScriptCommand(options.piBin) ? "" : resolveCommandDirectory(options.piBin);
10502
+ const piInstallDirectory = selectedPiDirectory || resolveCommandDirectory(command.command);
10503
+ return {
10504
+ ...command,
10505
+ label: `${labelPrefix}${step.label}`,
10506
+ timeoutMs: PI_UPDATE_TIMEOUT_MS,
10507
+ maxOutputLength: PI_UPDATE_OUTPUT_MAX_CHARS,
10508
+ piInstallDirectory,
10509
+ env: piInstallDirectory ? prependedPathEnvironment(piInstallDirectory) : undefined,
10510
+ };
10511
+ }));
10271
10512
  }
10272
10513
 
10273
10514
  function packageNodeModulesPath(nodeModulesRoot, packageName) {
@@ -10345,8 +10586,8 @@ function packageInstallSpecs(packageNames) {
10345
10586
  return packageNames.map((packageName) => `${packageName}@latest`);
10346
10587
  }
10347
10588
 
10348
- function resolvedNpmCommand(args) {
10349
- const invocation = resolveNpmCommandInvocation(args);
10589
+ function resolvedNpmCommand(args, runtime = {}) {
10590
+ const invocation = resolveNpmCommandInvocation(args, runtime);
10350
10591
  return {
10351
10592
  command: invocation.command,
10352
10593
  args: invocation.args,
@@ -10354,9 +10595,9 @@ function resolvedNpmCommand(args) {
10354
10595
  };
10355
10596
  }
10356
10597
 
10357
- function npmPrefixUpdateTask(label, installRoot, packageNames) {
10598
+ function npmPrefixUpdateTask(label, installRoot, packageNames, npmRuntime = {}) {
10358
10599
  if (!packageNames.length) return null;
10359
- const npmCommand = resolvedNpmCommand(["install", "--prefix", installRoot, "--ignore-scripts", "--min-release-age=0", ...packageInstallSpecs(packageNames)]);
10600
+ const npmCommand = resolvedNpmCommand(["install", "--prefix", installRoot, "--ignore-scripts", "--min-release-age=0", ...packageInstallSpecs(packageNames)], npmRuntime);
10360
10601
  return {
10361
10602
  label,
10362
10603
  command: npmCommand.command,
@@ -10366,31 +10607,31 @@ function npmPrefixUpdateTask(label, installRoot, packageNames) {
10366
10607
  };
10367
10608
  }
10368
10609
 
10369
- async function currentWebuiPackageUpdateTask() {
10610
+ async function currentWebuiPackageUpdateTask(npmRuntime = {}) {
10370
10611
  const sourceCheckout = webuiDevServer || !String(packageRoot).split(path.sep).includes("node_modules");
10371
10612
  if (sourceCheckout) {
10372
10613
  const manifest = await readJsonFileIfExists(path.join(packageRoot, "package.json"));
10373
10614
  const packages = declaredWebuiPiPackageNames(manifest);
10374
- return npmPrefixUpdateTask("current Web UI checkout package dependencies", packageRoot, packages);
10615
+ return npmPrefixUpdateTask("current Web UI checkout package dependencies", packageRoot, packages, npmRuntime);
10375
10616
  }
10376
10617
 
10377
10618
  const installRoot = nodeModulesParentForPackageRoot(packageRoot);
10378
10619
  const packages = await packagesPresentInInstallPrefix(installRoot);
10379
- return npmPrefixUpdateTask("current Web UI install root", installRoot, packages);
10620
+ return npmPrefixUpdateTask("current Web UI install root", installRoot, packages, npmRuntime);
10380
10621
  }
10381
10622
 
10382
- async function agentPackageRootUpdateTask() {
10623
+ async function agentPackageRootUpdateTask(npmRuntime = {}) {
10383
10624
  const installRoot = configuredAgentNpmRoot();
10384
10625
  const packages = await packagesPresentInInstallPrefix(installRoot);
10385
- return npmPrefixUpdateTask("Pi agent npm package root", installRoot, packages);
10626
+ return npmPrefixUpdateTask("Pi agent npm package root", installRoot, packages, npmRuntime);
10386
10627
  }
10387
10628
 
10388
- async function optionalFeatureInstallRootUpdateTask() {
10629
+ async function optionalFeatureInstallRootUpdateTask(npmRuntime = {}) {
10389
10630
  const configuredRoot = process.env[OPTIONAL_FEATURE_INSTALL_ROOT_ENV];
10390
10631
  if (!configuredRoot) return null;
10391
10632
  const installRoot = path.resolve(expandUserPath(configuredRoot));
10392
10633
  const packages = await packagesPresentInInstallPrefix(installRoot);
10393
- return npmPrefixUpdateTask("configured optional-feature npm root", installRoot, packages);
10634
+ return npmPrefixUpdateTask("configured optional-feature npm root", installRoot, packages, npmRuntime);
10394
10635
  }
10395
10636
 
10396
10637
  function activeProjectPackageRoots() {
@@ -10405,28 +10646,28 @@ function activeProjectPackageRoots() {
10405
10646
  return [...roots].sort();
10406
10647
  }
10407
10648
 
10408
- async function projectPackageRootUpdateTasks() {
10649
+ async function projectPackageRootUpdateTasks(npmRuntime = {}) {
10409
10650
  const tasks = [];
10410
10651
  for (const installRoot of activeProjectPackageRoots()) {
10411
10652
  const packages = await packagesPresentInInstallPrefix(installRoot);
10412
- const task = npmPrefixUpdateTask(`project Pi package root (${displayPath(path.dirname(installRoot))})`, installRoot, packages);
10653
+ const task = npmPrefixUpdateTask(`project Pi package root (${displayPath(path.dirname(installRoot))})`, installRoot, packages, npmRuntime);
10413
10654
  if (task) tasks.push(task);
10414
10655
  }
10415
10656
  return tasks;
10416
10657
  }
10417
10658
 
10418
- async function npmGlobalNodeModulesRoot() {
10419
- const npmCommand = resolvedNpmCommand(["root", "-g"]);
10659
+ async function npmGlobalNodeModulesRoot(npmRuntime = {}) {
10660
+ const npmCommand = resolvedNpmCommand(["root", "-g"], npmRuntime);
10420
10661
  const result = await runCommand(npmCommand.command, npmCommand.args, { timeoutMs: 5000, maxOutputLength: 8000 });
10421
10662
  if (result.exitCode !== 0 || result.timedOut || result.error) return null;
10422
10663
  return result.stdout.trim().split(/\r?\n/).filter(Boolean).at(-1) || null;
10423
10664
  }
10424
10665
 
10425
- async function npmGlobalPackageRootUpdateTask() {
10426
- const nodeModulesRoot = await npmGlobalNodeModulesRoot();
10666
+ async function npmGlobalPackageRootUpdateTask(npmRuntime = {}) {
10667
+ const nodeModulesRoot = await npmGlobalNodeModulesRoot(npmRuntime);
10427
10668
  const packages = await packagesPresentInNodeModulesRoot(nodeModulesRoot);
10428
10669
  if (!packages.length) return null;
10429
- const npmCommand = resolvedNpmCommand(["install", "-g", "--ignore-scripts", "--min-release-age=0", ...packageInstallSpecs(packages)]);
10670
+ const npmCommand = resolvedNpmCommand(["install", "-g", "--ignore-scripts", "--min-release-age=0", ...packageInstallSpecs(packages)], npmRuntime);
10430
10671
  return {
10431
10672
  label: "global npm package root",
10432
10673
  command: npmCommand.command,
@@ -10483,6 +10724,9 @@ async function resolveUpdateTasks({ all = false } = {}) {
10483
10724
  const piTasks = await resolvePiUpdateCommands({ all });
10484
10725
  if (!all) return uniqueUpdateTasks(piTasks);
10485
10726
 
10727
+ const npmRuntime = {
10728
+ preferredDirectories: [...new Set(piTasks.map((task) => task.piInstallDirectory).filter(Boolean))],
10729
+ };
10486
10730
  const [
10487
10731
  currentWebuiTask,
10488
10732
  agentTask,
@@ -10491,11 +10735,11 @@ async function resolveUpdateTasks({ all = false } = {}) {
10491
10735
  globalNpmTask,
10492
10736
  globalBunTask,
10493
10737
  ] = await Promise.all([
10494
- currentWebuiPackageUpdateTask(),
10495
- agentPackageRootUpdateTask(),
10496
- optionalFeatureInstallRootUpdateTask(),
10497
- projectPackageRootUpdateTasks(),
10498
- npmGlobalPackageRootUpdateTask(),
10738
+ currentWebuiPackageUpdateTask(npmRuntime),
10739
+ agentPackageRootUpdateTask(npmRuntime),
10740
+ optionalFeatureInstallRootUpdateTask(npmRuntime),
10741
+ projectPackageRootUpdateTasks(npmRuntime),
10742
+ npmGlobalPackageRootUpdateTask(npmRuntime),
10499
10743
  bunGlobalPackageRootUpdateTask(),
10500
10744
  ]);
10501
10745
 
@@ -10521,6 +10765,7 @@ async function runUpdateTask(task) {
10521
10765
  cwd: task.cwd || process.cwd(),
10522
10766
  timeoutMs: task.timeoutMs || PACKAGE_UPDATE_TIMEOUT_MS,
10523
10767
  maxOutputLength: task.maxOutputLength || PACKAGE_UPDATE_OUTPUT_MAX_CHARS,
10768
+ env: task.env,
10524
10769
  });
10525
10770
  const ok = result.exitCode === 0 && !result.timedOut && !result.error;
10526
10771
  if (!ok) {
@@ -10617,6 +10862,21 @@ const gitLiveWatcher = createGitLiveWatcher({
10617
10862
  },
10618
10863
  });
10619
10864
 
10865
+ const workspaceFilesLiveWatcher = createWorkspaceFilesLiveWatcher({
10866
+ onChange: ({ root, tabIds, changedAt }) => {
10867
+ for (const tabId of tabIds) {
10868
+ const tab = tabs.get(tabId);
10869
+ if (!tab || workspaceFilesLiveWatcher.subscribedRootForTab(tab.id) !== root) continue;
10870
+ broadcastTabEvent(tab, { type: "webui_workspace_files_changed", tabId: tab.id, root, changedAt });
10871
+ }
10872
+ },
10873
+ onError: ({ root, error }) => {
10874
+ const message = sanitizeError(error);
10875
+ recordEvent({ type: "webui_workspace_files_watch_error", root, error: message });
10876
+ console.warn(`Workspace files live watcher disabled for ${root}: ${message}`);
10877
+ },
10878
+ });
10879
+
10620
10880
  function trackGitRepositoryForTab(tab, root) {
10621
10881
  if (tab?.id && root) gitLiveWatcher.subscribe(tab.id, root);
10622
10882
  return root;
@@ -10631,6 +10891,8 @@ function renameTab(tab, title, { source = "explicit", maxLength, unique = source
10631
10891
  const previousTitle = tab.title;
10632
10892
  tab.title = nextTitle;
10633
10893
  tab.titleSource = source;
10894
+ tab.subagentDisplayTitle = source === "auto" ? truncateTabTitle(title, AUTO_TAB_TITLE_DISPLAY_MAX_LENGTH) : undefined;
10895
+ tab.subagentDisplayTitlePromise = undefined;
10634
10896
  if (previousTitle === nextTitle) return false;
10635
10897
  scheduleSupervisorMetadataUpdate(tab);
10636
10898
 
@@ -10656,6 +10918,11 @@ function maybeNameTabForConversation(tab, command) {
10656
10918
  return renameTab(tab, title, { source: "auto", maxLength: AUTO_TAB_TITLE_MAX_LENGTH });
10657
10919
  }
10658
10920
 
10921
+ function resetAutomaticTabTitleForNewSession(tab) {
10922
+ if (!tab || tab.titleSource === "explicit") return false;
10923
+ return renameTab(tab, defaultTabTitle(tab.index), { source: "default", unique: false });
10924
+ }
10925
+
10659
10926
  function responseWithTab(response, tab) {
10660
10927
  if (!response || typeof response !== "object") return response;
10661
10928
  return { ...response, tab: tabMeta(tab) };
@@ -10733,6 +11000,8 @@ async function performTabCwdUpdate(tab, cwd) {
10733
11000
  attachRpcToTab(tab, rpc);
10734
11001
  if (startDirectRpc) rpc.start();
10735
11002
  gitLiveWatcher.unsubscribe(tab.id);
11003
+ workspaceFilesLiveWatcher.unsubscribe(tab.id);
11004
+ workspaceFilesLiveWatcher.subscribe(tab.id, tab.cwd);
10736
11005
  // Non-fatal: a failed start surfaces through pi_process_error/exit events.
10737
11006
  await primeTabRpc(tab).catch(() => {});
10738
11007
 
@@ -12907,6 +13176,7 @@ async function handleNativeSlashCommand(tab, body, req) {
12907
13176
  const response = await tab.rpc.send({ type: "new_session" });
12908
13177
  if (response.success === false) return response;
12909
13178
  tab.conversationStarted = false;
13179
+ resetAutomaticTabTitleForNewSession(tab);
12910
13180
  forgetTabState(tab);
12911
13181
  rememberTabState(tab, response.data);
12912
13182
  clearPendingExtensionUiRequests(tab);
@@ -13006,6 +13276,7 @@ async function closeTab(id, { allowLast = false } = {}) {
13006
13276
  }
13007
13277
  rememberClosedRestorableTab(tab, restorableState);
13008
13278
  gitLiveWatcher.unsubscribe(tab.id);
13279
+ workspaceFilesLiveWatcher.unsubscribe(tab.id);
13009
13280
 
13010
13281
  const closingEvent = { type: "webui_tab_closing", tabId: tab.id, tabTitle: tab.title };
13011
13282
  recordEvent(closingEvent);
@@ -13026,6 +13297,7 @@ async function closeTab(id, { allowLast = false } = {}) {
13026
13297
  async function discardTab(tab) {
13027
13298
  if (!tab || !tabs.has(tab.id)) return;
13028
13299
  gitLiveWatcher.unsubscribe(tab.id);
13300
+ workspaceFilesLiveWatcher.unsubscribe(tab.id);
13029
13301
  tab.rpcUnsubscribe?.();
13030
13302
  rejectTabBashQueue(tab, new Error("Pi recovery tab initialization failed"));
13031
13303
  stopAppRunnerForTab(tab, "recovery initialization failed", { force: true });
@@ -13199,8 +13471,9 @@ function activateOutputMode(client, activeMode, reason = "server-default-change"
13199
13471
  }
13200
13472
 
13201
13473
  function sendSseToClient(client, event) {
13202
- sendSse(client, event);
13203
- if (client?.pendingMode && isOutputModeSemanticBarrier(event)) activateOutputMode(client, client.pendingMode);
13474
+ const sent = sendSse(client, event);
13475
+ if (sent && client?.pendingMode && isOutputModeSemanticBarrier(event)) activateOutputMode(client, client.pendingMode);
13476
+ return sent;
13204
13477
  }
13205
13478
 
13206
13479
  function refreshAutoOutputModes() {
@@ -13220,6 +13493,58 @@ function refreshAutoOutputModes() {
13220
13493
  }
13221
13494
  }
13222
13495
 
13496
+ const BROWSER_PROMPT_REQUEST_ID = /^[A-Za-z0-9_-]{16,128}$/;
13497
+ const BROWSER_PROMPT_REQUEST_TTL_MS = 10 * 60 * 1000;
13498
+ const BROWSER_PROMPT_REQUEST_LIMIT = 256;
13499
+
13500
+ function browserPromptRequestId(value) {
13501
+ if (value === undefined) return null;
13502
+ const id = String(value || "");
13503
+ if (!BROWSER_PROMPT_REQUEST_ID.test(id)) throw makeHttpError(400, "requestId must be an opaque 16-128 character identifier");
13504
+ return id;
13505
+ }
13506
+
13507
+ function browserPromptFingerprint(body) {
13508
+ return createHash("sha256").update(JSON.stringify({
13509
+ message: String(body?.message || ""),
13510
+ streamingBehavior: body?.streamingBehavior === "steer" || body?.streamingBehavior === "followUp" ? body.streamingBehavior : "",
13511
+ images: Array.isArray(body?.images) ? body.images : [],
13512
+ })).digest("base64url");
13513
+ }
13514
+
13515
+ function pruneBrowserPromptRequests(tab, now = Date.now()) {
13516
+ const requests = tab?.browserPromptRequests;
13517
+ if (!requests) return;
13518
+ for (const [id, entry] of requests) {
13519
+ if (entry.settledAt && entry.settledAt + BROWSER_PROMPT_REQUEST_TTL_MS <= now) requests.delete(id);
13520
+ }
13521
+ }
13522
+
13523
+ async function deduplicateBrowserPromptRequest(tab, body, dispatch) {
13524
+ const requestId = browserPromptRequestId(body?.requestId);
13525
+ if (!requestId) return dispatch();
13526
+ const requests = tab.browserPromptRequests || (tab.browserPromptRequests = new Map());
13527
+ const fingerprint = browserPromptFingerprint(body);
13528
+ pruneBrowserPromptRequests(tab);
13529
+ const known = requests.get(requestId);
13530
+ if (known) {
13531
+ if (known.fingerprint !== fingerprint) throw makeHttpError(409, "requestId was already used for a different prompt");
13532
+ return known.promise;
13533
+ }
13534
+ while (requests.size >= BROWSER_PROMPT_REQUEST_LIMIT) {
13535
+ const settled = [...requests.entries()].find(([, entry]) => entry.settledAt);
13536
+ if (!settled) throw makeHttpError(429, "too many in-flight prompt requests for this tab");
13537
+ requests.delete(settled[0]);
13538
+ }
13539
+ const entry = { fingerprint, settledAt: 0, promise: null };
13540
+ entry.promise = Promise.resolve().then(dispatch).finally(() => {
13541
+ entry.settledAt = Date.now();
13542
+ pruneBrowserPromptRequests(tab, entry.settledAt);
13543
+ });
13544
+ requests.set(requestId, entry);
13545
+ return entry.promise;
13546
+ }
13547
+
13223
13548
  async function saveOutputModeDefault(value) {
13224
13549
  let mode;
13225
13550
  try {
@@ -13625,6 +13950,36 @@ async function webuiStatus({ detailed = false, eventLimit = 40, includeAuthPin =
13625
13950
  return data;
13626
13951
  }
13627
13952
 
13953
+ async function handlePromptRequest(tab, body, req) {
13954
+ if (isNaturalConversationActive(tab) && naturalConversationSlashCommandName(body.message) && !isNaturalConversationSlashCommand(body.message)) {
13955
+ blockNaturalConversationAction("slash commands are blocked from the Web UI shell");
13956
+ }
13957
+ const nativeResponse = await handleNativeSlashCommand(tab, body, req);
13958
+ if (nativeResponse) {
13959
+ return { status: nativeResponse.success === false ? 400 : 200, payload: responseWithTab(nativeResponse, tab) };
13960
+ }
13961
+ const command = commandFromPost("/api/prompt", body);
13962
+ enforceNaturalConversationCommandAllowed(tab, command);
13963
+ const queuedForCompaction = maybeQueueCommandDuringCompaction(tab, command);
13964
+ if (queuedForCompaction) return { status: 202, payload: responseWithTab(queuedForCompaction, tab) };
13965
+ const naturalConversationSafetyResponse = await ensureNaturalConversationPromptSafety(tab, command);
13966
+ if (naturalConversationSafetyResponse?.success === false) {
13967
+ return { status: 400, payload: responseWithTab(naturalConversationSafetyResponse, tab) };
13968
+ }
13969
+ const pendingThinkingResponse = await applyPendingThinkingBeforePrompt(tab);
13970
+ if (pendingThinkingResponse?.success === false) {
13971
+ return { status: 400, payload: responseWithTab(pendingThinkingResponse, tab) };
13972
+ }
13973
+ const startsVisibleWork = commandStartsVisibleWork(command);
13974
+ if (startsVisibleWork) {
13975
+ maybeNameTabForConversation(tab, command);
13976
+ markTabWorking(tab);
13977
+ }
13978
+ const response = await tab.rpc.send(command, PROMPT_REQUEST_TIMEOUT_MS);
13979
+ if (response.success === false && startsVisibleWork) markTabIdle(tab);
13980
+ return { status: response.success === false ? 400 : 200, payload: responseWithTab(response, tab) };
13981
+ }
13982
+
13628
13983
  const server = createServer(async (req, res) => {
13629
13984
  try {
13630
13985
  const url = new URL(req.url || "/", `http://${req.headers.host || "localhost"}`);
@@ -13785,7 +14140,7 @@ const server = createServer(async (req, res) => {
13785
14140
  }
13786
14141
 
13787
14142
  if (url.pathname === "/api/subagents" && req.method === "GET") {
13788
- sendJson(res, 200, { ok: true, data: webuiSubagentsData() });
14143
+ sendJson(res, 200, { ok: true, data: await webuiSubagentsData() });
13789
14144
  return;
13790
14145
  }
13791
14146
 
@@ -13871,6 +14226,7 @@ const server = createServer(async (req, res) => {
13871
14226
  });
13872
14227
  const client = {
13873
14228
  res,
14229
+ tab,
13874
14230
  requestedMode: negotiated.requestedMode,
13875
14231
  protocolVersion: negotiated.protocolVersion,
13876
14232
  activeMode: negotiated.activeMode,
@@ -13927,7 +14283,13 @@ const server = createServer(async (req, res) => {
13927
14283
  replayExtensionStatuses(tab, client);
13928
14284
  replayExtensionWidgets(tab, client);
13929
14285
  replayPendingExtensionUiRequests(tab, client);
13930
- const keepAlive = setInterval(() => res.write(": keepalive\n\n"), 15000);
14286
+ const keepAlive = setInterval(() => {
14287
+ try {
14288
+ if (!res.write(": keepalive\n\n")) evictSlowSseClient(client);
14289
+ } catch {
14290
+ evictSlowSseClient(client);
14291
+ }
14292
+ }, 15000);
13931
14293
  req.on("close", () => {
13932
14294
  clearInterval(keepAlive);
13933
14295
  tab.sseClients.delete(client);
@@ -14620,39 +14982,8 @@ const server = createServer(async (req, res) => {
14620
14982
  if (url.pathname === "/api/prompt" && req.method === "POST") {
14621
14983
  const body = await readJsonBody(req, { limitBytes: requestBodyLimitForPath(url.pathname) });
14622
14984
  const tab = getRequestedTab(req, url, body);
14623
- if (isNaturalConversationActive(tab) && naturalConversationSlashCommandName(body.message) && !isNaturalConversationSlashCommand(body.message)) {
14624
- blockNaturalConversationAction("slash commands are blocked from the Web UI shell");
14625
- }
14626
- const nativeResponse = await handleNativeSlashCommand(tab, body, req);
14627
- if (nativeResponse) {
14628
- sendJson(res, nativeResponse.success === false ? 400 : 200, responseWithTab(nativeResponse, tab));
14629
- return;
14630
- }
14631
- const command = commandFromPost(url.pathname, body);
14632
- enforceNaturalConversationCommandAllowed(tab, command);
14633
- const queuedForCompaction = maybeQueueCommandDuringCompaction(tab, command);
14634
- if (queuedForCompaction) {
14635
- sendJson(res, 202, responseWithTab(queuedForCompaction, tab));
14636
- return;
14637
- }
14638
- const naturalConversationSafetyResponse = await ensureNaturalConversationPromptSafety(tab, command);
14639
- if (naturalConversationSafetyResponse?.success === false) {
14640
- sendJson(res, 400, responseWithTab(naturalConversationSafetyResponse, tab));
14641
- return;
14642
- }
14643
- const pendingThinkingResponse = await applyPendingThinkingBeforePrompt(tab);
14644
- if (pendingThinkingResponse?.success === false) {
14645
- sendJson(res, 400, responseWithTab(pendingThinkingResponse, tab));
14646
- return;
14647
- }
14648
- const startsVisibleWork = commandStartsVisibleWork(command);
14649
- if (startsVisibleWork) {
14650
- maybeNameTabForConversation(tab, command);
14651
- markTabWorking(tab);
14652
- }
14653
- const response = await tab.rpc.send(command, PROMPT_REQUEST_TIMEOUT_MS);
14654
- if (response.success === false && startsVisibleWork) markTabIdle(tab);
14655
- sendJson(res, response.success === false ? 400 : 200, responseWithTab(response, tab));
14985
+ const result = await deduplicateBrowserPromptRequest(tab, body, () => handlePromptRequest(tab, body, req));
14986
+ sendJson(res, result.status, result.payload);
14656
14987
  return;
14657
14988
  }
14658
14989
 
@@ -14838,6 +15169,7 @@ const server = createServer(async (req, res) => {
14838
15169
  "/api/git-changes/unstage-all": (cwd) => unstageAllGitChanges(cwd),
14839
15170
  "/api/git-changes/discard-file": (cwd, body) => discardGitFile(cwd, body),
14840
15171
  "/api/git-changes/delete-untracked": (cwd, body) => deleteGitUntrackedFile(cwd, body),
15172
+ "/api/git-changes/add-to-gitignore": (cwd, body) => addGitignoreEntry(cwd, body),
14841
15173
  "/api/git-operation/continue": (cwd, body) => gitOperationAction(cwd, "continue", body),
14842
15174
  "/api/git-operation/skip": (cwd, body) => gitOperationAction(cwd, "skip", body),
14843
15175
  "/api/git-operation/abort": (cwd, body) => gitOperationAction(cwd, "abort", body),
@@ -14957,6 +15289,7 @@ const server = createServer(async (req, res) => {
14957
15289
  if (response.success === false && startsVisibleWork) markTabIdle(tab);
14958
15290
  if (response.success !== false && command.type === "new_session") {
14959
15291
  tab.conversationStarted = false;
15292
+ resetAutomaticTabTitleForNewSession(tab);
14960
15293
  forgetTabState(tab);
14961
15294
  rememberTabState(tab, response.data);
14962
15295
  clearPendingExtensionUiRequests(tab);
@@ -15015,6 +15348,7 @@ async function shutdown(signal, { preserveSessions = false, exitCode = 0 } = {})
15015
15348
  shutdownInProgress = true;
15016
15349
  console.log(`\n${signal}: shutting down Pi Web UI...`);
15017
15350
  gitLiveWatcher.closeAll();
15351
+ workspaceFilesLiveWatcher.closeAll();
15018
15352
  for (const tab of tabs.values()) stopAppRunnerForTab(tab, "server shutdown", { force: true });
15019
15353
 
15020
15354
  const forceExit = setTimeout(() => process.exit(exitCode), 4000);