@firstpick/pi-package-webui 0.7.9 → 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 (57) hide show
  1. package/README.md +32 -9
  2. package/bin/pi-webui.mjs +750 -113
  3. package/lib/git-workflow-preferences.mjs +16 -0
  4. package/lib/git-worktrees.mjs +43 -4
  5. package/lib/npm-command.mjs +81 -0
  6. package/lib/queue-mutation.mjs +6 -0
  7. package/lib/workspace-files-live-watcher.mjs +138 -0
  8. package/package.json +11 -4
  9. package/public/app.js +3397 -380
  10. package/public/index.html +119 -20
  11. package/public/mobile-shell-state.mjs +166 -0
  12. package/public/service-worker.js +60 -13
  13. package/public/styles.css +1066 -362
  14. package/public/subagent-gate-visibility.mjs +16 -0
  15. package/public/subagent-launch-slot-state.mjs +16 -0
  16. package/public/transcript-renderer.mjs +433 -0
  17. package/tests/boot-failure-diagnostics.test.mjs +3 -3
  18. package/tests/browser/interaction-continuity.spec.mjs +739 -0
  19. package/tests/browser/mobile-foundation.spec.mjs +352 -0
  20. package/tests/browser/optimistic-prompt.spec.mjs +130 -0
  21. package/tests/chat-scroll-intent-static.test.mjs +6 -1
  22. package/tests/codex-fast-mode-static.test.mjs +59 -0
  23. package/tests/compact-sections-static.test.mjs +20 -2
  24. package/tests/compaction-mutation-contract.test.mjs +18 -4
  25. package/tests/compaction-static.test.mjs +1 -0
  26. package/tests/completion-signal-contract.test.mjs +13 -2
  27. package/tests/composer-skill-tag-layout.test.mjs +70 -0
  28. package/tests/fast-mode-client-static.test.mjs +14 -11
  29. package/tests/fixtures/fake-pi.mjs +222 -2
  30. package/tests/git-panel-gitignore-static.test.mjs +104 -0
  31. package/tests/git-workflow-preferences.test.mjs +8 -0
  32. package/tests/guided-git-publication-backend-static.test.mjs +40 -0
  33. package/tests/http-endpoints-harness.test.mjs +490 -3
  34. package/tests/interaction-state-stability-static.test.mjs +254 -0
  35. package/tests/mobile-continuity-tablet-static.test.mjs +55 -0
  36. package/tests/mobile-foundation-static.test.mjs +69 -0
  37. package/tests/mobile-phone-experience-static.test.mjs +65 -0
  38. package/tests/mobile-shell-state.test.mjs +69 -0
  39. package/tests/mobile-static.test.mjs +300 -43
  40. package/tests/mobile-transcript-cache-characterization.test.mjs +34 -0
  41. package/tests/npm-command.test.mjs +64 -1
  42. package/tests/open-issue-wizard-static.test.mjs +2 -1
  43. package/tests/queue-edit-reorder-static.test.mjs +9 -1
  44. package/tests/queue-mutation-contract.test.mjs +22 -0
  45. package/tests/service-worker-lifecycle.test.mjs +120 -0
  46. package/tests/side-panel-resize-static.test.mjs +8 -1
  47. package/tests/sse-backpressure-harness.test.mjs +98 -0
  48. package/tests/streaming-ui-coupling.test.mjs +7 -1
  49. package/tests/subagent-gate-visibility.test.mjs +18 -2
  50. package/tests/subagent-launch-slot-state.test.mjs +32 -0
  51. package/tests/subagent-launch-slots-static.test.mjs +8 -2
  52. package/tests/subagents-helper.test.mjs +90 -0
  53. package/tests/terminal-tab-workspace-static.test.mjs +1 -1
  54. package/tests/update-commands.test.mjs +4 -0
  55. package/tests/workspace-files-live-updates-static.test.mjs +76 -0
  56. package/tests/workspace-files-live-watcher.test.mjs +95 -0
  57. 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,
