@firstpick/pi-package-webui 0.7.8 → 0.8.0

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 (41) hide show
  1. package/README.md +10 -4
  2. package/bin/pi-webui.mjs +696 -69
  3. package/lib/git-workflow-preferences.mjs +16 -0
  4. package/lib/git-worktrees.mjs +43 -4
  5. package/lib/queue-mutation.mjs +109 -0
  6. package/lib/scoped-models.mjs +19 -0
  7. package/lib/webui-workspaces.mjs +265 -0
  8. package/package.json +4 -2
  9. package/public/app.js +2074 -188
  10. package/public/index.html +105 -4
  11. package/public/service-worker.js +1 -1
  12. package/public/styles.css +618 -73
  13. package/public/voice-conversation.mjs +1 -1
  14. package/tests/boot-failure-diagnostics.test.mjs +2 -2
  15. package/tests/codex-fast-mode-static.test.mjs +56 -0
  16. package/tests/compaction-mutation-contract.test.mjs +166 -0
  17. package/tests/compaction-resume-harness.test.mjs +113 -2
  18. package/tests/compaction-static.test.mjs +5 -0
  19. package/tests/composer-skill-tag-layout.test.mjs +70 -0
  20. package/tests/cwd-footer-reliability-static.test.mjs +5 -0
  21. package/tests/fast-mode-client-static.test.mjs +8 -8
  22. package/tests/file-selection-overlay-static.test.mjs +21 -0
  23. package/tests/file-viewer-search-static.test.mjs +65 -0
  24. package/tests/fixtures/fake-pi.mjs +216 -43
  25. package/tests/git-panel-file-preview-static.test.mjs +20 -5
  26. package/tests/git-workflow-preferences.test.mjs +8 -0
  27. package/tests/guided-git-publication-backend-static.test.mjs +40 -0
  28. package/tests/http-endpoints-harness.test.mjs +422 -2
  29. package/tests/mobile-static.test.mjs +111 -42
  30. package/tests/native-parity.test.mjs +1 -1
  31. package/tests/open-issue-wizard-static.test.mjs +1 -1
  32. package/tests/queue-edit-reorder-static.test.mjs +101 -0
  33. package/tests/queue-mutation-contract.test.mjs +143 -0
  34. package/tests/scoped-models.test.mjs +42 -0
  35. package/tests/side-panel-resize-static.test.mjs +8 -1
  36. package/tests/subagents-helper.test.mjs +216 -3
  37. package/tests/terminal-tab-workspace-static.test.mjs +4 -2
  38. package/tests/webui-workspaces-harness.test.mjs +223 -0
  39. package/tests/webui-workspaces.test.mjs +106 -0
  40. package/tests/workspace-save-load-static.test.mjs +69 -0
  41. package/webui-rpc-helper.mjs +300 -41
package/bin/pi-webui.mjs CHANGED
@@ -14,6 +14,13 @@ import { brotliCompress, constants as zlibConstants, gzip } from "node:zlib";
14
14
  import { SessionManager, SettingsManager, DefaultPackageManager } from "@earendil-works/pi-coding-agent";
15
15
  import { authProvidersPayload, createAuthContext, logoutStoredProvider } from "../lib/auth-actions.mjs";
16
16
  import { resolveCodexUsageAuth } from "../lib/codex-usage-auth.mjs";
17
+ import { resolveScopedModelsFromPatterns } from "../lib/scoped-models.mjs";
18
+ import {
19
+ deleteWebuiWorkspace,
20
+ getWebuiWorkspace,
21
+ listWebuiWorkspaces,
22
+ saveWebuiWorkspace,
23
+ } from "../lib/webui-workspaces.mjs";
17
24
  import { nativeExportDownloadPayload } from "../lib/native-export-payload.mjs";
18
25
  import { discoverStartAttachRpcSupervisor } from "../lib/rpc-supervisor-client.mjs";
19
26
  import { readSupervisorState, supervisorPaths } from "../lib/rpc-supervisor-state.mjs";