@@ -48,6 +48,8 @@ import {
48
48
  GIT_WORKFLOW_STAGING_POLICIES,
49
49
  GIT_WORKFLOW_THINKING_LEVELS,
50
50
  GIT_WORKFLOW_VERIFICATION_POLICIES,
51
+ WEBUI_SIDE_PANEL_WIDTH_MAX_PX,
52
+ WEBUI_SIDE_PANEL_WIDTH_MIN_PX,
51
53
  isGitWorkflowSetupComplete,
52
54
  mergeGitWorkflowPreferences,
53
55
  readGitWorkflowPreferences,
@@ -108,6 +110,7 @@ import {
108
110
  removeGitWorktree,
109
111
  } from "../lib/git-worktrees.mjs";
110
112
  import { createGitLiveWatcher } from "../lib/git-live-watcher.mjs";
113
+ import { createWorkspaceFilesLiveWatcher } from "../lib/workspace-files-live-watcher.mjs";
111
114
  import {
112
115
  gitMessageArtifactPairReadiness,
113
116
  readStableGitMessageArtifactPair,
@@ -152,6 +155,9 @@ const WEBUI_SUBAGENT_GATE_LIMIT = 32;
152
155
  const WEBUI_SUBAGENT_GATE_ATTEMPT_LIMIT = 100;
153
156
  const WEBUI_SUBAGENT_OUTPUT_LINE_LIMIT = 120;
154
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;
155
161
  const PI_CODING_AGENT_PACKAGE = "@earendil-works/pi-coding-agent";
156
162
  const WEBUI_PACKAGE = packageJson.name || "@firstpick/pi-package-webui";
157
163
  const PI_LATEST_VERSION_URL = process.env.PI_WEBUI_PI_LATEST_VERSION_URL || "https://pi.dev/api/latest-version";
@@ -248,6 +254,7 @@ const UPLOAD_TEMP_TTL_MS = 24 * 60 * 60 * 1000;
248
254
  const NATIVE_EXPORT_TEMP_TTL_MS = 60 * 60 * 1000;
249
255
  const TEMP_ARTIFACT_SWEEP_INTERVAL_MS = 60 * 60 * 1000;
250
256
  const AUTO_TAB_TITLE_MAX_LENGTH = 44;
257
+ const AUTO_TAB_TITLE_DISPLAY_MAX_LENGTH = 160;
251
258
  const AUTO_TAB_TITLE_WORD_LIMIT = 8;
252
259
  const AUTO_TAB_TITLE_STOP_WORDS = new Set([
253
260
  "a",
@@ -378,6 +385,7 @@ const OPTIONAL_FEATURE_PACKAGES = new Map([
378
385
  ["naturalConversation", "@firstpick/pi-package-natural-conversation"],
379
386
  ["gitFooterStatus", "@firstpick/pi-extension-git-footer-status"],
380
387
  ["statsCommand", "@firstpick/pi-extension-stats"],
388
+ ["codexFastMode", "@firstpick/pi-extension-codex-fast-mode"],
381
389
  ["themeBundle", "@firstpick/pi-themes-bundle"],
382
390
  ]);
383
391
  const WEBUI_CONTROLLED_PACKAGES = new Set([
@@ -393,6 +401,15 @@ const UPDATE_PACKAGE_NAMES = [...new Set([
393
401
  ])].sort();
394
402
  const NATURAL_CONVERSATION_STATUS_KEY = "natural-conversation";
395
403
  const NATURAL_CONVERSATION_COMMAND_NAMES = ["talk", "voice", "conversation"];
404
+ // Codex subscription Fast mode is owned by the optional @firstpick/pi-extension-codex-fast-mode
405
+ // package. The Web UI never inspects ChatGPT credentials or request payloads; it only mirrors the
406
+ // extension-published status key and drives the package-owned /fast-mode command over RPC.
407
+ const CODEX_FAST_MODE_FEATURE_ID = "codexFastMode";
408
+ const CODEX_FAST_MODE_STATUS_KEY = "codex-fast-mode";
409
+ const CODEX_FAST_MODE_COMMAND_NAME = "fast-mode";
410
+ const CODEX_FAST_MODE_PROVIDER = "openai-codex";
411
+ const CODEX_FAST_MODE_STATUS_TIMEOUT_MS = 1000;
412
+ const CODEX_FAST_MODE_CREDIT_NOTICE = "Fast mode asks Codex for about 1.5x faster responses and spends 2x Standard credits on GPT-5.4 and 2.5x on GPT-5.5/5.6. It only marks subscription-backed openai-codex requests; upstream account and model eligibility stays authoritative.";
396
413
  const PACKAGE_NAME_CACHE = new Map();
397
414
 
398
415
  function usage() {
@@ -1257,12 +1274,33 @@ function sendRemoteAuthRequired(req, res, url) {
1257
1274
  sendJson(res, 401, { ok: false, error: "Remote PIN required", remoteAuthRequired: true }, { "www-authenticate": "PiRemotePin" });
1258
1275
  }
1259
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
+
1260
1292
  function sendSse(client, event) {
1261
1293
  const res = client?.res || client;
1262
1294
  const payload = encodeBrowserSseEvent(event, { outputMode: client?.activeMode || OUTPUT_MODE_NORMAL });
1263
- if (payload === undefined) return false;
1264
- res.write(`data: ${payload}\n\n`);
1265
- 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
+ }
1266
1304
  }
1267
1305
 
1268
1306
  function rpcSuccess(command, data = {}) {
@@ -1609,7 +1647,7 @@ function generatedTabTitleFromPrompt(message) {
1609
1647
  const words = cleaned.split(/\s+/).map((word) => word.replace(/^[^\w]+|[^\w]+$/g, "")).filter(Boolean);
1610
1648
  const meaningfulWords = words.filter((word) => !AUTO_TAB_TITLE_STOP_WORDS.has(word.toLowerCase()));
1611
1649
  const selectedWords = (meaningfulWords.length >= 3 ? meaningfulWords : words).slice(0, AUTO_TAB_TITLE_WORD_LIMIT);
1612
- return truncateTabTitle(titleCaseTabTitle(selectedWords.join(" ")));
1650
+ return truncateTabTitle(titleCaseTabTitle(selectedWords.join(" ")), AUTO_TAB_TITLE_DISPLAY_MAX_LENGTH);
1613
1651
  }
1614
1652
 
1615
1653
  function uniqueTabTitle(title, currentTab, maxLength = AUTO_TAB_TITLE_MAX_LENGTH) {
@@ -5499,6 +5537,117 @@ function normalizeGitRelativePath(root, relativePath) {
5499
5537
  return path.relative(root, resolved).split(path.sep).join("/");
5500
5538
  }
5501
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
+
5502
5651
  async function readGitUntrackedEntry(root, file, { maxBytes = Number.POSITIVE_INFINITY } = {}) {
5503
5652
  const normalized = normalizeGitRelativePath(root, file);
5504
5653
  const filePath = resolveGitRelativePath(root, normalized);
@@ -5819,6 +5968,7 @@ const GIT_FETCH_TIMEOUT_MS = 2 * 60 * 1000;
5819
5968
  const GIT_CONFLICT_PREVIEW_MAX_BYTES = 200_000;
5820
5969
  const GIT_STASH_PATCH_MAX_OUTPUT = 200_000;
5821
5970
  const PROTECTED_GIT_BRANCHES = new Set(["main", "master"]);
5971
+ const NO_REMOTE_HINT = "No push destination is configured. Publish this repository or add a Git remote, then retry.";
5822
5972
 
5823
5973
  const sleepMs = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
5824
5974
 
@@ -5889,6 +6039,9 @@ function classifyGitSyncFailure(result, { push = false } = {}) {
5889
6039
  if (/could not resolve host|failed to connect|connection (?:refused|reset|timed out)|network is unreachable|operation timed out/.test(text)) {
5890
6040
  return { code: "NETWORK", hint: "The remote could not be reached. Check connectivity and retry." };
5891
6041
  }
6042
+ if (push && /fatal:\s+no configured push destination\./.test(text)) {
6043
+ return { code: "NO_REMOTE", hint: NO_REMOTE_HINT };
6044
+ }
5892
6045
  if (push && /protected branch|gh006/.test(text)) {
5893
6046
  return { code: "PROTECTED_BRANCH", hint: "The remote refused the push because the branch is protected. Push to a feature branch and open a PR instead." };
5894
6047
  }
@@ -6932,18 +7085,71 @@ function normalizeGitBranchList(branchText, current = "") {
6932
7085
  });
6933
7086
  }
6934
7087
 
7088
+ function configuredRemoteForRef(remoteRef, remoteNames = []) {
7089
+ return remoteNames
7090
+ .filter((remoteName) => remoteRef.startsWith(`${remoteName}/`))
7091
+ .sort((left, right) => right.length - left.length || left.localeCompare(right))[0] || "";
7092
+ }
7093
+
7094
+ function remoteBranchRecord(fullRef, symref = "", remoteNames = []) {
7095
+ const prefix = "refs/remotes/";
7096
+ const ref = String(fullRef || "");
7097
+ if (!ref.startsWith(prefix) || symref) return null;
7098
+ const remoteRef = ref.slice(prefix.length);
7099
+ const remoteName = configuredRemoteForRef(remoteRef, remoteNames);
7100
+ if (!remoteName) return null;
7101
+ const name = remoteRef.slice(remoteName.length + 1);
7102
+ if (!name) return null;
7103
+ return { name, current: false, remote: true, remoteRef, remoteName, displayName: remoteRef };
7104
+ }
7105
+
7106
+ async function readRemoteGitBranchData(root) {
7107
+ const [remoteNamesText, refs] = await Promise.all([
7108
+ runGitReadCommand(root, ["remote"], { timeoutMs: 5000, maxOutputLength: 120_000 }),
7109
+ runGitReadCommandDetailed(root, ["for-each-ref", "--format=%(refname)%09%(symref)", "refs/remotes"], { timeoutMs: 5000, maxOutputLength: 120_000 }),
7110
+ ]);
7111
+ return {
7112
+ remoteNames: remoteNamesText.split(/\r?\n/).map((line) => line.trim()).filter(Boolean),
7113
+ refText: refs.output,
7114
+ truncated: refs.truncated === true,
7115
+ unavailable: false,
7116
+ };
7117
+ }
7118
+
7119
+ function normalizeRemoteGitBranches(remoteData, localBranchNames) {
7120
+ // Never parse tail-truncated output: the first retained line may be a partial
7121
+ // ref. Local branches and worktrees remain available while the UI can expose
7122
+ // the truncation flag.
7123
+ if (!remoteData || remoteData.truncated) return [];
7124
+ const remoteBranches = [];
7125
+ for (const line of String(remoteData.refText || "").split(/\r?\n/)) {
7126
+ const [fullRef = "", symref = ""] = line.split("\t", 2);
7127
+ const branch = remoteBranchRecord(fullRef, symref, remoteData.remoteNames);
7128
+ // A local branch takes precedence over every same-named remote ref. Until
7129
+ // then, retain each exact remote ref so multiple remotes stay unambiguous.
7130
+ if (branch && !localBranchNames.has(branch.name)) remoteBranches.push(branch);
7131
+ }
7132
+ return remoteBranches.sort((left, right) => left.displayName.localeCompare(right.displayName));
7133
+ }
7134
+
6935
7135
  async function readGitBranches(cwd) {
6936
7136
  const root = await getGitRoot(cwd);
6937
- const [current, branchText, worktreeData] = await Promise.all([
7137
+ const [current, branchText, worktreeData, remoteData] = await Promise.all([
6938
7138
  currentGitBranchForPicker(root),
6939
- runGitReadCommand(root, ["branch", "--format=%(refname:short)"], { timeoutMs: 5000, maxOutputLength: 120_000 }),
7139
+ runGitReadCommand(root, ["branch", "--format=%(refname:lstrip=2)"], { timeoutMs: 5000, maxOutputLength: 120_000 }),
6940
7140
  listGitWorktrees(cwd).catch(() => null),
7141
+ readRemoteGitBranchData(root).catch(() => ({ remoteNames: [], refText: "", truncated: false, unavailable: true })),
6941
7142
  ]);
6942
7143
  const occupiedByBranch = new Map();
6943
7144
  for (const item of worktreeData?.occupiedBranches || []) {
6944
7145
  if (!item?.branch || occupiedByBranch.has(item.branch)) continue;
6945
7146
  occupiedByBranch.set(item.branch, item);
6946
7147
  }
7148
+ const localBranches = normalizeGitBranchList(branchText, current).map((branch) => {
7149
+ const occupied = occupiedByBranch.get(branch.name);
7150
+ return occupied ? { ...branch, occupied: true, worktreePath: occupied.path, worktreeCurrent: occupied.current === true, mainWorktree: occupied.isMainWorktree === true } : branch;
7151
+ });
7152
+ const remoteBranches = normalizeRemoteGitBranches(remoteData, new Set(localBranches.map((branch) => branch.name)));
6947
7153
  return {
6948
7154
  cwd,
6949
7155
  root,
@@ -6953,24 +7159,60 @@ async function readGitBranches(cwd) {
6953
7159
  defaultWorktreesRoot: worktreeData?.defaultWorktreesRoot || "",
6954
7160
  current,
6955
7161
  generatedAt: new Date().toISOString(),
6956
- branches: normalizeGitBranchList(branchText, current).map((branch) => {
6957
- const occupied = occupiedByBranch.get(branch.name);
6958
- return occupied ? { ...branch, occupied: true, worktreePath: occupied.path, worktreeCurrent: occupied.current === true, mainWorktree: occupied.isMainWorktree === true } : branch;
6959
- }),
7162
+ branches: [...localBranches, ...remoteBranches],
7163
+ remoteBranchesTruncated: remoteData.truncated === true,
7164
+ remoteBranchesUnavailable: remoteData.unavailable === true,
6960
7165
  worktrees: worktreeData?.worktrees || [],
6961
7166
  occupiedBranches: worktreeData?.occupiedBranches || [],
6962
7167
  };
6963
7168
  }
6964
7169
 
6965
- async function switchGitBranch(cwd, branch, { create = false } = {}) {
7170
+ function requestedRemoteRef(body = {}) {
7171
+ if (!Object.hasOwn(body, "remoteRef")) return null;
7172
+ if (typeof body.remoteRef !== "string" || !body.remoteRef || body.remoteRef.trim() !== body.remoteRef) {
7173
+ throw new Error("remoteRef must be a non-empty exact remote-tracking ref");
7174
+ }
7175
+ return body.remoteRef;
7176
+ }
7177
+
7178
+ async function verifyRemoteGitBranchIntent(cwd, branch, remoteRef) {
7179
+ const targetBranch = cleanGitBranchName(branch);
7180
+ const branches = await readGitBranches(cwd);
7181
+ const localBranch = branches.branches.find((item) => item.remote !== true && item.name === targetBranch);
7182
+ if (localBranch) throw new Error(`Local git branch already exists: ${targetBranch}. Refresh the picker and use the local branch instead.`);
7183
+ const remoteBranch = branches.branches.find((item) => item.remote === true && item.remoteRef === remoteRef);
7184
+ if (!remoteBranch) throw new Error(`Unknown remote git branch: ${remoteRef}`);
7185
+ if (remoteBranch.name !== targetBranch) {
7186
+ throw new Error(`Remote git branch ${remoteRef} does not match local branch ${targetBranch}`);
7187
+ }
7188
+ return { root: branches.root, branch: targetBranch, remoteRef: remoteBranch.remoteRef };
7189
+ }
7190
+
7191
+ async function switchGitBranch(cwd, branch, { create = false, remoteRef = null } = {}) {
7192
+ if (remoteRef !== null) {
7193
+ // Re-read the advertised remote-only record immediately before creating a
7194
+ // tracking branch. This rejects stale refs and local-name collisions.
7195
+ const intent = await verifyRemoteGitBranchIntent(cwd, branch, remoteRef);
7196
+ const payload = gitMutationPayload(await runGitMutationCommand(["switch", "--track", "-c", intent.branch, intent.remoteRef], { cwd: intent.root, timeoutMs: 10 * 60 * 1000 }));
7197
+ if (payload.ok) {
7198
+ payload.data.branch = intent.branch;
7199
+ payload.data.root = intent.root;
7200
+ payload.data.switched = true;
7201
+ payload.data.created = true;
7202
+ } else {
7203
+ payload.error = (payload.data?.stderr || payload.data?.stdout || payload.error || `Failed to create and switch to ${intent.branch}`).trim();
7204
+ }
7205
+ return payload;
7206
+ }
7207
+
6966
7208
  const root = await getGitRoot(cwd);
6967
7209
  const targetBranch = cleanGitBranchName(branch);
6968
7210
  await validateGitBranchName(root, targetBranch);
6969
7211
  const branches = await readGitBranches(cwd);
6970
- const branchExists = branches.branches.some((item) => item.name === targetBranch);
7212
+ const branchExists = branches.branches.some((item) => item.remote !== true && item.name === targetBranch);
6971
7213
  if (create && branchExists) throw new Error(`Local git branch already exists: ${targetBranch}`);
6972
7214
  if (!create && !branchExists) throw new Error(`Unknown local git branch: ${targetBranch}`);
6973
- const occupied = branches.branches.find((item) => item.name === targetBranch && item.occupied && !item.worktreeCurrent);
7215
+ const occupied = branches.branches.find((item) => item.remote !== true && item.name === targetBranch && item.occupied && !item.worktreeCurrent);
6974
7216
  if (!create && occupied?.worktreePath) {
6975
7217
  return {
6976
7218
  ok: false,
@@ -7215,9 +7457,13 @@ async function createGitWorkflowBranchWorktree(tab, body = {}) {
7215
7457
  }
7216
7458
 
7217
7459
  async function createGitWorktreeTab(tab, body = {}) {
7460
+ const remoteRef = requestedRemoteRef(body);
7461
+ const worktreeRequest = remoteRef === null
7462
+ ? body
7463
+ : { ...body, branchName: (await verifyRemoteGitBranchIntent(tab.cwd, body.branchName || body.branch, remoteRef)).branch, remoteRef };
7218
7464
  let createdResult = null;
7219
7465
  try {
7220
- createdResult = await createGitWorktree(tab.cwd, body);
7466
+ createdResult = await createGitWorktree(tab.cwd, worktreeRequest);
7221
7467
  const opened = await openWorktreeResultForTab(tab, createdResult, { openTab: body.openTab !== false, ...body });
7222
7468
  if (createdResult.created) {
7223
7469
  recordEvent({ type: "webui_worktree_created", tabId: opened.tab?.id || tab.id, cwd: opened.worktree?.path || opened.path, branch: opened.branch || body.branchName || "" });
@@ -7263,10 +7509,14 @@ function sendGitWorktreeFailure(res, error) {
7263
7509
  sendJson(res, 200, gitWorktreeErrorPayload(error));
7264
7510
  }
7265
7511
 
7266
- async function defaultGitRemote(root) {
7512
+ async function gitRemoteNames(root) {
7267
7513
  const result = await runGitWorkflowCommand(["remote"], { cwd: root, timeoutMs: 5000 });
7268
7514
  if (result.exitCode !== 0) throw new Error((result.stderr || result.stdout || "Cannot list git remotes").trim());
7269
- const remotes = result.stdout.split("\n").map((line) => line.trim()).filter(Boolean);
7515
+ return result.stdout.split("\n").map((line) => line.trim()).filter(Boolean);
7516
+ }
7517
+
7518
+ async function defaultGitRemote(root) {
7519
+ const remotes = await gitRemoteNames(root);
7270
7520
  if (!remotes.length) throw new Error("No git remote is configured for this repository");
7271
7521
  return remotes.includes("origin") ? "origin" : remotes[0];
7272
7522
  }
@@ -7381,6 +7631,20 @@ function gitWorkflowCommandPayload(result) {
7381
7631
  };
7382
7632
  }
7383
7633
 
7634
+ function applyGitHubPublicationFailure(payload) {
7635
+ if (payload.ok) return payload;
7636
+ const text = `${payload.data?.stderr || ""}\n${payload.data?.stdout || ""}\n${payload.data?.error || ""}`.toLowerCase();
7637
+ if (payload.data?.errorCode === "ENOENT") {
7638
+ payload.hint = "Install GitHub CLI (gh), ensure it is on PATH, then retry.";
7639
+ } else if (/not logged into any github hosts|gh auth login|http 401|bad credentials/.test(text)) {
7640
+ payload.code = "AUTH";
7641
+ payload.hint = "GitHub CLI is not authenticated. Run 'gh auth login' in a terminal, then retry.";
7642
+ } else if (/name already exists on this account|repository .+ already exists/.test(text)) {
7643
+ payload.hint = "A GitHub repository with this name already exists for the authenticated account. Choose another repository name and retry.";
7644
+ }
7645
+ return payload;
7646
+ }
7647
+
7384
7648
  // Read-only workflow lookups are safe over GET; everything else mutates the
7385
7649
  // repository (or process state, for cancel) and must be POST. Method + access
7386
7650
  // guard are enforced at the router before dispatch — never dispatch on path
@@ -7405,6 +7669,7 @@ const GIT_WORKFLOW_MUTATING_PATHS = new Set([
7405
7669
  "/api/git-workflow/branch",
7406
7670
  "/api/git-workflow/commit",
7407
7671
  "/api/git-workflow/push",
7672
+ "/api/git-workflow/publish",
7408
7673
  "/api/git-workflow/create-pr",
7409
7674
  "/api/git-workflow/cancel",
7410
7675
  ]);
@@ -7517,6 +7782,23 @@ async function handleGitWorkflowRequest(pathname, body = {}, tabOrCwd = options.
7517
7782
  }
7518
7783
  return applyGitSyncFailure(payload, { push: true });
7519
7784
  }
7785
+ case "/api/git-workflow/publish": {
7786
+ const repoName = cleanGitHubRepoName(body.repoName);
7787
+ const visibility = String(body.visibility || "").trim();
7788
+ if (visibility !== "public" && visibility !== "private") throw makeHttpError(400, "visibility must be 'public' or 'private'");
7789
+ requireConfirmed(body, `Publishing GitHub repository ${repoName} as ${visibility}`);
7790
+ const root = await getGitRoot(cwd);
7791
+ const remotes = await gitRemoteNames(root);
7792
+ if (remotes.length) throw makeHttpError(409, "GitHub publication requires a repository with no configured remotes. Existing remotes are not changed or repaired.");
7793
+ const branch = await currentGitBranch(root);
7794
+ const protectedBranch = PROTECTED_GIT_BRANCHES.has(branch);
7795
+ const payload = applyGitHubPublicationFailure(gitWorkflowCommandPayload(await runGitHubWorkflowCommand(
7796
+ ["repo", "create", repoName, `--${visibility}`, "--source", root, "--remote", "origin", "--push"],
7797
+ { cwd: root, timeoutMs: 15 * 60 * 1000 },
7798
+ )));
7799
+ if (payload.ok) Object.assign(payload.data, { repoName, visibility, remote: "origin", branch, protectedBranch });
7800
+ return payload;
7801
+ }
7520
7802
  case "/api/git-workflow/create-pr": {
7521
7803
  const root = await getGitRoot(cwd);
7522
7804
  const branch = await currentGitBranch(root);
@@ -7626,7 +7908,7 @@ async function readBundledThemes() {
7626
7908
  function normalizeStaticPath(urlPath) {
7627
7909
  if (urlPath === "/") return "index.html";
7628
7910
  const name = urlPath.startsWith("/") ? urlPath.slice(1) : urlPath;
7629
- 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;
7630
7912
  return name;
7631
7913
  }
7632
7914
 
@@ -8216,17 +8498,17 @@ async function resolvedPiCliScript() {
8216
8498
  return "";
8217
8499
  }
8218
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
+
8219
8510
  async function resolvePiCommand(piArgs) {
8220
- if (options.piBinExplicit) {
8221
- if (isNodeScriptCommand(options.piBin)) {
8222
- return {
8223
- command: process.execPath,
8224
- args: [options.piBin, ...piArgs],
8225
- displayCommand: `${process.execPath} ${options.piBin} ${piArgs.join(" ")}`,
8226
- };
8227
- }
8228
- return { command: options.piBin, args: piArgs, displayCommand: `${options.piBin} ${piArgs.join(" ")}` };
8229
- }
8511
+ if (options.piBinExplicit) return resolveSelectedPiCommand(piArgs);
8230
8512
 
8231
8513
  const bundledCli = await resolvedPiCliScript();
8232
8514
  if (bundledCli) {
@@ -8237,7 +8519,7 @@ async function resolvePiCommand(piArgs) {
8237
8519
  };
8238
8520
  }
8239
8521
 
8240
- return { command: options.piBin, args: piArgs, displayCommand: `${options.piBin} ${piArgs.join(" ")}` };
8522
+ return resolveSelectedPiCommand(piArgs);
8241
8523
  }
8242
8524
 
8243
8525
  const tabs = new Map();
@@ -8515,6 +8797,10 @@ function createTabActivity(now = new Date().toISOString()) {
8515
8797
  status: "idle",
8516
8798
  isWorking: false,
8517
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,
8518
8804
  completionSerial: 0,
8519
8805
  lastChangedAt: now,
8520
8806
  lastStartedAt: null,
@@ -8884,8 +9170,10 @@ function queueMutationRequest(body) {
8884
9170
  } else if (request.operation.type === "move") {
8885
9171
  request.operation.from = queueMutationIndex(operation.from, "operation.from");
8886
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");
8887
9175
  } else {
8888
- 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");
8889
9177
  }
8890
9178
  if (source === "webui-compaction") {
8891
9179
  if (!Number.isSafeInteger(body.revision) || body.revision < 0) throw makeHttpError(400, "Compaction queue mutation requires a non-negative revision");
@@ -8971,13 +9259,18 @@ function mutateCompactionFollowUpQueue(tab, request) {
8971
9259
  if (operation.type === "edit") {
8972
9260
  if (operation.index >= slots.length || current.followUp[operation.index] !== operation.expectedText) return failed("invalid-request");
8973
9261
  queue[slots[operation.index]].command.message = operation.text;
8974
- } else {
9262
+ } else if (operation.type === "move") {
8975
9263
  if (operation.from >= slots.length || operation.to >= slots.length || operation.from === operation.to
8976
9264
  || current.followUp[operation.from] !== operation.expectedText) return failed("invalid-request");
8977
9265
  const followUps = slots.map((index) => queue[index]);
8978
9266
  const [moved] = followUps.splice(operation.from, 1);
8979
9267
  followUps.splice(operation.to, 0, moved);
8980
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");
8981
9274
  }
8982
9275
 
8983
9276
  advanceCompactionQueueRevision(tab);
@@ -9249,6 +9542,7 @@ async function cancelPendingExtensionUiRequests(tab) {
9249
9542
 
9250
9543
  function markTabWorking(tab, timestamp = new Date().toISOString(), { runStarted = false } = {}) {
9251
9544
  const activity = tab.activity || createTabActivity(timestamp);
9545
+ if (!activity.isWorking || !activity.runId) activity.runId = randomUUID();
9252
9546
  activity.status = "working";
9253
9547
  activity.isWorking = true;
9254
9548
  activity.runStarted = activity.runStarted === true || runStarted === true;
@@ -9268,10 +9562,24 @@ function markTabDone(tab, timestamp = new Date().toISOString()) {
9268
9562
  tab.activity = activity;
9269
9563
  }
9270
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
+
9271
9576
  function markTabIdle(tab, timestamp = new Date().toISOString()) {
9272
9577
  const activity = tab.activity || createTabActivity(timestamp);
9273
9578
  activity.status = "idle";
9274
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;
9275
9583
  activity.runStarted = false;
9276
9584
  activity.lastChangedAt = timestamp;
9277
9585
  tab.activity = activity;
@@ -9341,19 +9649,30 @@ function updateTabActivityFromEvent(tab, event) {
9341
9649
  switch (event?.type) {
9342
9650
  case "agent_start":
9343
9651
  patchTabState(tab, { isStreaming: true });
9652
+ tab.pendingTurnFailure = false;
9344
9653
  markTabWorking(tab, timestamp, { runStarted: true });
9345
9654
  break;
9346
9655
  case "compaction_start":
9347
9656
  patchTabState(tab, { isCompacting: true });
9348
9657
  markTabWorking(tab, timestamp);
9349
9658
  break;
9350
- case "agent_end":
9659
+ case "agent_end": {
9351
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;
9352
9668
  break;
9353
9669
  case "agent_settled":
9354
9670
  patchTabState(tab, { isStreaming: false });
9355
- if (tab.activity?.runStarted) markTabDone(tab, timestamp);
9356
- 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;
9357
9676
  break;
9358
9677
  case "compaction_end":
9359
9678
  patchTabState(tab, { isCompacting: false });
@@ -9363,8 +9682,14 @@ function updateTabActivityFromEvent(tab, event) {
9363
9682
  patchTabState(tab, { pendingMessageCount: (event.steering?.length || 0) + (event.followUp?.length || 0) });
9364
9683
  break;
9365
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;
9366
9689
  case "pi_process_error":
9367
- markTabIdle(tab, timestamp);
9690
+ if (tab.activity?.runStarted) markTabFailed(tab, timestamp);
9691
+ else markTabIdle(tab, timestamp);
9692
+ tab.pendingTurnFailure = false;
9368
9693
  break;
9369
9694
  case "response":
9370
9695
  if (event.command === "get_state" && event.success !== false) {
@@ -9411,6 +9736,7 @@ function attachRpcToTab(tab, rpc) {
9411
9736
  clearExtensionWidgets(tab);
9412
9737
  clearWebuiSubagents(tab);
9413
9738
  resetNaturalConversationMode(tab);
9739
+ resetCodexFastMode(tab);
9414
9740
  } else {
9415
9741
  rememberExtensionStatusEvent(tab, scopedEvent);
9416
9742
  rememberNaturalConversationStatusEvent(tab, scopedEvent);
@@ -9445,6 +9771,8 @@ function createTabRecord({ id, index, title, titleSource, conversationStarted, c
9445
9771
  extensionStatuses: new Map(),
9446
9772
  extensionWidgets: new Map(),
9447
9773
  webuiSubagents: null,
9774
+ subagentDisplayTitle: undefined,
9775
+ subagentDisplayTitlePromise: undefined,
9448
9776
  webuiHelperRequests: new Map(),
9449
9777
  webuiHelperResponseIds: new Set(),
9450
9778
  bashQueue: [],
@@ -9456,8 +9784,10 @@ function createTabRecord({ id, index, title, titleSource, conversationStarted, c
9456
9784
  rpc,
9457
9785
  rpcUnsubscribe: undefined,
9458
9786
  sseClients: new Set(),
9787
+ browserPromptRequests: new Map(),
9459
9788
  };
9460
9789
  resetNaturalConversationMode(tab);
9790
+ resetCodexFastMode(tab);
9461
9791
  return tab;
9462
9792
  }
9463
9793
 
@@ -9492,6 +9822,7 @@ async function createTab({ id: requestedId, index, title, titleSource, conversat
9492
9822
 
9493
9823
  attachRpcToTab(tab, rpc);
9494
9824
  tabs.set(id, tab);
9825
+ workspaceFilesLiveWatcher.subscribe(tab.id, tab.cwd);
9495
9826
  try {
9496
9827
  if (rpc instanceof SupervisorPiRpcProcess) {
9497
9828
  const snapshot = await rpcSupervisor.createTab({
@@ -9509,6 +9840,7 @@ async function createTab({ id: requestedId, index, title, titleSource, conversat
9509
9840
  tab.rpcUnsubscribe?.();
9510
9841
  rpc.dispose?.();
9511
9842
  gitLiveWatcher.unsubscribe(id);
9843
+ workspaceFilesLiveWatcher.unsubscribe(id);
9512
9844
  tabs.delete(id);
9513
9845
  throw new Error(`Pi RPC process failed while starting ${tabTitle}: ${sanitizeError(error)}`);
9514
9846
  }
@@ -9554,12 +9886,14 @@ async function hydrateManagedTabs(snapshot) {
9554
9886
  });
9555
9887
  attachRpcToTab(tab, rpc);
9556
9888
  tabs.set(tab.id, tab);
9889
+ workspaceFilesLiveWatcher.subscribe(tab.id, tab.cwd);
9557
9890
  hydrated.push(tab);
9558
9891
  }
9559
9892
  } catch (error) {
9560
9893
  for (const tab of hydrated) {
9561
9894
  tab.rpcUnsubscribe?.();
9562
9895
  tab.rpc.dispose?.();
9896
+ workspaceFilesLiveWatcher.unsubscribe(tab.id);
9563
9897
  tabs.delete(tab.id);
9564
9898
  }
9565
9899
  throw error;
@@ -9601,16 +9935,37 @@ function listTabs() {
9601
9935
  return [...tabs.values()].map(tabMeta);
9602
9936
  }
9603
9937
 
9604
- 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() {
9605
9959
  const sortedTabs = [...tabs.values()].sort((a, b) => a.index - b.index || a.title.localeCompare(b.title));
9606
- const tabSummaries = sortedTabs.map((tab) => {
9960
+ const tabSummaries = await Promise.all(sortedTabs.map(async (tab) => {
9607
9961
  const status = tab.webuiSubagents || { version: 1, available: false, updatedAt: null, receivedAt: null, runs: [], gates: [] };
9608
9962
  const runs = Array.isArray(status.runs) ? status.runs : [];
9609
9963
  const gates = Array.isArray(status.gates) ? status.gates : [];
9964
+ const tabTitle = runs.length || gates.length ? await resolveSubagentDisplayTitle(tab) : tab.title;
9610
9965
  return {
9611
9966
  tabId: tab.id,
9612
9967
  tabIndex: tab.index,
9613
- tabTitle: tab.title,
9968
+ tabTitle,
9614
9969
  cwd: tab.cwd,
9615
9970
  sessionName: normalizeWebuiSubagentText(tab.lastState?.sessionName || tab.title, 160),
9616
9971
  sessionFile: tabRestorableSessionFile(tab) || null,
@@ -9625,7 +9980,7 @@ function webuiSubagentsData() {
9625
9980
  runningAgents: runs.reduce((count, run) => count + run.agents.filter((agent) => agent.status === "running").length, 0),
9626
9981
  gateCount: gates.length,
9627
9982
  };
9628
- });
9983
+ }));
9629
9984
  return {
9630
9985
  version: 1,
9631
9986
  updatedAt: Date.now(),
@@ -9712,6 +10067,29 @@ function normalizeWebuiSubagentTranscript(value) {
9712
10067
  return messages;
9713
10068
  }
9714
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
+
9715
10093
  function normalizeWebuiSubagentOutput(value, selection) {
9716
10094
  if (!value || typeof value !== "object" || value.version !== 1) throw makeHttpError(502, "Invalid subagent output response from Web UI helper");
9717
10095
  const rawAgent = value.agent && typeof value.agent === "object" ? value.agent : {};
@@ -9746,6 +10124,10 @@ function normalizeWebuiSubagentOutput(value, selection) {
9746
10124
  tokens: Number.isFinite(rawAgent.tokens) ? rawAgent.tokens : undefined,
9747
10125
  model: normalizeWebuiSubagentText(rawAgent.model, 240) || selection.agent.model || undefined,
9748
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
+ }),
9749
10131
  recentTools,
9750
10132
  recentOutput,
9751
10133
  transcript,
@@ -10096,31 +10478,37 @@ async function piUpdateCommandSupportsAll(command) {
10096
10478
  async function resolvePiUpdateCommands({ all = false } = {}) {
10097
10479
  let resolveCommand;
10098
10480
  let labelPrefix = "";
10481
+ let useBundledPi = false;
10099
10482
 
10100
10483
  if (options.piBinExplicit) {
10101
10484
  resolveCommand = (args) => resolvePiCommand(args);
10102
10485
  } else {
10103
- 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 });
10104
10488
  if (pathPi.exitCode === 0 && !pathPi.timedOut && !pathPi.error) {
10105
- resolveCommand = async (args) => ({
10106
- command: options.piBin,
10107
- args,
10108
- displayCommand: formatCommandForDisplay(options.piBin, args),
10109
- });
10489
+ resolveCommand = async (args) => resolveSelectedPiCommand(args);
10110
10490
  } else {
10111
10491
  resolveCommand = (args) => resolvePiCommand(args);
10112
10492
  labelPrefix = "bundled ";
10493
+ useBundledPi = true;
10113
10494
  }
10114
10495
  }
10115
10496
 
10116
10497
  const supportsAll = all && await piUpdateCommandSupportsAll(await resolveCommand(["update", "--help"]));
10117
10498
  const steps = piUpdateCommandSteps({ all, supportsAll });
10118
- return Promise.all(steps.map(async (step) => ({
10119
- ...(await resolveCommand(step.args)),
10120
- label: `${labelPrefix}${step.label}`,
10121
- timeoutMs: PI_UPDATE_TIMEOUT_MS,
10122
- maxOutputLength: PI_UPDATE_OUTPUT_MAX_CHARS,
10123
- })));
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
+ }));
10124
10512
  }
10125
10513
 
10126
10514
  function packageNodeModulesPath(nodeModulesRoot, packageName) {
@@ -10198,8 +10586,8 @@ function packageInstallSpecs(packageNames) {
10198
10586
  return packageNames.map((packageName) => `${packageName}@latest`);
10199
10587
  }
10200
10588
 
10201
- function resolvedNpmCommand(args) {
10202
- const invocation = resolveNpmCommandInvocation(args);
10589
+ function resolvedNpmCommand(args, runtime = {}) {
10590
+ const invocation = resolveNpmCommandInvocation(args, runtime);
10203
10591
  return {
10204
10592
  command: invocation.command,
10205
10593
  args: invocation.args,
@@ -10207,9 +10595,9 @@ function resolvedNpmCommand(args) {
10207
10595
  };
10208
10596
  }
10209
10597
 
10210
- function npmPrefixUpdateTask(label, installRoot, packageNames) {
10598
+ function npmPrefixUpdateTask(label, installRoot, packageNames, npmRuntime = {}) {
10211
10599
  if (!packageNames.length) return null;
10212
- 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);
10213
10601
  return {
10214
10602
  label,
10215
10603
  command: npmCommand.command,
@@ -10219,31 +10607,31 @@ function npmPrefixUpdateTask(label, installRoot, packageNames) {
10219
10607
  };
10220
10608
  }
10221
10609
 
10222
- async function currentWebuiPackageUpdateTask() {
10610
+ async function currentWebuiPackageUpdateTask(npmRuntime = {}) {
10223
10611
  const sourceCheckout = webuiDevServer || !String(packageRoot).split(path.sep).includes("node_modules");
10224
10612
  if (sourceCheckout) {
10225
10613
  const manifest = await readJsonFileIfExists(path.join(packageRoot, "package.json"));
10226
10614
  const packages = declaredWebuiPiPackageNames(manifest);
10227
- return npmPrefixUpdateTask("current Web UI checkout package dependencies", packageRoot, packages);
10615
+ return npmPrefixUpdateTask("current Web UI checkout package dependencies", packageRoot, packages, npmRuntime);
10228
10616
  }
10229
10617
 
10230
10618
  const installRoot = nodeModulesParentForPackageRoot(packageRoot);
10231
10619
  const packages = await packagesPresentInInstallPrefix(installRoot);
10232
- return npmPrefixUpdateTask("current Web UI install root", installRoot, packages);
10620
+ return npmPrefixUpdateTask("current Web UI install root", installRoot, packages, npmRuntime);
10233
10621
  }
10234
10622
 
10235
- async function agentPackageRootUpdateTask() {
10623
+ async function agentPackageRootUpdateTask(npmRuntime = {}) {
10236
10624
  const installRoot = configuredAgentNpmRoot();
10237
10625
  const packages = await packagesPresentInInstallPrefix(installRoot);
10238
- return npmPrefixUpdateTask("Pi agent npm package root", installRoot, packages);
10626
+ return npmPrefixUpdateTask("Pi agent npm package root", installRoot, packages, npmRuntime);
10239
10627
  }
10240
10628
 
10241
- async function optionalFeatureInstallRootUpdateTask() {
10629
+ async function optionalFeatureInstallRootUpdateTask(npmRuntime = {}) {
10242
10630
  const configuredRoot = process.env[OPTIONAL_FEATURE_INSTALL_ROOT_ENV];
10243
10631
  if (!configuredRoot) return null;
10244
10632
  const installRoot = path.resolve(expandUserPath(configuredRoot));
10245
10633
  const packages = await packagesPresentInInstallPrefix(installRoot);
10246
- return npmPrefixUpdateTask("configured optional-feature npm root", installRoot, packages);
10634
+ return npmPrefixUpdateTask("configured optional-feature npm root", installRoot, packages, npmRuntime);
10247
10635
  }
10248
10636
 
10249
10637
  function activeProjectPackageRoots() {
@@ -10258,28 +10646,28 @@ function activeProjectPackageRoots() {
10258
10646
  return [...roots].sort();
10259
10647
  }
10260
10648
 
10261
- async function projectPackageRootUpdateTasks() {
10649
+ async function projectPackageRootUpdateTasks(npmRuntime = {}) {
10262
10650
  const tasks = [];
10263
10651
  for (const installRoot of activeProjectPackageRoots()) {
10264
10652
  const packages = await packagesPresentInInstallPrefix(installRoot);
10265
- 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);
10266
10654
  if (task) tasks.push(task);
10267
10655
  }
10268
10656
  return tasks;
10269
10657
  }
10270
10658
 
10271
- async function npmGlobalNodeModulesRoot() {
10272
- const npmCommand = resolvedNpmCommand(["root", "-g"]);
10659
+ async function npmGlobalNodeModulesRoot(npmRuntime = {}) {
10660
+ const npmCommand = resolvedNpmCommand(["root", "-g"], npmRuntime);
10273
10661
  const result = await runCommand(npmCommand.command, npmCommand.args, { timeoutMs: 5000, maxOutputLength: 8000 });
10274
10662
  if (result.exitCode !== 0 || result.timedOut || result.error) return null;
10275
10663
  return result.stdout.trim().split(/\r?\n/).filter(Boolean).at(-1) || null;
10276
10664
  }
10277
10665
 
10278
- async function npmGlobalPackageRootUpdateTask() {
10279
- const nodeModulesRoot = await npmGlobalNodeModulesRoot();
10666
+ async function npmGlobalPackageRootUpdateTask(npmRuntime = {}) {
10667
+ const nodeModulesRoot = await npmGlobalNodeModulesRoot(npmRuntime);
10280
10668
  const packages = await packagesPresentInNodeModulesRoot(nodeModulesRoot);
10281
10669
  if (!packages.length) return null;
10282
- 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);
10283
10671
  return {
10284
10672
  label: "global npm package root",
10285
10673
  command: npmCommand.command,
@@ -10336,6 +10724,9 @@ async function resolveUpdateTasks({ all = false } = {}) {
10336
10724
  const piTasks = await resolvePiUpdateCommands({ all });
10337
10725
  if (!all) return uniqueUpdateTasks(piTasks);
10338
10726
 
10727
+ const npmRuntime = {
10728
+ preferredDirectories: [...new Set(piTasks.map((task) => task.piInstallDirectory).filter(Boolean))],
10729
+ };
10339
10730
  const [
10340
10731
  currentWebuiTask,
10341
10732
  agentTask,
@@ -10344,11 +10735,11 @@ async function resolveUpdateTasks({ all = false } = {}) {
10344
10735
  globalNpmTask,
10345
10736
  globalBunTask,
10346
10737
  ] = await Promise.all([
10347
- currentWebuiPackageUpdateTask(),
10348
- agentPackageRootUpdateTask(),
10349
- optionalFeatureInstallRootUpdateTask(),
10350
- projectPackageRootUpdateTasks(),
10351
- npmGlobalPackageRootUpdateTask(),
10738
+ currentWebuiPackageUpdateTask(npmRuntime),
10739
+ agentPackageRootUpdateTask(npmRuntime),
10740
+ optionalFeatureInstallRootUpdateTask(npmRuntime),
10741
+ projectPackageRootUpdateTasks(npmRuntime),
10742
+ npmGlobalPackageRootUpdateTask(npmRuntime),
10352
10743
  bunGlobalPackageRootUpdateTask(),
10353
10744
  ]);
10354
10745
 
@@ -10374,6 +10765,7 @@ async function runUpdateTask(task) {
10374
10765
  cwd: task.cwd || process.cwd(),
10375
10766
  timeoutMs: task.timeoutMs || PACKAGE_UPDATE_TIMEOUT_MS,
10376
10767
  maxOutputLength: task.maxOutputLength || PACKAGE_UPDATE_OUTPUT_MAX_CHARS,
10768
+ env: task.env,
10377
10769
  });
10378
10770
  const ok = result.exitCode === 0 && !result.timedOut && !result.error;
10379
10771
  if (!ok) {
@@ -10470,6 +10862,21 @@ const gitLiveWatcher = createGitLiveWatcher({
10470
10862
  },
10471
10863
  });
10472
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
+
10473
10880
  function trackGitRepositoryForTab(tab, root) {
10474
10881
  if (tab?.id && root) gitLiveWatcher.subscribe(tab.id, root);
10475
10882
  return root;
@@ -10484,6 +10891,8 @@ function renameTab(tab, title, { source = "explicit", maxLength, unique = source
10484
10891
  const previousTitle = tab.title;
10485
10892
  tab.title = nextTitle;
10486
10893
  tab.titleSource = source;
10894
+ tab.subagentDisplayTitle = source === "auto" ? truncateTabTitle(title, AUTO_TAB_TITLE_DISPLAY_MAX_LENGTH) : undefined;
10895
+ tab.subagentDisplayTitlePromise = undefined;
10487
10896
  if (previousTitle === nextTitle) return false;
10488
10897
  scheduleSupervisorMetadataUpdate(tab);
10489
10898
 
@@ -10509,6 +10918,11 @@ function maybeNameTabForConversation(tab, command) {
10509
10918
  return renameTab(tab, title, { source: "auto", maxLength: AUTO_TAB_TITLE_MAX_LENGTH });
10510
10919
  }
10511
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
+
10512
10926
  function responseWithTab(response, tab) {
10513
10927
  if (!response || typeof response !== "object") return response;
10514
10928
  return { ...response, tab: tabMeta(tab) };
@@ -10555,6 +10969,7 @@ async function performTabCwdUpdate(tab, cwd) {
10555
10969
  clearExtensionWidgets(tab);
10556
10970
  clearWebuiSubagents(tab);
10557
10971
  resetNaturalConversationMode(tab);
10972
+ resetCodexFastMode(tab);
10558
10973
 
10559
10974
  let rpc;
10560
10975
  let startDirectRpc = false;
@@ -10585,6 +11000,8 @@ async function performTabCwdUpdate(tab, cwd) {
10585
11000
  attachRpcToTab(tab, rpc);
10586
11001
  if (startDirectRpc) rpc.start();
10587
11002
  gitLiveWatcher.unsubscribe(tab.id);
11003
+ workspaceFilesLiveWatcher.unsubscribe(tab.id);
11004
+ workspaceFilesLiveWatcher.subscribe(tab.id, tab.cwd);
10588
11005
  // Non-fatal: a failed start surfaces through pi_process_error/exit events.
10589
11006
  await primeTabRpc(tab).catch(() => {});
10590
11007
 
@@ -10617,6 +11034,7 @@ async function restartTabRpc(tab, reason = "reload") {
10617
11034
  clearExtensionWidgets(tab);
10618
11035
  clearWebuiSubagents(tab);
10619
11036
  resetNaturalConversationMode(tab);
11037
+ resetCodexFastMode(tab);
10620
11038
  let rpc;
10621
11039
  if (oldRpc instanceof SupervisorPiRpcProcess) {
10622
11040
  const snapshot = await oldRpc.replace({
@@ -11324,6 +11742,120 @@ async function setNaturalConversationMode(tab, body = {}) {
11324
11742
  return { ...(await naturalConversationFeatureData(tab, { refreshCommands: false })), response };
11325
11743
  }
11326
11744
 
11745
+ function codexFastModeCommandBaseName(name) {
11746
+ return String(name || "").trim().toLowerCase().replace(/:\d+$/, "");
11747
+ }
11748
+
11749
+ // The extension publishes exactly "on" or "off"; anything else is treated as unknown so the
11750
+ // browser can render an explicit unknown state instead of silently claiming Fast mode is off.
11751
+ function codexFastModeStatusState(statusText) {
11752
+ const text = stripAnsi(statusText).replace(/\s+/g, " ").trim().toLowerCase();
11753
+ if (text !== "on" && text !== "off") return { known: false, enabled: false };
11754
+ return { known: true, enabled: text === "on" };
11755
+ }
11756
+
11757
+ function codexFastModeSnapshot(tab, patch = {}) {
11758
+ const previous = tab?.codexFastMode && typeof tab.codexFastMode === "object" ? tab.codexFastMode : {};
11759
+ const status = codexFastModeStatusState(extensionStatusMap(tab).get(CODEX_FAST_MODE_STATUS_KEY) || "");
11760
+ const known = patch.statusKnown ?? (status.known || previous.statusKnown === true);
11761
+ return {
11762
+ featureId: CODEX_FAST_MODE_FEATURE_ID,
11763
+ enabled: patch.enabled ?? (status.known ? status.enabled : previous.enabled === true),
11764
+ statusKnown: known,
11765
+ updatedAt: patch.updatedAt || new Date().toISOString(),
11766
+ };
11767
+ }
11768
+
11769
+ function resetCodexFastMode(tab) {
11770
+ if (!tab) return;
11771
+ tab.codexFastMode = null;
11772
+ tab.codexFastModeCommandName = "";
11773
+ }
11774
+
11775
+ async function codexFastModePackageStatus() {
11776
+ try {
11777
+ return await optionalFeaturePackageStatus(CODEX_FAST_MODE_FEATURE_ID);
11778
+ } catch (error) {
11779
+ return { featureId: CODEX_FAST_MODE_FEATURE_ID, packageName: OPTIONAL_FEATURE_PACKAGES.get(CODEX_FAST_MODE_FEATURE_ID), installed: false, error: sanitizeError(error) };
11780
+ }
11781
+ }
11782
+
11783
+ async function codexFastModeCommandState(tab, { refreshCommands = true } = {}) {
11784
+ if (!refreshCommands) return { commandName: String(tab?.codexFastModeCommandName || ""), rpcRunning: true, error: "" };
11785
+ try {
11786
+ const data = await getCommandData(tab, { annotateSkills: false });
11787
+ const match = (data.commands || []).find((command) => codexFastModeCommandBaseName(command?.name) === CODEX_FAST_MODE_COMMAND_NAME);
11788
+ tab.codexFastModeCommandName = match?.name ? String(match.name) : "";
11789
+ return { commandName: tab.codexFastModeCommandName, rpcRunning: data.rpcRunning !== false, error: data.error || "" };
11790
+ } catch (error) {
11791
+ tab.codexFastModeCommandName = "";
11792
+ return { commandName: "", rpcRunning: false, error: sanitizeError(error) };
11793
+ }
11794
+ }
11795
+
11796
+ async function codexFastModeFeatureData(tab, { refreshCommands = true } = {}) {
11797
+ const packageStatus = await codexFastModePackageStatus();
11798
+ const command = await codexFastModeCommandState(tab, { refreshCommands });
11799
+ const state = await currentSessionState(tab).catch(() => tab?.lastState || {});
11800
+ const model = state?.model?.provider && state?.model?.id
11801
+ ? { provider: String(state.model.provider), id: String(state.model.id) }
11802
+ : null;
11803
+ const mode = codexFastModeSnapshot(tab);
11804
+ tab.codexFastMode = mode;
11805
+ const available = !!command.commandName;
11806
+ return {
11807
+ featureId: CODEX_FAST_MODE_FEATURE_ID,
11808
+ packageName: OPTIONAL_FEATURE_PACKAGES.get(CODEX_FAST_MODE_FEATURE_ID),
11809
+ available,
11810
+ packageInstalled: packageStatus.installed === true,
11811
+ packageStatus,
11812
+ commandName: command.commandName,
11813
+ enabled: mode.enabled,
11814
+ statusKnown: mode.statusKnown,
11815
+ busy: tabHasActiveOutput(tab),
11816
+ model,
11817
+ modelEligible: model?.provider === CODEX_FAST_MODE_PROVIDER,
11818
+ creditNotice: CODEX_FAST_MODE_CREDIT_NOTICE,
11819
+ rpcRunning: command.rpcRunning,
11820
+ unavailableReason: available
11821
+ ? ""
11822
+ : packageStatus.installed
11823
+ ? "Codex Fast mode package is installed, but /fast-mode is not loaded in the active Pi tab. Reload the tab or enable the package extension."
11824
+ : "Codex Fast mode package is not installed or not visible from the Web UI package root.",
11825
+ error: command.error || undefined,
11826
+ };
11827
+ }
11828
+
11829
+ async function waitForCodexFastModeStatus(tab, desired) {
11830
+ const deadline = Date.now() + CODEX_FAST_MODE_STATUS_TIMEOUT_MS;
11831
+ do {
11832
+ const snapshot = codexFastModeSnapshot(tab);
11833
+ if (snapshot.statusKnown && snapshot.enabled === desired) {
11834
+ tab.codexFastMode = snapshot;
11835
+ return snapshot;
11836
+ }
11837
+ if (Date.now() >= deadline) break;
11838
+ await sleepMs(25);
11839
+ } while (true);
11840
+ throw makeHttpError(409, `Codex Fast mode did not confirm ${desired ? "on" : "off"}. The session may have become busy; inspect /fast-mode status and retry when idle.`);
11841
+ }
11842
+
11843
+ async function setCodexFastMode(tab, body = {}) {
11844
+ if (typeof body?.enabled !== "boolean") throw makeHttpError(400, "Codex Fast mode requires an explicit enabled boolean");
11845
+ const desired = body.enabled === true;
11846
+ const feature = await codexFastModeFeatureData(tab);
11847
+ if (!feature.available) throw makeHttpError(404, feature.unavailableReason);
11848
+ // A mid-turn tier change would produce a mixed-tier tool loop, so mutations are rejected while
11849
+ // the tab is working. Reading status stays available.
11850
+ if (feature.busy) throw makeHttpError(409, "This tab is busy; Codex Fast mode cannot change during a running turn. Wait for the turn to finish, then retry.");
11851
+ const response = await tab.rpc.send({ type: "prompt", message: `/${feature.commandName} ${desired ? "on" : "off"}` }, REQUEST_TIMEOUT_MS);
11852
+ if (response.success === false) throw makeHttpError(400, response.error || `Failed to turn Codex Fast mode ${desired ? "on" : "off"}`);
11853
+ // RPC success only means the extension command returned. Require its authoritative status event
11854
+ // to confirm the requested state so a busy-transition rejection cannot become false success.
11855
+ await waitForCodexFastModeStatus(tab, desired);
11856
+ return { ...(await codexFastModeFeatureData(tab, { refreshCommands: false })), requested: desired };
11857
+ }
11858
+
11327
11859
  // Piper voice switching for the native /talk audio loop. The WebUI never
11328
11860
  // imports the natural-conversation package; it mirrors the package's small
11329
11861
  // voice catalog for display, reads voice.json / the piper voice dir for
@@ -12644,6 +13176,7 @@ async function handleNativeSlashCommand(tab, body, req) {
12644
13176
  const response = await tab.rpc.send({ type: "new_session" });
12645
13177
  if (response.success === false) return response;
12646
13178
  tab.conversationStarted = false;
13179
+ resetAutomaticTabTitleForNewSession(tab);
12647
13180
  forgetTabState(tab);
12648
13181
  rememberTabState(tab, response.data);
12649
13182
  clearPendingExtensionUiRequests(tab);
@@ -12651,6 +13184,7 @@ async function handleNativeSlashCommand(tab, body, req) {
12651
13184
  clearExtensionWidgets(tab);
12652
13185
  clearWebuiSubagents(tab);
12653
13186
  resetNaturalConversationMode(tab);
13187
+ resetCodexFastMode(tab);
12654
13188
  return respondNative("new", {
12655
13189
  status: "succeeded",
12656
13190
  message: "Started a new session.",
@@ -12742,6 +13276,7 @@ async function closeTab(id, { allowLast = false } = {}) {
12742
13276
  }
12743
13277
  rememberClosedRestorableTab(tab, restorableState);
12744
13278
  gitLiveWatcher.unsubscribe(tab.id);
13279
+ workspaceFilesLiveWatcher.unsubscribe(tab.id);
12745
13280
 
12746
13281
  const closingEvent = { type: "webui_tab_closing", tabId: tab.id, tabTitle: tab.title };
12747
13282
  recordEvent(closingEvent);
@@ -12762,6 +13297,7 @@ async function closeTab(id, { allowLast = false } = {}) {
12762
13297
  async function discardTab(tab) {
12763
13298
  if (!tab || !tabs.has(tab.id)) return;
12764
13299
  gitLiveWatcher.unsubscribe(tab.id);
13300
+ workspaceFilesLiveWatcher.unsubscribe(tab.id);
12765
13301
  tab.rpcUnsubscribe?.();
12766
13302
  rejectTabBashQueue(tab, new Error("Pi recovery tab initialization failed"));
12767
13303
  stopAppRunnerForTab(tab, "recovery initialization failed", { force: true });
@@ -12935,8 +13471,9 @@ function activateOutputMode(client, activeMode, reason = "server-default-change"
12935
13471
  }
12936
13472
 
12937
13473
  function sendSseToClient(client, event) {
12938
- sendSse(client, event);
12939
- 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;
12940
13477
  }
12941
13478
 
12942
13479
  function refreshAutoOutputModes() {
@@ -12956,6 +13493,58 @@ function refreshAutoOutputModes() {
12956
13493
  }
12957
13494
  }
12958
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
+
12959
13548
  async function saveOutputModeDefault(value) {
12960
13549
  let mode;
12961
13550
  try {
@@ -12969,6 +13558,20 @@ async function saveOutputModeDefault(value) {
12969
13558
  return outputModeMetadata();
12970
13559
  }
12971
13560
 
13561
+ async function interfacePreferencesData() {
13562
+ const settings = await readWebuiSettings();
13563
+ return { preferences: settings.interfacePreferences };
13564
+ }
13565
+
13566
+ async function saveInterfacePreferences(body = {}) {
13567
+ const sidePanelWidth = Number(body.sidePanelWidth);
13568
+ if (!Number.isFinite(sidePanelWidth) || sidePanelWidth < WEBUI_SIDE_PANEL_WIDTH_MIN_PX || sidePanelWidth > WEBUI_SIDE_PANEL_WIDTH_MAX_PX) {
13569
+ throw makeHttpError(400, `sidePanelWidth must be between ${WEBUI_SIDE_PANEL_WIDTH_MIN_PX} and ${WEBUI_SIDE_PANEL_WIDTH_MAX_PX} pixels`);
13570
+ }
13571
+ const settings = await writeWebuiSettings({ interfacePreferences: { sidePanelWidth: Math.round(sidePanelWidth) } });
13572
+ return { preferences: settings.interfacePreferences };
13573
+ }
13574
+
12972
13575
  const remoteAuth = {
12973
13576
  pin: undefined,
12974
13577
  token: undefined,
@@ -13347,6 +13950,36 @@ async function webuiStatus({ detailed = false, eventLimit = 40, includeAuthPin =
13347
13950
  return data;
13348
13951
  }
13349
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
+
13350
13983
  const server = createServer(async (req, res) => {
13351
13984
  try {
13352
13985
  const url = new URL(req.url || "/", `http://${req.headers.host || "localhost"}`);
@@ -13440,6 +14073,16 @@ const server = createServer(async (req, res) => {
13440
14073
  return;
13441
14074
  }
13442
14075
 
14076
+ if (url.pathname === "/api/interface-preferences" && req.method === "GET") {
14077
+ sendJson(res, 200, { ok: true, data: await interfacePreferencesData() });
14078
+ return;
14079
+ }
14080
+
14081
+ if (url.pathname === "/api/interface-preferences" && req.method === "PUT") {
14082
+ sendJson(res, 200, { ok: true, data: await saveInterfacePreferences(await readJsonBody(req)) });
14083
+ return;
14084
+ }
14085
+
13443
14086
  if (url.pathname === "/api/tabs" && req.method === "GET") {
13444
14087
  sendJson(res, 200, { ok: true, data: { tabs: await listTabsWithReconciledActivity() } });
13445
14088
  return;
@@ -13497,7 +14140,7 @@ const server = createServer(async (req, res) => {
13497
14140
  }
13498
14141
 
13499
14142
  if (url.pathname === "/api/subagents" && req.method === "GET") {
13500
- sendJson(res, 200, { ok: true, data: webuiSubagentsData() });
14143
+ sendJson(res, 200, { ok: true, data: await webuiSubagentsData() });
13501
14144
  return;
13502
14145
  }
13503
14146
 
@@ -13583,6 +14226,7 @@ const server = createServer(async (req, res) => {
13583
14226
  });
13584
14227
  const client = {
13585
14228
  res,
14229
+ tab,
13586
14230
  requestedMode: negotiated.requestedMode,
13587
14231
  protocolVersion: negotiated.protocolVersion,
13588
14232
  activeMode: negotiated.activeMode,
@@ -13639,7 +14283,13 @@ const server = createServer(async (req, res) => {
13639
14283
  replayExtensionStatuses(tab, client);
13640
14284
  replayExtensionWidgets(tab, client);
13641
14285
  replayPendingExtensionUiRequests(tab, client);
13642
- 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);
13643
14293
  req.on("close", () => {
13644
14294
  clearInterval(keepAlive);
13645
14295
  tab.sseClients.delete(client);
@@ -14131,6 +14781,19 @@ const server = createServer(async (req, res) => {
14131
14781
  return;
14132
14782
  }
14133
14783
 
14784
+ if (url.pathname === "/api/codex-fast-mode" && req.method === "GET") {
14785
+ const tab = getRequestedTab(req, url);
14786
+ sendJson(res, 200, { ok: true, data: await codexFastModeFeatureData(tab), tab: tabMeta(tab) });
14787
+ return;
14788
+ }
14789
+
14790
+ if (url.pathname === "/api/codex-fast-mode" && req.method === "PUT") {
14791
+ const body = await readJsonBody(req);
14792
+ const tab = getRequestedTab(req, url, body);
14793
+ sendJson(res, 200, { ok: true, data: await setCodexFastMode(tab, body), tab: tabMeta(tab) });
14794
+ return;
14795
+ }
14796
+
14134
14797
  if (url.pathname === "/api/conversation-voices" && req.method === "GET") {
14135
14798
  const tab = getRequestedTab(req, url);
14136
14799
  sendJson(res, 200, { ok: true, data: await conversationVoicesData(), tab: tabMeta(tab) });
@@ -14319,39 +14982,8 @@ const server = createServer(async (req, res) => {
14319
14982
  if (url.pathname === "/api/prompt" && req.method === "POST") {
14320
14983
  const body = await readJsonBody(req, { limitBytes: requestBodyLimitForPath(url.pathname) });
14321
14984
  const tab = getRequestedTab(req, url, body);
14322
- if (isNaturalConversationActive(tab) && naturalConversationSlashCommandName(body.message) && !isNaturalConversationSlashCommand(body.message)) {
14323
- blockNaturalConversationAction("slash commands are blocked from the Web UI shell");
14324
- }
14325
- const nativeResponse = await handleNativeSlashCommand(tab, body, req);
14326
- if (nativeResponse) {
14327
- sendJson(res, nativeResponse.success === false ? 400 : 200, responseWithTab(nativeResponse, tab));
14328
- return;
14329
- }
14330
- const command = commandFromPost(url.pathname, body);
14331
- enforceNaturalConversationCommandAllowed(tab, command);
14332
- const queuedForCompaction = maybeQueueCommandDuringCompaction(tab, command);
14333
- if (queuedForCompaction) {
14334
- sendJson(res, 202, responseWithTab(queuedForCompaction, tab));
14335
- return;
14336
- }
14337
- const naturalConversationSafetyResponse = await ensureNaturalConversationPromptSafety(tab, command);
14338
- if (naturalConversationSafetyResponse?.success === false) {
14339
- sendJson(res, 400, responseWithTab(naturalConversationSafetyResponse, tab));
14340
- return;
14341
- }
14342
- const pendingThinkingResponse = await applyPendingThinkingBeforePrompt(tab);
14343
- if (pendingThinkingResponse?.success === false) {
14344
- sendJson(res, 400, responseWithTab(pendingThinkingResponse, tab));
14345
- return;
14346
- }
14347
- const startsVisibleWork = commandStartsVisibleWork(command);
14348
- if (startsVisibleWork) {
14349
- maybeNameTabForConversation(tab, command);
14350
- markTabWorking(tab);
14351
- }
14352
- const response = await tab.rpc.send(command, PROMPT_REQUEST_TIMEOUT_MS);
14353
- if (response.success === false && startsVisibleWork) markTabIdle(tab);
14354
- 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);
14355
14987
  return;
14356
14988
  }
14357
14989
 
@@ -14495,7 +15127,8 @@ const server = createServer(async (req, res) => {
14495
15127
  const tab = getRequestedTab(req, url, body);
14496
15128
  ensureNaturalConversationRouteAllowed(tab, "git branch changes are blocked");
14497
15129
  try {
14498
- sendJson(res, 200, await switchGitBranch(tab.cwd, body.branch, { create: body.create === true }));
15130
+ const remoteRef = requestedRemoteRef(body);
15131
+ sendJson(res, 200, await switchGitBranch(tab.cwd, body.branch, { create: body.create === true, remoteRef }));
14499
15132
  } catch (error) {
14500
15133
  sendJson(res, 200, { ok: false, error: sanitizeError(error) });
14501
15134
  }
@@ -14536,6 +15169,7 @@ const server = createServer(async (req, res) => {
14536
15169
  "/api/git-changes/unstage-all": (cwd) => unstageAllGitChanges(cwd),
14537
15170
  "/api/git-changes/discard-file": (cwd, body) => discardGitFile(cwd, body),
14538
15171
  "/api/git-changes/delete-untracked": (cwd, body) => deleteGitUntrackedFile(cwd, body),
15172
+ "/api/git-changes/add-to-gitignore": (cwd, body) => addGitignoreEntry(cwd, body),
14539
15173
  "/api/git-operation/continue": (cwd, body) => gitOperationAction(cwd, "continue", body),
14540
15174
  "/api/git-operation/skip": (cwd, body) => gitOperationAction(cwd, "skip", body),
14541
15175
  "/api/git-operation/abort": (cwd, body) => gitOperationAction(cwd, "abort", body),
@@ -14655,6 +15289,7 @@ const server = createServer(async (req, res) => {
14655
15289
  if (response.success === false && startsVisibleWork) markTabIdle(tab);
14656
15290
  if (response.success !== false && command.type === "new_session") {
14657
15291
  tab.conversationStarted = false;
15292
+ resetAutomaticTabTitleForNewSession(tab);
14658
15293
  forgetTabState(tab);
14659
15294
  rememberTabState(tab, response.data);
14660
15295
  clearPendingExtensionUiRequests(tab);
@@ -14662,6 +15297,7 @@ const server = createServer(async (req, res) => {
14662
15297
  clearExtensionWidgets(tab);
14663
15298
  clearWebuiSubagents(tab);
14664
15299
  resetNaturalConversationMode(tab);
15300
+ resetCodexFastMode(tab);
14665
15301
  }
14666
15302
  sendJson(res, response.success === false ? 400 : 200, responseWithTab(response, tab));
14667
15303
  return;
@@ -14712,6 +15348,7 @@ async function shutdown(signal, { preserveSessions = false, exitCode = 0 } = {})
14712
15348
  shutdownInProgress = true;
14713
15349
  console.log(`\n${signal}: shutting down Pi Web UI...`);
14714
15350
  gitLiveWatcher.closeAll();
15351
+ workspaceFilesLiveWatcher.closeAll();
14715
15352
  for (const tab of tabs.values()) stopAppRunnerForTab(tab, "server shutdown", { force: true });
14716
15353
 
14717
15354
  const forceExit = setTimeout(() => process.exit(exitCode), 4000);