@@ -41,6 +48,8 @@ import {
41
48
  GIT_WORKFLOW_STAGING_POLICIES,
42
49
  GIT_WORKFLOW_THINKING_LEVELS,
43
50
  GIT_WORKFLOW_VERIFICATION_POLICIES,
51
+ WEBUI_SIDE_PANEL_WIDTH_MAX_PX,
52
+ WEBUI_SIDE_PANEL_WIDTH_MIN_PX,
44
53
  isGitWorkflowSetupComplete,
45
54
  mergeGitWorkflowPreferences,
46
55
  readGitWorkflowPreferences,
@@ -181,6 +190,7 @@ const FILE_SEARCH_MAX_SCANNED = 12_000;
181
190
  const FILE_SEARCH_MAX_DEPTH = 8;
182
191
  const FILE_SEARCH_EXCLUDED_DIRS = new Set([".git", "node_modules"]);
183
192
  const PROMPT_BODY_LIMIT_BYTES = 24 * 1024 * 1024;
193
+ const QUEUE_MUTATION_MAX_ITEMS = 512;
184
194
  const VOICE_AUDIO_BODY_LIMIT_BYTES = 24 * 1024 * 1024;
185
195
  const VOICE_AUDIO_JSON_BODY_LIMIT_BYTES = Math.ceil(VOICE_AUDIO_BODY_LIMIT_BYTES * 1.4) + 1024 * 1024;
186
196
  const VOICE_PROVIDER_TIMEOUT_MS = Math.max(1000, Number.parseInt(process.env.PI_VOICE_PROVIDER_TIMEOUT_MS || "120000", 10) || 120000);
@@ -370,6 +380,7 @@ const OPTIONAL_FEATURE_PACKAGES = new Map([
370
380
  ["naturalConversation", "@firstpick/pi-package-natural-conversation"],
371
381
  ["gitFooterStatus", "@firstpick/pi-extension-git-footer-status"],
372
382
  ["statsCommand", "@firstpick/pi-extension-stats"],
383
+ ["codexFastMode", "@firstpick/pi-extension-codex-fast-mode"],
373
384
  ["themeBundle", "@firstpick/pi-themes-bundle"],
374
385
  ]);
375
386
  const WEBUI_CONTROLLED_PACKAGES = new Set([
@@ -385,6 +396,15 @@ const UPDATE_PACKAGE_NAMES = [...new Set([
385
396
  ])].sort();
386
397
  const NATURAL_CONVERSATION_STATUS_KEY = "natural-conversation";
387
398
  const NATURAL_CONVERSATION_COMMAND_NAMES = ["talk", "voice", "conversation"];
399
+ // Codex subscription Fast mode is owned by the optional @firstpick/pi-extension-codex-fast-mode
400
+ // package. The Web UI never inspects ChatGPT credentials or request payloads; it only mirrors the
401
+ // extension-published status key and drives the package-owned /fast-mode command over RPC.
402
+ const CODEX_FAST_MODE_FEATURE_ID = "codexFastMode";
403
+ const CODEX_FAST_MODE_STATUS_KEY = "codex-fast-mode";
404
+ const CODEX_FAST_MODE_COMMAND_NAME = "fast-mode";
405
+ const CODEX_FAST_MODE_PROVIDER = "openai-codex";
406
+ const CODEX_FAST_MODE_STATUS_TIMEOUT_MS = 1000;
407
+ 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.";
388
408
  const PACKAGE_NAME_CACHE = new Map();
389
409
 
390
410
  function usage() {
@@ -4660,48 +4680,12 @@ async function configuredScopedModelPatterns(cwd = options.cwd) {
4660
4680
  return { patterns: [], source: "none" };
4661
4681
  }
4662
4682
 
4663
- function stripThinkingSuffix(pattern) {
4664
- const text = String(pattern || "").trim();
4665
- const slashIndex = text.indexOf("/");
4666
- const colonIndex = text.lastIndexOf(":");
4667
- if (colonIndex > (slashIndex === -1 ? -1 : slashIndex)) return text.slice(0, colonIndex);
4668
- return text;
4669
- }
4670
-
4671
- function globToRegExp(pattern) {
4672
- const escaped = pattern.replace(/[.+^${}()|\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".");
4673
- return new RegExp(`^${escaped}$`, "i");
4674
- }
4675
-
4676
- function modelMatchesPattern(model, pattern) {
4677
- const clean = stripThinkingSuffix(pattern).toLowerCase();
4678
- if (!clean) return false;
4679
- const full = `${model.provider}/${model.id}`.toLowerCase();
4680
- const id = String(model.id || "").toLowerCase();
4681
- if (/[?*\[]/.test(clean)) return globToRegExp(clean).test(full) || globToRegExp(clean).test(id);
4682
- return full === clean || id === clean || full.includes(clean) || id.includes(clean);
4683
- }
4684
-
4685
- function resolveScopedModelsFromPatterns(patterns, models) {
4686
- const scoped = [];
4687
- const seen = new Set();
4688
- for (const pattern of patterns || []) {
4689
- for (const model of models || []) {
4690
- const key = `${model.provider}/${model.id}`;
4691
- if (seen.has(key) || !modelMatchesPattern(model, pattern)) continue;
4692
- seen.add(key);
4693
- scoped.push(model);
4694
- }
4695
- }
4696
- return scoped;
4697
- }
4698
-
4699
4683
  async function getScopedModelData(tab) {
4700
4684
  const { patterns, source } = await configuredScopedModelPatterns(tab.cwd);
4701
4685
  if (!patterns.length) return { models: [], patterns, source };
4702
4686
  const response = await safeRpcResponse(tab, { type: "get_available_models" });
4703
4687
  if (response.success === false) throw makeHttpError(400, response.error || "failed to load available models");
4704
- return { models: resolveScopedModelsFromPatterns(patterns, response.data?.models || []), patterns, source, rpcRunning: response.rpcRunning !== false };
4688
+ return { models: await resolveScopedModelsFromPatterns(patterns, response.data?.models || []), patterns, source, rpcRunning: response.rpcRunning !== false };
4705
4689
  }
4706
4690
 
4707
4691
  function modelKey(model) {
@@ -4713,7 +4697,7 @@ async function cycleTabModel(tab, direction = "forward") {
4713
4697
  if (availableResponse.success === false) return availableResponse;
4714
4698
  const allModels = Array.isArray(availableResponse.data?.models) ? availableResponse.data.models : [];
4715
4699
  const { patterns, source } = await configuredScopedModelPatterns(tab.cwd);
4716
- const scopedModels = patterns.length ? resolveScopedModelsFromPatterns(patterns, allModels) : [];
4700
+ const scopedModels = patterns.length ? await resolveScopedModelsFromPatterns(patterns, allModels) : [];
4717
4701
  const candidates = scopedModels.length ? scopedModels : allModels;
4718
4702
  if (!candidates.length) throw makeHttpError(400, "No models are available to cycle.");
4719
4703
 
@@ -5847,6 +5831,7 @@ const GIT_FETCH_TIMEOUT_MS = 2 * 60 * 1000;
5847
5831
  const GIT_CONFLICT_PREVIEW_MAX_BYTES = 200_000;
5848
5832
  const GIT_STASH_PATCH_MAX_OUTPUT = 200_000;
5849
5833
  const PROTECTED_GIT_BRANCHES = new Set(["main", "master"]);
5834
+ const NO_REMOTE_HINT = "No push destination is configured. Publish this repository or add a Git remote, then retry.";
5850
5835
 
5851
5836
  const sleepMs = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
5852
5837
 
@@ -5917,6 +5902,9 @@ function classifyGitSyncFailure(result, { push = false } = {}) {
5917
5902
  if (/could not resolve host|failed to connect|connection (?:refused|reset|timed out)|network is unreachable|operation timed out/.test(text)) {
5918
5903
  return { code: "NETWORK", hint: "The remote could not be reached. Check connectivity and retry." };
5919
5904
  }
5905
+ if (push && /fatal:\s+no configured push destination\./.test(text)) {
5906
+ return { code: "NO_REMOTE", hint: NO_REMOTE_HINT };
5907
+ }
5920
5908
  if (push && /protected branch|gh006/.test(text)) {
5921
5909
  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." };
5922
5910
  }
@@ -6960,18 +6948,71 @@ function normalizeGitBranchList(branchText, current = "") {
6960
6948
  });
6961
6949
  }
6962
6950
 
6951
+ function configuredRemoteForRef(remoteRef, remoteNames = []) {
6952
+ return remoteNames
6953
+ .filter((remoteName) => remoteRef.startsWith(`${remoteName}/`))
6954
+ .sort((left, right) => right.length - left.length || left.localeCompare(right))[0] || "";
6955
+ }
6956
+
6957
+ function remoteBranchRecord(fullRef, symref = "", remoteNames = []) {
6958
+ const prefix = "refs/remotes/";
6959
+ const ref = String(fullRef || "");
6960
+ if (!ref.startsWith(prefix) || symref) return null;
6961
+ const remoteRef = ref.slice(prefix.length);
6962
+ const remoteName = configuredRemoteForRef(remoteRef, remoteNames);
6963
+ if (!remoteName) return null;
6964
+ const name = remoteRef.slice(remoteName.length + 1);
6965
+ if (!name) return null;
6966
+ return { name, current: false, remote: true, remoteRef, remoteName, displayName: remoteRef };
6967
+ }
6968
+
6969
+ async function readRemoteGitBranchData(root) {
6970
+ const [remoteNamesText, refs] = await Promise.all([
6971
+ runGitReadCommand(root, ["remote"], { timeoutMs: 5000, maxOutputLength: 120_000 }),
6972
+ runGitReadCommandDetailed(root, ["for-each-ref", "--format=%(refname)%09%(symref)", "refs/remotes"], { timeoutMs: 5000, maxOutputLength: 120_000 }),
6973
+ ]);
6974
+ return {
6975
+ remoteNames: remoteNamesText.split(/\r?\n/).map((line) => line.trim()).filter(Boolean),
6976
+ refText: refs.output,
6977
+ truncated: refs.truncated === true,
6978
+ unavailable: false,
6979
+ };
6980
+ }
6981
+
6982
+ function normalizeRemoteGitBranches(remoteData, localBranchNames) {
6983
+ // Never parse tail-truncated output: the first retained line may be a partial
6984
+ // ref. Local branches and worktrees remain available while the UI can expose
6985
+ // the truncation flag.
6986
+ if (!remoteData || remoteData.truncated) return [];
6987
+ const remoteBranches = [];
6988
+ for (const line of String(remoteData.refText || "").split(/\r?\n/)) {
6989
+ const [fullRef = "", symref = ""] = line.split("\t", 2);
6990
+ const branch = remoteBranchRecord(fullRef, symref, remoteData.remoteNames);
6991
+ // A local branch takes precedence over every same-named remote ref. Until
6992
+ // then, retain each exact remote ref so multiple remotes stay unambiguous.
6993
+ if (branch && !localBranchNames.has(branch.name)) remoteBranches.push(branch);
6994
+ }
6995
+ return remoteBranches.sort((left, right) => left.displayName.localeCompare(right.displayName));
6996
+ }
6997
+
6963
6998
  async function readGitBranches(cwd) {
6964
6999
  const root = await getGitRoot(cwd);
6965
- const [current, branchText, worktreeData] = await Promise.all([
7000
+ const [current, branchText, worktreeData, remoteData] = await Promise.all([
6966
7001
  currentGitBranchForPicker(root),
6967
- runGitReadCommand(root, ["branch", "--format=%(refname:short)"], { timeoutMs: 5000, maxOutputLength: 120_000 }),
7002
+ runGitReadCommand(root, ["branch", "--format=%(refname:lstrip=2)"], { timeoutMs: 5000, maxOutputLength: 120_000 }),
6968
7003
  listGitWorktrees(cwd).catch(() => null),
7004
+ readRemoteGitBranchData(root).catch(() => ({ remoteNames: [], refText: "", truncated: false, unavailable: true })),
6969
7005
  ]);
6970
7006
  const occupiedByBranch = new Map();
6971
7007
  for (const item of worktreeData?.occupiedBranches || []) {
6972
7008
  if (!item?.branch || occupiedByBranch.has(item.branch)) continue;
6973
7009
  occupiedByBranch.set(item.branch, item);
6974
7010
  }
7011
+ const localBranches = normalizeGitBranchList(branchText, current).map((branch) => {
7012
+ const occupied = occupiedByBranch.get(branch.name);
7013
+ return occupied ? { ...branch, occupied: true, worktreePath: occupied.path, worktreeCurrent: occupied.current === true, mainWorktree: occupied.isMainWorktree === true } : branch;
7014
+ });
7015
+ const remoteBranches = normalizeRemoteGitBranches(remoteData, new Set(localBranches.map((branch) => branch.name)));
6975
7016
  return {
6976
7017
  cwd,
6977
7018
  root,
@@ -6981,24 +7022,60 @@ async function readGitBranches(cwd) {
6981
7022
  defaultWorktreesRoot: worktreeData?.defaultWorktreesRoot || "",
6982
7023
  current,
6983
7024
  generatedAt: new Date().toISOString(),
6984
- branches: normalizeGitBranchList(branchText, current).map((branch) => {
6985
- const occupied = occupiedByBranch.get(branch.name);
6986
- return occupied ? { ...branch, occupied: true, worktreePath: occupied.path, worktreeCurrent: occupied.current === true, mainWorktree: occupied.isMainWorktree === true } : branch;
6987
- }),
7025
+ branches: [...localBranches, ...remoteBranches],
7026
+ remoteBranchesTruncated: remoteData.truncated === true,
7027
+ remoteBranchesUnavailable: remoteData.unavailable === true,
6988
7028
  worktrees: worktreeData?.worktrees || [],
6989
7029
  occupiedBranches: worktreeData?.occupiedBranches || [],
6990
7030
  };
6991
7031
  }
6992
7032
 
6993
- async function switchGitBranch(cwd, branch, { create = false } = {}) {
7033
+ function requestedRemoteRef(body = {}) {
7034
+ if (!Object.hasOwn(body, "remoteRef")) return null;
7035
+ if (typeof body.remoteRef !== "string" || !body.remoteRef || body.remoteRef.trim() !== body.remoteRef) {
7036
+ throw new Error("remoteRef must be a non-empty exact remote-tracking ref");
7037
+ }
7038
+ return body.remoteRef;
7039
+ }
7040
+
7041
+ async function verifyRemoteGitBranchIntent(cwd, branch, remoteRef) {
7042
+ const targetBranch = cleanGitBranchName(branch);
7043
+ const branches = await readGitBranches(cwd);
7044
+ const localBranch = branches.branches.find((item) => item.remote !== true && item.name === targetBranch);
7045
+ if (localBranch) throw new Error(`Local git branch already exists: ${targetBranch}. Refresh the picker and use the local branch instead.`);
7046
+ const remoteBranch = branches.branches.find((item) => item.remote === true && item.remoteRef === remoteRef);
7047
+ if (!remoteBranch) throw new Error(`Unknown remote git branch: ${remoteRef}`);
7048
+ if (remoteBranch.name !== targetBranch) {
7049
+ throw new Error(`Remote git branch ${remoteRef} does not match local branch ${targetBranch}`);
7050
+ }
7051
+ return { root: branches.root, branch: targetBranch, remoteRef: remoteBranch.remoteRef };
7052
+ }
7053
+
7054
+ async function switchGitBranch(cwd, branch, { create = false, remoteRef = null } = {}) {
7055
+ if (remoteRef !== null) {
7056
+ // Re-read the advertised remote-only record immediately before creating a
7057
+ // tracking branch. This rejects stale refs and local-name collisions.
7058
+ const intent = await verifyRemoteGitBranchIntent(cwd, branch, remoteRef);
7059
+ const payload = gitMutationPayload(await runGitMutationCommand(["switch", "--track", "-c", intent.branch, intent.remoteRef], { cwd: intent.root, timeoutMs: 10 * 60 * 1000 }));
7060
+ if (payload.ok) {
7061
+ payload.data.branch = intent.branch;
7062
+ payload.data.root = intent.root;
7063
+ payload.data.switched = true;
7064
+ payload.data.created = true;
7065
+ } else {
7066
+ payload.error = (payload.data?.stderr || payload.data?.stdout || payload.error || `Failed to create and switch to ${intent.branch}`).trim();
7067
+ }
7068
+ return payload;
7069
+ }
7070
+
6994
7071
  const root = await getGitRoot(cwd);
6995
7072
  const targetBranch = cleanGitBranchName(branch);
6996
7073
  await validateGitBranchName(root, targetBranch);
6997
7074
  const branches = await readGitBranches(cwd);
6998
- const branchExists = branches.branches.some((item) => item.name === targetBranch);
7075
+ const branchExists = branches.branches.some((item) => item.remote !== true && item.name === targetBranch);
6999
7076
  if (create && branchExists) throw new Error(`Local git branch already exists: ${targetBranch}`);
7000
7077
  if (!create && !branchExists) throw new Error(`Unknown local git branch: ${targetBranch}`);
7001
- const occupied = branches.branches.find((item) => item.name === targetBranch && item.occupied && !item.worktreeCurrent);
7078
+ const occupied = branches.branches.find((item) => item.remote !== true && item.name === targetBranch && item.occupied && !item.worktreeCurrent);
7002
7079
  if (!create && occupied?.worktreePath) {
7003
7080
  return {
7004
7081
  ok: false,
@@ -7243,9 +7320,13 @@ async function createGitWorkflowBranchWorktree(tab, body = {}) {
7243
7320
  }
7244
7321
 
7245
7322
  async function createGitWorktreeTab(tab, body = {}) {
7323
+ const remoteRef = requestedRemoteRef(body);
7324
+ const worktreeRequest = remoteRef === null
7325
+ ? body
7326
+ : { ...body, branchName: (await verifyRemoteGitBranchIntent(tab.cwd, body.branchName || body.branch, remoteRef)).branch, remoteRef };
7246
7327
  let createdResult = null;
7247
7328
  try {
7248
- createdResult = await createGitWorktree(tab.cwd, body);
7329
+ createdResult = await createGitWorktree(tab.cwd, worktreeRequest);
7249
7330
  const opened = await openWorktreeResultForTab(tab, createdResult, { openTab: body.openTab !== false, ...body });
7250
7331
  if (createdResult.created) {
7251
7332
  recordEvent({ type: "webui_worktree_created", tabId: opened.tab?.id || tab.id, cwd: opened.worktree?.path || opened.path, branch: opened.branch || body.branchName || "" });
@@ -7291,10 +7372,14 @@ function sendGitWorktreeFailure(res, error) {
7291
7372
  sendJson(res, 200, gitWorktreeErrorPayload(error));
7292
7373
  }
7293
7374
 
7294
- async function defaultGitRemote(root) {
7375
+ async function gitRemoteNames(root) {
7295
7376
  const result = await runGitWorkflowCommand(["remote"], { cwd: root, timeoutMs: 5000 });
7296
7377
  if (result.exitCode !== 0) throw new Error((result.stderr || result.stdout || "Cannot list git remotes").trim());
7297
- const remotes = result.stdout.split("\n").map((line) => line.trim()).filter(Boolean);
7378
+ return result.stdout.split("\n").map((line) => line.trim()).filter(Boolean);
7379
+ }
7380
+
7381
+ async function defaultGitRemote(root) {
7382
+ const remotes = await gitRemoteNames(root);
7298
7383
  if (!remotes.length) throw new Error("No git remote is configured for this repository");
7299
7384
  return remotes.includes("origin") ? "origin" : remotes[0];
7300
7385
  }
@@ -7409,6 +7494,20 @@ function gitWorkflowCommandPayload(result) {
7409
7494
  };
7410
7495
  }
7411
7496
 
7497
+ function applyGitHubPublicationFailure(payload) {
7498
+ if (payload.ok) return payload;
7499
+ const text = `${payload.data?.stderr || ""}\n${payload.data?.stdout || ""}\n${payload.data?.error || ""}`.toLowerCase();
7500
+ if (payload.data?.errorCode === "ENOENT") {
7501
+ payload.hint = "Install GitHub CLI (gh), ensure it is on PATH, then retry.";
7502
+ } else if (/not logged into any github hosts|gh auth login|http 401|bad credentials/.test(text)) {
7503
+ payload.code = "AUTH";
7504
+ payload.hint = "GitHub CLI is not authenticated. Run 'gh auth login' in a terminal, then retry.";
7505
+ } else if (/name already exists on this account|repository .+ already exists/.test(text)) {
7506
+ payload.hint = "A GitHub repository with this name already exists for the authenticated account. Choose another repository name and retry.";
7507
+ }
7508
+ return payload;
7509
+ }
7510
+
7412
7511
  // Read-only workflow lookups are safe over GET; everything else mutates the
7413
7512
  // repository (or process state, for cancel) and must be POST. Method + access
7414
7513
  // guard are enforced at the router before dispatch — never dispatch on path
@@ -7433,6 +7532,7 @@ const GIT_WORKFLOW_MUTATING_PATHS = new Set([
7433
7532
  "/api/git-workflow/branch",
7434
7533
  "/api/git-workflow/commit",
7435
7534
  "/api/git-workflow/push",
7535
+ "/api/git-workflow/publish",
7436
7536
  "/api/git-workflow/create-pr",
7437
7537
  "/api/git-workflow/cancel",
7438
7538
  ]);
@@ -7545,6 +7645,23 @@ async function handleGitWorkflowRequest(pathname, body = {}, tabOrCwd = options.
7545
7645
  }
7546
7646
  return applyGitSyncFailure(payload, { push: true });
7547
7647
  }
7648
+ case "/api/git-workflow/publish": {
7649
+ const repoName = cleanGitHubRepoName(body.repoName);
7650
+ const visibility = String(body.visibility || "").trim();
7651
+ if (visibility !== "public" && visibility !== "private") throw makeHttpError(400, "visibility must be 'public' or 'private'");
7652
+ requireConfirmed(body, `Publishing GitHub repository ${repoName} as ${visibility}`);
7653
+ const root = await getGitRoot(cwd);
7654
+ const remotes = await gitRemoteNames(root);
7655
+ if (remotes.length) throw makeHttpError(409, "GitHub publication requires a repository with no configured remotes. Existing remotes are not changed or repaired.");
7656
+ const branch = await currentGitBranch(root);
7657
+ const protectedBranch = PROTECTED_GIT_BRANCHES.has(branch);
7658
+ const payload = applyGitHubPublicationFailure(gitWorkflowCommandPayload(await runGitHubWorkflowCommand(
7659
+ ["repo", "create", repoName, `--${visibility}`, "--source", root, "--remote", "origin", "--push"],
7660
+ { cwd: root, timeoutMs: 15 * 60 * 1000 },
7661
+ )));
7662
+ if (payload.ok) Object.assign(payload.data, { repoName, visibility, remote: "origin", branch, protectedBranch });
7663
+ return payload;
7664
+ }
7548
7665
  case "/api/git-workflow/create-pr": {
7549
7666
  const root = await getGitRoot(cwd);
7550
7667
  const branch = await currentGitBranch(root);
@@ -7752,7 +7869,7 @@ async function serveStatic(req, res, url) {
7752
7869
  function requestBodyLimitForPath(pathname) {
7753
7870
  if (pathname === "/api/attachments") return UPLOAD_BODY_LIMIT_BYTES;
7754
7871
  if (pathname === "/api/files/content") return FILE_VIEWER_BODY_LIMIT_BYTES;
7755
- if (["/api/prompt", "/api/steer", "/api/follow-up"].includes(pathname)) return PROMPT_BODY_LIMIT_BYTES;
7872
+ if (["/api/prompt", "/api/steer", "/api/follow-up", "/api/queue/mutate"].includes(pathname)) return PROMPT_BODY_LIMIT_BYTES;
7756
7873
  return BODY_LIMIT_BYTES;
7757
7874
  }
7758
7875
 
@@ -8275,6 +8392,7 @@ let rpcSupervisor = null;
8275
8392
  let rpcSupervisorSnapshot = null;
8276
8393
  let rpcSupervisorEventUnsubscribe = null;
8277
8394
  let rpcSupervisorSequenceState = null;
8395
+ let workspaceLoadInProgress = false;
8278
8396
 
8279
8397
  function markRpcSupervisorDiscontinuity(reason) {
8280
8398
  if (!rpcSupervisorSnapshot) return;
@@ -8508,8 +8626,9 @@ function responseWithPendingThinking(tab, response) {
8508
8626
  }
8509
8627
 
8510
8628
  function eventForTabClients(tab, event) {
8629
+ const decorated = event?.type === "queue_update" ? { ...event, source: "pi-runtime" } : event;
8511
8630
  return {
8512
- ...rewriteArtifactsForTab(tab, responseWithPendingThinking(tab, event)),
8631
+ ...rewriteArtifactsForTab(tab, responseWithPendingThinking(tab, decorated)),
8513
8632
  tabId: tab.id,
8514
8633
  tabTitle: tab.title,
8515
8634
  tabActivity: tabActivitySnapshot(tab),
@@ -8615,14 +8734,18 @@ function normalizeWebuiSubagentPayload(value) {
8615
8734
  if (!rawRun || typeof rawRun !== "object") continue;
8616
8735
  const id = normalizeWebuiSubagentText(rawRun.id, 160);
8617
8736
  if (!id) continue;
8737
+ const status = ["running", "done", "failed", "cancelled"].includes(rawRun.status) ? rawRun.status : "running";
8618
8738
  const agents = [];
8619
8739
  for (const rawAgent of Array.isArray(rawRun.agents) ? rawRun.agents.slice(0, WEBUI_SUBAGENT_AGENT_LIMIT) : []) {
8620
8740
  const name = normalizeWebuiSubagentText(rawAgent?.name, 160);
8621
- if (!name || rawAgent?.status !== "running") continue;
8741
+ const agentStatus = ["running", "done", "failed", "cancelled"].includes(rawAgent?.status)
8742
+ ? rawAgent.status
8743
+ : status === "cancelled" ? "cancelled" : status === "running" ? "running" : "done";
8744
+ if (!name || (status === "running" && agentStatus !== "running")) continue;
8622
8745
  agents.push({
8623
8746
  id: normalizeWebuiSubagentText(rawAgent.id || `${id}:${agents.length}`, 240),
8624
8747
  name,
8625
- status: "running",
8748
+ status: agentStatus,
8626
8749
  index: Number.isInteger(rawAgent.index) ? rawAgent.index : agents.length,
8627
8750
  currentTool: normalizeWebuiSubagentText(rawAgent.currentTool, 120) || undefined,
8628
8751
  activityState: normalizeWebuiSubagentText(rawAgent.activityState, 80) || undefined,
@@ -8631,13 +8754,17 @@ function normalizeWebuiSubagentPayload(value) {
8631
8754
  nested: rawAgent.nested === true,
8632
8755
  });
8633
8756
  }
8634
- if (!agents.length) continue;
8757
+ if (status === "running" && !agents.length) continue;
8635
8758
  runs.push({
8636
8759
  id,
8637
8760
  source: normalizeWebuiSubagentSource(rawRun.source),
8638
8761
  mode: ["single", "parallel", "chain"].includes(rawRun.mode) ? rawRun.mode : "single",
8639
- status: "running",
8762
+ status,
8640
8763
  startedAt: Number.isFinite(rawRun.startedAt) ? rawRun.startedAt : Date.now(),
8764
+ endedAt: status === "running" ? undefined : Number.isFinite(rawRun.endedAt) ? rawRun.endedAt : undefined,
8765
+ cancelReason: status === "cancelled" ? normalizeWebuiSubagentText(rawRun.cancelReason, 120) || undefined : undefined,
8766
+ cancelNote: status === "cancelled" ? normalizeWebuiSubagentText(rawRun.cancelNote, 2000) || undefined : undefined,
8767
+ cancelledBy: status === "cancelled" && rawRun.cancelledBy === "user" ? "user" : undefined,
8641
8768
  agents: agents.sort((a, b) => a.index - b.index || a.name.localeCompare(b.name)),
8642
8769
  });
8643
8770
  }
@@ -8845,6 +8972,75 @@ function compactionQueueForTab(tab) {
8845
8972
  return tab.compactionQueue;
8846
8973
  }
8847
8974
 
8975
+ function compactionQueueRevision(tab) {
8976
+ if (!Number.isSafeInteger(tab.compactionQueueRevision) || tab.compactionQueueRevision < 0) tab.compactionQueueRevision = 0;
8977
+ return tab.compactionQueueRevision;
8978
+ }
8979
+
8980
+ function advanceCompactionQueueRevision(tab) {
8981
+ tab.compactionQueueRevision = compactionQueueRevision(tab) + 1;
8982
+ return tab.compactionQueueRevision;
8983
+ }
8984
+
8985
+ function queueMutationText(value, label, { allowBlank = false, normalize = true } = {}) {
8986
+ if (typeof value !== "string") throw makeHttpError(400, `${label} must be a string`);
8987
+ if (Buffer.byteLength(value, "utf8") > PROMPT_BODY_LIMIT_BYTES) throw makeHttpError(413, `${label} is too large`);
8988
+ if (!allowBlank && !value.trim()) throw makeHttpError(400, `${label} is required`);
8989
+ if (value.includes("\0")) throw makeHttpError(400, `${label} contains a NUL byte`);
8990
+ return normalize ? value.trim() : value;
8991
+ }
8992
+
8993
+ function queueMutationExpected(body) {
8994
+ const expected = body?.expected;
8995
+ if (!expected || typeof expected !== "object" || !Array.isArray(expected.steering) || !Array.isArray(expected.followUp)) {
8996
+ throw makeHttpError(400, "Queue mutation requires complete expected steering and followUp arrays");
8997
+ }
8998
+ if (expected.steering.length > QUEUE_MUTATION_MAX_ITEMS || expected.followUp.length > QUEUE_MUTATION_MAX_ITEMS) {
8999
+ throw makeHttpError(400, `Queue mutation expected arrays may contain at most ${QUEUE_MUTATION_MAX_ITEMS} items`);
9000
+ }
9001
+ return {
9002
+ steering: expected.steering.map((item, index) => queueMutationText(item, `expected.steering[${index}]`, { normalize: false })),
9003
+ followUp: expected.followUp.map((item, index) => queueMutationText(item, `expected.followUp[${index}]`, { normalize: false })),
9004
+ };
9005
+ }
9006
+
9007
+ function queueMutationIndex(value, label) {
9008
+ if (!Number.isSafeInteger(value) || value < 0) throw makeHttpError(400, `${label} must be a non-negative integer`);
9009
+ return value;
9010
+ }
9011
+
9012
+ function queueMutationRequest(body) {
9013
+ if (!body || typeof body !== "object") throw makeHttpError(400, "Queue mutation body must be an object");
9014
+ const source = String(body.source || "");
9015
+ if (source !== "pi-runtime" && source !== "webui-compaction") throw makeHttpError(400, "Queue mutation source must be pi-runtime or webui-compaction");
9016
+ if (body.kind !== "followUp") throw makeHttpError(400, "Queue mutation kind must be followUp");
9017
+ const operation = body.operation;
9018
+ if (!operation || typeof operation !== "object") throw makeHttpError(400, "Queue mutation operation is required");
9019
+ const expectedText = queueMutationText(operation.expectedText, "operation.expectedText", { normalize: false });
9020
+ const request = {
9021
+ source,
9022
+ kind: "followUp",
9023
+ expected: queueMutationExpected(body),
9024
+ operation: { type: String(operation.type || ""), expectedText },
9025
+ };
9026
+ if (request.operation.type === "edit") {
9027
+ request.operation.index = queueMutationIndex(operation.index, "operation.index");
9028
+ request.operation.text = queueMutationText(operation.text, "operation.text");
9029
+ } else if (request.operation.type === "move") {
9030
+ request.operation.from = queueMutationIndex(operation.from, "operation.from");
9031
+ request.operation.to = queueMutationIndex(operation.to, "operation.to");
9032
+ } else {
9033
+ throw makeHttpError(400, "Queue mutation operation type must be edit or move");
9034
+ }
9035
+ if (source === "webui-compaction") {
9036
+ if (!Number.isSafeInteger(body.revision) || body.revision < 0) throw makeHttpError(400, "Compaction queue mutation requires a non-negative revision");
9037
+ request.revision = body.revision;
9038
+ } else if (Object.hasOwn(body, "revision")) {
9039
+ throw makeHttpError(400, "Pi runtime queue mutation must not include a revision");
9040
+ }
9041
+ return request;
9042
+ }
9043
+
8848
9044
  function queueableCompactionCommand(command) {
8849
9045
  return ["prompt", "steer", "follow_up"].includes(command?.type) && !!String(command.message || "").trim();
8850
9046
  }
@@ -8864,7 +9060,7 @@ function compactQueuedCommand(command) {
8864
9060
  return queued;
8865
9061
  }
8866
9062
 
8867
- function compactionQueueEvent(tab, extra = {}) {
9063
+ function compactionQueueSnapshot(tab) {
8868
9064
  const queue = compactionQueueForTab(tab);
8869
9065
  const steering = [];
8870
9066
  const followUp = [];
@@ -8874,20 +9070,67 @@ function compactionQueueEvent(tab, extra = {}) {
8874
9070
  if (item.command.mode === "followUp") followUp.push(message);
8875
9071
  else steering.push(message);
8876
9072
  }
9073
+ return {
9074
+ source: "webui-compaction",
9075
+ revision: compactionQueueRevision(tab),
9076
+ steering,
9077
+ followUp,
9078
+ draining: tab.compactionQueueDraining === true,
9079
+ };
9080
+ }
9081
+
9082
+ function compactionQueueEvent(tab, extra = {}) {
9083
+ const queue = compactionQueueForTab(tab);
8877
9084
  return {
8878
9085
  type: "webui_compaction_queue_update",
8879
9086
  tabId: tab.id,
8880
9087
  tabTitle: tab.title,
8881
9088
  queueLength: queue.length,
8882
9089
  pendingMessageCount: queue.length,
8883
- steering,
8884
- followUp,
8885
- draining: tab.compactionQueueDraining === true,
9090
+ ...compactionQueueSnapshot(tab),
8886
9091
  tabActivity: tabActivitySnapshot(tab),
8887
9092
  ...extra,
8888
9093
  };
8889
9094
  }
8890
9095
 
9096
+ function sameQueueSnapshot(expected, current) {
9097
+ return expected.steering.length === current.steering.length
9098
+ && expected.followUp.length === current.followUp.length
9099
+ && expected.steering.every((item, index) => item === current.steering[index])
9100
+ && expected.followUp.every((item, index) => item === current.followUp[index]);
9101
+ }
9102
+
9103
+ function compactionFollowUpSlots(queue) {
9104
+ return queue.flatMap((item, index) => item?.command?.mode === "followUp" && String(item.command.message || "").trim() ? [index] : []);
9105
+ }
9106
+
9107
+ function mutateCompactionFollowUpQueue(tab, request) {
9108
+ const queue = compactionQueueForTab(tab);
9109
+ const current = compactionQueueSnapshot(tab);
9110
+ const failed = (reason) => ({ mutated: false, reason, source: "webui-compaction", queue: compactionQueueSnapshot(tab) });
9111
+ if (current.draining) return failed("queue-draining");
9112
+ if (request.revision !== current.revision || !sameQueueSnapshot(request.expected, current)) return failed("queue-changed");
9113
+
9114
+ const slots = compactionFollowUpSlots(queue);
9115
+ const operation = request.operation;
9116
+ if (operation.type === "edit") {
9117
+ if (operation.index >= slots.length || current.followUp[operation.index] !== operation.expectedText) return failed("invalid-request");
9118
+ queue[slots[operation.index]].command.message = operation.text;
9119
+ } else {
9120
+ if (operation.from >= slots.length || operation.to >= slots.length || operation.from === operation.to
9121
+ || current.followUp[operation.from] !== operation.expectedText) return failed("invalid-request");
9122
+ const followUps = slots.map((index) => queue[index]);
9123
+ const [moved] = followUps.splice(operation.from, 1);
9124
+ followUps.splice(operation.to, 0, moved);
9125
+ slots.forEach((slot, index) => { queue[slot] = followUps[index]; });
9126
+ }
9127
+
9128
+ advanceCompactionQueueRevision(tab);
9129
+ const result = { mutated: true, source: "webui-compaction", queue: compactionQueueSnapshot(tab) };
9130
+ broadcastTabEvent(tab, compactionQueueEvent(tab));
9131
+ return result;
9132
+ }
9133
+
8891
9134
  function enqueueCommandUntilCompactionEnds(tab, command) {
8892
9135
  const queue = compactionQueueForTab(tab);
8893
9136
  const item = {
@@ -8896,6 +9139,7 @@ function enqueueCommandUntilCompactionEnds(tab, command) {
8896
9139
  enqueuedAt: new Date().toISOString(),
8897
9140
  };
8898
9141
  queue.push(item);
9142
+ advanceCompactionQueueRevision(tab);
8899
9143
  broadcastTabEvent(tab, compactionQueueEvent(tab, { queuedId: item.id }));
8900
9144
  return rpcSuccess(command.type, {
8901
9145
  queued: true,
@@ -8940,6 +9184,7 @@ function requeueCompactionItems(tab, items) {
8940
9184
  if (!items?.length) return;
8941
9185
  const queue = compactionQueueForTab(tab);
8942
9186
  queue.unshift(...items);
9187
+ advanceCompactionQueueRevision(tab);
8943
9188
  broadcastTabEvent(tab, compactionQueueEvent(tab));
8944
9189
  }
8945
9190
 
@@ -8956,6 +9201,7 @@ async function flushCompactionQueue(tab, event = {}) {
8956
9201
  if (!queue.length || tab.compactionQueueDraining) return;
8957
9202
  const items = queue.splice(0);
8958
9203
  tab.compactionQueueDraining = true;
9204
+ advanceCompactionQueueRevision(tab);
8959
9205
  broadcastTabEvent(tab, compactionQueueEvent(tab));
8960
9206
  const remaining = [...items];
8961
9207
  try {
@@ -9310,6 +9556,7 @@ function attachRpcToTab(tab, rpc) {
9310
9556
  clearExtensionWidgets(tab);
9311
9557
  clearWebuiSubagents(tab);
9312
9558
  resetNaturalConversationMode(tab);
9559
+ resetCodexFastMode(tab);
9313
9560
  } else {
9314
9561
  rememberExtensionStatusEvent(tab, scopedEvent);
9315
9562
  rememberNaturalConversationStatusEvent(tab, scopedEvent);
@@ -9349,6 +9596,7 @@ function createTabRecord({ id, index, title, titleSource, conversationStarted, c
9349
9596
  bashQueue: [],
9350
9597
  bashQueueDraining: false,
9351
9598
  compactionQueue: [],
9599
+ compactionQueueRevision: 0,
9352
9600
  compactionQueueDraining: false,
9353
9601
  cwdChangeInProgress: false,
9354
9602
  rpc,
@@ -9356,6 +9604,7 @@ function createTabRecord({ id, index, title, titleSource, conversationStarted, c
9356
9604
  sseClients: new Set(),
9357
9605
  };
9358
9606
  resetNaturalConversationMode(tab);
9607
+ resetCodexFastMode(tab);
9359
9608
  return tab;
9360
9609
  }
9361
9610
 
@@ -9519,6 +9768,8 @@ function webuiSubagentsData() {
9519
9768
  runs,
9520
9769
  gates,
9521
9770
  agentCount: runs.reduce((count, run) => count + run.agents.length, 0),
9771
+ runningRuns: runs.filter((run) => run.status === "running").length,
9772
+ runningAgents: runs.reduce((count, run) => count + run.agents.filter((agent) => agent.status === "running").length, 0),
9522
9773
  gateCount: gates.length,
9523
9774
  };
9524
9775
  });
@@ -9528,6 +9779,8 @@ function webuiSubagentsData() {
9528
9779
  available: tabSummaries.some((tab) => tab.available),
9529
9780
  totalRuns: tabSummaries.reduce((count, tab) => count + tab.runs.length, 0),
9530
9781
  totalAgents: tabSummaries.reduce((count, tab) => count + tab.agentCount, 0),
9782
+ runningRuns: tabSummaries.reduce((count, tab) => count + tab.runningRuns, 0),
9783
+ runningAgents: tabSummaries.reduce((count, tab) => count + tab.runningAgents, 0),
9531
9784
  totalGates: tabSummaries.reduce((count, tab) => count + tab.gateCount, 0),
9532
9785
  tabs: tabSummaries,
9533
9786
  };
@@ -9651,9 +9904,9 @@ function normalizeWebuiSubagentOutput(value, selection) {
9651
9904
  async function webuiSubagentOutputData(tab, runId, agentId) {
9652
9905
  const runs = Array.isArray(tab.webuiSubagents?.runs) ? tab.webuiSubagents.runs : [];
9653
9906
  const run = runs.find((candidate) => candidate.id === runId);
9654
- if (!run) throw makeHttpError(404, `Running subagent run not found: ${runId}`);
9907
+ if (!run) throw makeHttpError(404, `Subagent run not found: ${runId}`);
9655
9908
  const agent = (Array.isArray(run.agents) ? run.agents : []).find((candidate) => candidate.id === agentId);
9656
- if (!agent) throw makeHttpError(404, `Running subagent not found: ${agentId}`);
9909
+ if (!agent) throw makeHttpError(404, `Subagent not found: ${agentId}`);
9657
9910
  const data = await sendWebuiHelperCommand(tab, "subagent-output", { runId, agentId });
9658
9911
  return normalizeWebuiSubagentOutput(data, { run, agent });
9659
9912
  }
@@ -9706,6 +9959,140 @@ async function restorableTabsForRestart() {
9706
9959
  return mergeRestorableTabDescriptors(liveDescriptors);
9707
9960
  }
9708
9961
 
9962
+ function workspaceLoadWarning(savedTabId, code, message) {
9963
+ return { savedTabId, code, message };
9964
+ }
9965
+
9966
+ async function workspaceLoadDescriptor(descriptor, warnings) {
9967
+ const next = { ...descriptor };
9968
+ if (next.sessionFile) {
9969
+ const sessionInfo = await stat(next.sessionFile).catch(() => null);
9970
+ if (!sessionInfo?.isFile()) {
9971
+ delete next.sessionFile;
9972
+ warnings.push(workspaceLoadWarning(descriptor.id, "missing_session_file", "The saved session file is unavailable; opened a fresh session instead."));
9973
+ }
9974
+ }
9975
+ try {
9976
+ next.cwd = await resolveCwd(next.cwd, options.cwd);
9977
+ } catch {
9978
+ next.cwd = options.cwd;
9979
+ warnings.push(workspaceLoadWarning(descriptor.id, "missing_cwd", "The saved working directory is unavailable; opened in the default directory instead."));
9980
+ }
9981
+ return next;
9982
+ }
9983
+
9984
+ function workspaceReplacementIntent(body) {
9985
+ if (!body || typeof body !== "object" || Array.isArray(body) || body.replaceOpenTabs !== true) {
9986
+ throw makeHttpError(400, "Replacing open tabs requires replaceOpenTabs: true and one save or discard decision");
9987
+ }
9988
+ const hasDiscard = Object.hasOwn(body, "discardCurrent");
9989
+ const hasSave = Object.hasOwn(body, "saveCurrent");
9990
+ if (hasDiscard === hasSave) {
9991
+ throw makeHttpError(400, "Choose exactly one of discardCurrent or saveCurrent when replacing open tabs");
9992
+ }
9993
+ if (hasDiscard) {
9994
+ if (body.discardCurrent !== true) throw makeHttpError(400, "discardCurrent must be true when replacing open tabs");
9995
+ return { discardCurrent: true };
9996
+ }
9997
+ if (!body.saveCurrent || typeof body.saveCurrent !== "object" || Array.isArray(body.saveCurrent)) {
9998
+ throw makeHttpError(400, "saveCurrent must be an object when replacing open tabs");
9999
+ }
10000
+ return { saveCurrent: body.saveCurrent };
10001
+ }
10002
+
10003
+ function openTabsUnchanged(tabIds) {
10004
+ return tabs.size === tabIds.length && tabIds.every((id) => tabs.has(id));
10005
+ }
10006
+
10007
+ async function saveCurrentWorkspaceForReplacement(saveCurrent, tabIds) {
10008
+ const descriptors = await restorableTabsForRestart();
10009
+ const descriptorIds = new Set(descriptors.map((descriptor) => descriptor.id));
10010
+ if (descriptors.length !== tabIds.length || tabIds.some((id) => !descriptorIds.has(id))) {
10011
+ throw makeHttpError(400, `Only ${RESTORE_TAB_LIMIT} open tabs can be saved; close some tabs or choose Load without saving`);
10012
+ }
10013
+ try {
10014
+ return await saveWebuiWorkspace({
10015
+ name: saveCurrent.name,
10016
+ groups: saveCurrent.groups,
10017
+ activeTabId: saveCurrent.activeTabId,
10018
+ overwrite: saveCurrent.overwrite === true,
10019
+ tabs: descriptors,
10020
+ });
10021
+ } catch (error) {
10022
+ if (error?.code === "WORKSPACE_NAME_CONFLICT") throw makeHttpError(409, error.message);
10023
+ throw error;
10024
+ }
10025
+ }
10026
+
10027
+ async function loadWebuiWorkspace(id, body = {}) {
10028
+ if (workspaceLoadInProgress) throw makeHttpError(409, "A workspace load is already in progress");
10029
+ workspaceLoadInProgress = true;
10030
+ try {
10031
+ const workspace = await getWebuiWorkspace(id);
10032
+ if (!workspace) throw makeHttpError(404, "Workspace not found");
10033
+
10034
+ const openTabIds = [...tabs.keys()];
10035
+ let closedIds = [];
10036
+ let savedCurrent;
10037
+ if (openTabIds.length) {
10038
+ const intent = workspaceReplacementIntent(body);
10039
+ if (intent.saveCurrent) {
10040
+ savedCurrent = await saveCurrentWorkspaceForReplacement(intent.saveCurrent, openTabIds);
10041
+ broadcastServerEvent({
10042
+ type: "webui_workspace_saved",
10043
+ workspaceId: savedCurrent.workspace.id,
10044
+ workspaceName: savedCurrent.workspace.name,
10045
+ tabCount: savedCurrent.workspace.tabCount,
10046
+ evictedIds: savedCurrent.evicted.map((workspace) => workspace.id),
10047
+ });
10048
+ }
10049
+ if (!openTabsUnchanged(openTabIds)) {
10050
+ const savedNote = savedCurrent ? "The current workspace was saved, but " : "";
10051
+ throw makeHttpError(409, `${savedNote}open tabs changed before the workspace could be replaced`);
10052
+ }
10053
+ closedIds = (await closeTabs(openTabIds, { allowEmpty: true })).map((tab) => tab.id);
10054
+ }
10055
+
10056
+ const warnings = [];
10057
+ const idMap = {};
10058
+ for (const descriptor of workspace.tabs) {
10059
+ const preflighted = await workspaceLoadDescriptor(descriptor, warnings);
10060
+ try {
10061
+ const tab = await createTab(preflighted);
10062
+ idMap[descriptor.id] = tab.id;
10063
+ } catch (error) {
10064
+ warnings.push(workspaceLoadWarning(descriptor.id, "tab_create_failed", `Could not restore this tab: ${sanitizeError(error)}`));
10065
+ }
10066
+ }
10067
+ const groups = workspace.groups.map((group) => ({
10068
+ title: group.title,
10069
+ tabIds: group.tabIds.map((tabId) => idMap[tabId]).filter(Boolean),
10070
+ })).filter((group) => group.tabIds.length);
10071
+ const activeTabId = workspace.activeTabId ? idMap[workspace.activeTabId] || null : null;
10072
+ const data = {
10073
+ tabs: listTabs(),
10074
+ idMap,
10075
+ groups,
10076
+ activeTabId,
10077
+ warnings,
10078
+ closedIds,
10079
+ ...(savedCurrent ? { savedCurrent } : {}),
10080
+ };
10081
+ broadcastServerEvent({
10082
+ type: "webui_workspace_loaded",
10083
+ workspaceId: workspace.id,
10084
+ workspaceName: workspace.name,
10085
+ tabCount: data.tabs.length,
10086
+ warningCount: warnings.length,
10087
+ closedIds,
10088
+ ...(savedCurrent ? { savedCurrentId: savedCurrent.workspace.id } : {}),
10089
+ });
10090
+ return data;
10091
+ } finally {
10092
+ workspaceLoadInProgress = false;
10093
+ }
10094
+ }
10095
+
9709
10096
  function spawnRestartServer(restorableTabs, supervisorCursor) {
9710
10097
  const env = {
9711
10098
  ...process.env,
@@ -10315,6 +10702,7 @@ async function performTabCwdUpdate(tab, cwd) {
10315
10702
  clearExtensionWidgets(tab);
10316
10703
  clearWebuiSubagents(tab);
10317
10704
  resetNaturalConversationMode(tab);
10705
+ resetCodexFastMode(tab);
10318
10706
 
10319
10707
  let rpc;
10320
10708
  let startDirectRpc = false;
@@ -10377,6 +10765,7 @@ async function restartTabRpc(tab, reason = "reload") {
10377
10765
  clearExtensionWidgets(tab);
10378
10766
  clearWebuiSubagents(tab);
10379
10767
  resetNaturalConversationMode(tab);
10768
+ resetCodexFastMode(tab);
10380
10769
  let rpc;
10381
10770
  if (oldRpc instanceof SupervisorPiRpcProcess) {
10382
10771
  const snapshot = await oldRpc.replace({
@@ -11084,6 +11473,120 @@ async function setNaturalConversationMode(tab, body = {}) {
11084
11473
  return { ...(await naturalConversationFeatureData(tab, { refreshCommands: false })), response };
11085
11474
  }
11086
11475
 
11476
+ function codexFastModeCommandBaseName(name) {
11477
+ return String(name || "").trim().toLowerCase().replace(/:\d+$/, "");
11478
+ }
11479
+
11480
+ // The extension publishes exactly "on" or "off"; anything else is treated as unknown so the
11481
+ // browser can render an explicit unknown state instead of silently claiming Fast mode is off.
11482
+ function codexFastModeStatusState(statusText) {
11483
+ const text = stripAnsi(statusText).replace(/\s+/g, " ").trim().toLowerCase();
11484
+ if (text !== "on" && text !== "off") return { known: false, enabled: false };
11485
+ return { known: true, enabled: text === "on" };
11486
+ }
11487
+
11488
+ function codexFastModeSnapshot(tab, patch = {}) {
11489
+ const previous = tab?.codexFastMode && typeof tab.codexFastMode === "object" ? tab.codexFastMode : {};
11490
+ const status = codexFastModeStatusState(extensionStatusMap(tab).get(CODEX_FAST_MODE_STATUS_KEY) || "");
11491
+ const known = patch.statusKnown ?? (status.known || previous.statusKnown === true);
11492
+ return {
11493
+ featureId: CODEX_FAST_MODE_FEATURE_ID,
11494
+ enabled: patch.enabled ?? (status.known ? status.enabled : previous.enabled === true),
11495
+ statusKnown: known,
11496
+ updatedAt: patch.updatedAt || new Date().toISOString(),
11497
+ };
11498
+ }
11499
+
11500
+ function resetCodexFastMode(tab) {
11501
+ if (!tab) return;
11502
+ tab.codexFastMode = null;
11503
+ tab.codexFastModeCommandName = "";
11504
+ }
11505
+
11506
+ async function codexFastModePackageStatus() {
11507
+ try {
11508
+ return await optionalFeaturePackageStatus(CODEX_FAST_MODE_FEATURE_ID);
11509
+ } catch (error) {
11510
+ return { featureId: CODEX_FAST_MODE_FEATURE_ID, packageName: OPTIONAL_FEATURE_PACKAGES.get(CODEX_FAST_MODE_FEATURE_ID), installed: false, error: sanitizeError(error) };
11511
+ }
11512
+ }
11513
+
11514
+ async function codexFastModeCommandState(tab, { refreshCommands = true } = {}) {
11515
+ if (!refreshCommands) return { commandName: String(tab?.codexFastModeCommandName || ""), rpcRunning: true, error: "" };
11516
+ try {
11517
+ const data = await getCommandData(tab, { annotateSkills: false });
11518
+ const match = (data.commands || []).find((command) => codexFastModeCommandBaseName(command?.name) === CODEX_FAST_MODE_COMMAND_NAME);
11519
+ tab.codexFastModeCommandName = match?.name ? String(match.name) : "";
11520
+ return { commandName: tab.codexFastModeCommandName, rpcRunning: data.rpcRunning !== false, error: data.error || "" };
11521
+ } catch (error) {
11522
+ tab.codexFastModeCommandName = "";
11523
+ return { commandName: "", rpcRunning: false, error: sanitizeError(error) };
11524
+ }
11525
+ }
11526
+
11527
+ async function codexFastModeFeatureData(tab, { refreshCommands = true } = {}) {
11528
+ const packageStatus = await codexFastModePackageStatus();
11529
+ const command = await codexFastModeCommandState(tab, { refreshCommands });
11530
+ const state = await currentSessionState(tab).catch(() => tab?.lastState || {});
11531
+ const model = state?.model?.provider && state?.model?.id
11532
+ ? { provider: String(state.model.provider), id: String(state.model.id) }
11533
+ : null;
11534
+ const mode = codexFastModeSnapshot(tab);
11535
+ tab.codexFastMode = mode;
11536
+ const available = !!command.commandName;
11537
+ return {
11538
+ featureId: CODEX_FAST_MODE_FEATURE_ID,
11539
+ packageName: OPTIONAL_FEATURE_PACKAGES.get(CODEX_FAST_MODE_FEATURE_ID),
11540
+ available,
11541
+ packageInstalled: packageStatus.installed === true,
11542
+ packageStatus,
11543
+ commandName: command.commandName,
11544
+ enabled: mode.enabled,
11545
+ statusKnown: mode.statusKnown,
11546
+ busy: tabHasActiveOutput(tab),
11547
+ model,
11548
+ modelEligible: model?.provider === CODEX_FAST_MODE_PROVIDER,
11549
+ creditNotice: CODEX_FAST_MODE_CREDIT_NOTICE,
11550
+ rpcRunning: command.rpcRunning,
11551
+ unavailableReason: available
11552
+ ? ""
11553
+ : packageStatus.installed
11554
+ ? "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."
11555
+ : "Codex Fast mode package is not installed or not visible from the Web UI package root.",
11556
+ error: command.error || undefined,
11557
+ };
11558
+ }
11559
+
11560
+ async function waitForCodexFastModeStatus(tab, desired) {
11561
+ const deadline = Date.now() + CODEX_FAST_MODE_STATUS_TIMEOUT_MS;
11562
+ do {
11563
+ const snapshot = codexFastModeSnapshot(tab);
11564
+ if (snapshot.statusKnown && snapshot.enabled === desired) {
11565
+ tab.codexFastMode = snapshot;
11566
+ return snapshot;
11567
+ }
11568
+ if (Date.now() >= deadline) break;
11569
+ await sleepMs(25);
11570
+ } while (true);
11571
+ 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.`);
11572
+ }
11573
+
11574
+ async function setCodexFastMode(tab, body = {}) {
11575
+ if (typeof body?.enabled !== "boolean") throw makeHttpError(400, "Codex Fast mode requires an explicit enabled boolean");
11576
+ const desired = body.enabled === true;
11577
+ const feature = await codexFastModeFeatureData(tab);
11578
+ if (!feature.available) throw makeHttpError(404, feature.unavailableReason);
11579
+ // A mid-turn tier change would produce a mixed-tier tool loop, so mutations are rejected while
11580
+ // the tab is working. Reading status stays available.
11581
+ 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.");
11582
+ const response = await tab.rpc.send({ type: "prompt", message: `/${feature.commandName} ${desired ? "on" : "off"}` }, REQUEST_TIMEOUT_MS);
11583
+ if (response.success === false) throw makeHttpError(400, response.error || `Failed to turn Codex Fast mode ${desired ? "on" : "off"}`);
11584
+ // RPC success only means the extension command returned. Require its authoritative status event
11585
+ // to confirm the requested state so a busy-transition rejection cannot become false success.
11586
+ await waitForCodexFastModeStatus(tab, desired);
11587
+ return { ...(await codexFastModeFeatureData(tab, { refreshCommands: false })), requested: desired };
11588
+ }
11589
+
11087
11590
  // Piper voice switching for the native /talk audio loop. The WebUI never
11088
11591
  // imports the natural-conversation package; it mirrors the package's small
11089
11592
  // voice catalog for display, reads voice.json / the piper voice dir for
@@ -12411,6 +12914,7 @@ async function handleNativeSlashCommand(tab, body, req) {
12411
12914
  clearExtensionWidgets(tab);
12412
12915
  clearWebuiSubagents(tab);
12413
12916
  resetNaturalConversationMode(tab);
12917
+ resetCodexFastMode(tab);
12414
12918
  return respondNative("new", {
12415
12919
  status: "succeeded",
12416
12920
  message: "Started a new session.",
@@ -12490,10 +12994,10 @@ async function handleNativeSlashCommand(tab, body, req) {
12490
12994
  }
12491
12995
  }
12492
12996
 
12493
- async function closeTab(id) {
12997
+ async function closeTab(id, { allowLast = false } = {}) {
12494
12998
  const tab = tabs.get(id);
12495
12999
  if (!tab) throw makeHttpError(404, `Unknown Pi tab: ${id}`);
12496
- if (tabs.size <= 1) throw makeHttpError(400, "Cannot close the last Pi tab");
13000
+ if (!allowLast && tabs.size <= 1) throw makeHttpError(400, "Cannot close the last Pi tab");
12497
13001
 
12498
13002
  let restorableState = null;
12499
13003
  if (!options.noSession) {
@@ -12583,19 +13087,19 @@ async function openPlanRecovery(body = {}) {
12583
13087
  }
12584
13088
  }
12585
13089
 
12586
- async function closeTabs(ids) {
13090
+ async function closeTabs(ids, { allowEmpty = false } = {}) {
12587
13091
  const uniqueIds = [...new Set((Array.isArray(ids) ? ids : []).map((id) => String(id || "").trim()).filter(Boolean))];
12588
13092
  const targetTabs = uniqueIds.map((id) => tabs.get(id)).filter(Boolean);
12589
13093
  if (!targetTabs.length) return [];
12590
13094
 
12591
- if (targetTabs.length >= tabs.size) {
13095
+ if (!allowEmpty && targetTabs.length >= tabs.size) {
12592
13096
  await createTab({ cwd: targetTabs[0]?.cwd || options.cwd });
12593
13097
  }
12594
13098
 
12595
13099
  const closed = [];
12596
13100
  for (const tab of targetTabs) {
12597
13101
  if (!tabs.has(tab.id)) continue;
12598
- closed.push(await closeTab(tab.id));
13102
+ closed.push(await closeTab(tab.id, { allowLast: allowEmpty }));
12599
13103
  }
12600
13104
  return closed;
12601
13105
  }
@@ -12729,6 +13233,20 @@ async function saveOutputModeDefault(value) {
12729
13233
  return outputModeMetadata();
12730
13234
  }
12731
13235
 
13236
+ async function interfacePreferencesData() {
13237
+ const settings = await readWebuiSettings();
13238
+ return { preferences: settings.interfacePreferences };
13239
+ }
13240
+
13241
+ async function saveInterfacePreferences(body = {}) {
13242
+ const sidePanelWidth = Number(body.sidePanelWidth);
13243
+ if (!Number.isFinite(sidePanelWidth) || sidePanelWidth < WEBUI_SIDE_PANEL_WIDTH_MIN_PX || sidePanelWidth > WEBUI_SIDE_PANEL_WIDTH_MAX_PX) {
13244
+ throw makeHttpError(400, `sidePanelWidth must be between ${WEBUI_SIDE_PANEL_WIDTH_MIN_PX} and ${WEBUI_SIDE_PANEL_WIDTH_MAX_PX} pixels`);
13245
+ }
13246
+ const settings = await writeWebuiSettings({ interfacePreferences: { sidePanelWidth: Math.round(sidePanelWidth) } });
13247
+ return { preferences: settings.interfacePreferences };
13248
+ }
13249
+
12732
13250
  const remoteAuth = {
12733
13251
  pin: undefined,
12734
13252
  token: undefined,
@@ -13200,11 +13718,72 @@ const server = createServer(async (req, res) => {
13200
13718
  return;
13201
13719
  }
13202
13720
 
13721
+ if (url.pathname === "/api/interface-preferences" && req.method === "GET") {
13722
+ sendJson(res, 200, { ok: true, data: await interfacePreferencesData() });
13723
+ return;
13724
+ }
13725
+
13726
+ if (url.pathname === "/api/interface-preferences" && req.method === "PUT") {
13727
+ sendJson(res, 200, { ok: true, data: await saveInterfacePreferences(await readJsonBody(req)) });
13728
+ return;
13729
+ }
13730
+
13203
13731
  if (url.pathname === "/api/tabs" && req.method === "GET") {
13204
13732
  sendJson(res, 200, { ok: true, data: { tabs: await listTabsWithReconciledActivity() } });
13205
13733
  return;
13206
13734
  }
13207
13735
 
13736
+ if (url.pathname === "/api/workspaces" && req.method === "GET") {
13737
+ sendJson(res, 200, { ok: true, data: { workspaces: await listWebuiWorkspaces() } });
13738
+ return;
13739
+ }
13740
+
13741
+ if (url.pathname === "/api/workspaces" && req.method === "POST") {
13742
+ if (!tabs.size) throw makeHttpError(400, "A workspace requires at least one open tab");
13743
+ const body = await readJsonBody(req);
13744
+ const descriptors = await restorableTabsForRestart();
13745
+ if (!descriptors.length) throw makeHttpError(400, "A workspace requires at least one open tab");
13746
+ let data;
13747
+ try {
13748
+ data = await saveWebuiWorkspace({
13749
+ name: body.name,
13750
+ groups: body.groups,
13751
+ activeTabId: body.activeTabId,
13752
+ overwrite: body.overwrite === true,
13753
+ tabs: descriptors,
13754
+ });
13755
+ } catch (error) {
13756
+ if (error?.code === "WORKSPACE_NAME_CONFLICT") throw makeHttpError(409, error.message);
13757
+ throw error;
13758
+ }
13759
+ broadcastServerEvent({
13760
+ type: "webui_workspace_saved",
13761
+ workspaceId: data.workspace.id,
13762
+ workspaceName: data.workspace.name,
13763
+ tabCount: data.workspace.tabCount,
13764
+ evictedIds: data.evicted.map((workspace) => workspace.id),
13765
+ });
13766
+ sendJson(res, 201, { ok: true, data });
13767
+ return;
13768
+ }
13769
+
13770
+ const workspaceLoadRoute = /^\/api\/workspaces\/([^/]+)\/load$/.exec(url.pathname);
13771
+ if (workspaceLoadRoute && req.method === "POST") {
13772
+ const body = await readJsonBody(req);
13773
+ sendJson(res, 200, { ok: true, data: await loadWebuiWorkspace(decodeURIComponent(workspaceLoadRoute[1]), body) });
13774
+ return;
13775
+ }
13776
+
13777
+ if (url.pathname.startsWith("/api/workspaces/") && req.method === "DELETE") {
13778
+ const id = decodeURIComponent(url.pathname.slice("/api/workspaces/".length));
13779
+ if (!id || id.includes("/")) throw makeHttpError(404, "Workspace not found");
13780
+ const data = await deleteWebuiWorkspace(id);
13781
+ if (!data) throw makeHttpError(404, "Workspace not found");
13782
+ broadcastServerEvent({ type: "webui_workspace_deleted", workspaceId: data.deletedId });
13783
+ sendJson(res, 200, { ok: true, data });
13784
+ return;
13785
+ }
13786
+
13208
13787
  if (url.pathname === "/api/subagents" && req.method === "GET") {
13209
13788
  sendJson(res, 200, { ok: true, data: webuiSubagentsData() });
13210
13789
  return;
@@ -13233,6 +13812,26 @@ const server = createServer(async (req, res) => {
13233
13812
  return;
13234
13813
  }
13235
13814
 
13815
+ if (url.pathname === "/api/subagents/cancel" && req.method === "POST") {
13816
+ requireLocalhostRoute(req, url.pathname);
13817
+ const body = await readJsonBody(req);
13818
+ const tab = getRequestedTab(req, url, body);
13819
+ sendJson(res, 200, { ok: true, data: await sendWebuiHelperCommand(tab, "subagent-cancel", {
13820
+ runId: body.runId,
13821
+ reason: body.reason,
13822
+ note: body.note,
13823
+ }) });
13824
+ return;
13825
+ }
13826
+
13827
+ if (url.pathname === "/api/subagents/dismiss" && req.method === "POST") {
13828
+ requireLocalhostRoute(req, url.pathname);
13829
+ const body = await readJsonBody(req);
13830
+ const tab = getRequestedTab(req, url, body);
13831
+ sendJson(res, 200, { ok: true, data: await sendWebuiHelperCommand(tab, "subagent-dismiss", { runId: body.runId }) });
13832
+ return;
13833
+ }
13834
+
13236
13835
  if (url.pathname === "/api/tabs" && req.method === "POST") {
13237
13836
  const body = await readJsonBody(req);
13238
13837
  const tab = await createTab({ title: body.title, cwd: body.cwd });
@@ -13242,7 +13841,7 @@ const server = createServer(async (req, res) => {
13242
13841
 
13243
13842
  if (url.pathname === "/api/tabs/close" && req.method === "POST") {
13244
13843
  const body = await readJsonBody(req);
13245
- const closed = await closeTabs(body.ids || body.tabIds || []);
13844
+ const closed = await closeTabs(body.ids || body.tabIds || [], { allowEmpty: body.allowEmpty === true });
13246
13845
  sendJson(res, 200, { ok: true, data: { closedIds: closed.map((tab) => tab.id), tabs: listTabs(), activeTabId: firstTab()?.id || null } });
13247
13846
  return;
13248
13847
  }
@@ -13820,6 +14419,19 @@ const server = createServer(async (req, res) => {
13820
14419
  return;
13821
14420
  }
13822
14421
 
14422
+ if (url.pathname === "/api/codex-fast-mode" && req.method === "GET") {
14423
+ const tab = getRequestedTab(req, url);
14424
+ sendJson(res, 200, { ok: true, data: await codexFastModeFeatureData(tab), tab: tabMeta(tab) });
14425
+ return;
14426
+ }
14427
+
14428
+ if (url.pathname === "/api/codex-fast-mode" && req.method === "PUT") {
14429
+ const body = await readJsonBody(req);
14430
+ const tab = getRequestedTab(req, url, body);
14431
+ sendJson(res, 200, { ok: true, data: await setCodexFastMode(tab, body), tab: tabMeta(tab) });
14432
+ return;
14433
+ }
14434
+
13823
14435
  if (url.pathname === "/api/conversation-voices" && req.method === "GET") {
13824
14436
  const tab = getRequestedTab(req, url);
13825
14437
  sendJson(res, 200, { ok: true, data: await conversationVoicesData(), tab: tabMeta(tab) });
@@ -13992,6 +14604,19 @@ const server = createServer(async (req, res) => {
13992
14604
  return;
13993
14605
  }
13994
14606
 
14607
+ if (url.pathname === "/api/queue/mutate" && req.method === "POST") {
14608
+ const body = await readJsonBody(req, { limitBytes: requestBodyLimitForPath(url.pathname) });
14609
+ const tab = getRequestedTab(req, url, body);
14610
+ const request = queueMutationRequest(body);
14611
+ const data = request.source === "webui-compaction"
14612
+ ? mutateCompactionFollowUpQueue(tab, request)
14613
+ : await sendWebuiHelperCommand(tab, "queue-mutate", request);
14614
+ const conflict = data?.mutated === false && ["queue-changed", "queue-desynchronized", "queue-draining"].includes(data.reason);
14615
+ const status = data?.mutated === true ? 200 : conflict ? 409 : 400;
14616
+ sendJson(res, status, { ok: data?.mutated === true, data });
14617
+ return;
14618
+ }
14619
+
13995
14620
  if (url.pathname === "/api/prompt" && req.method === "POST") {
13996
14621
  const body = await readJsonBody(req, { limitBytes: requestBodyLimitForPath(url.pathname) });
13997
14622
  const tab = getRequestedTab(req, url, body);
@@ -14171,7 +14796,8 @@ const server = createServer(async (req, res) => {
14171
14796
  const tab = getRequestedTab(req, url, body);
14172
14797
  ensureNaturalConversationRouteAllowed(tab, "git branch changes are blocked");
14173
14798
  try {
14174
- sendJson(res, 200, await switchGitBranch(tab.cwd, body.branch, { create: body.create === true }));
14799
+ const remoteRef = requestedRemoteRef(body);
14800
+ sendJson(res, 200, await switchGitBranch(tab.cwd, body.branch, { create: body.create === true, remoteRef }));
14175
14801
  } catch (error) {
14176
14802
  sendJson(res, 200, { ok: false, error: sanitizeError(error) });
14177
14803
  }
@@ -14338,6 +14964,7 @@ const server = createServer(async (req, res) => {
14338
14964
  clearExtensionWidgets(tab);
14339
14965
  clearWebuiSubagents(tab);
14340
14966
  resetNaturalConversationMode(tab);
14967
+ resetCodexFastMode(tab);
14341
14968
  }
14342
14969
  sendJson(res, response.success === false ? 400 : 200, responseWithTab(response, tab));
14343
14970
  return;