@firstpick/pi-package-webui 0.7.9 → 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.
package/README.md CHANGED
@@ -153,13 +153,19 @@ Operations and recovery:
153
153
 
154
154
  ### Compact live output mode
155
155
 
156
- Normal output is the default. In the sidebar, open **Controls → Output processing**, select **Fast**, and click **Apply**. The same persisted server default is also available under **Settings → Browser workflow → Output processing**. Alternatively, set `--output-mode compact-v1`, `PI_WEBUI_OUTPUT_MODE=compact-v1`, or `outputModeDefault` directly. Precedence is explicit CLI flag, then environment variable, then the persisted setting, then `normal`.
156
+ Normal output is the default. In the sidebar, open **Controls → Output processing**, select **Compact**, and click **Apply**. The same persisted server default is also available under **Settings → Browser workflow → Output processing**. Alternatively, set `--output-mode compact-v1`, `PI_WEBUI_OUTPUT_MODE=compact-v1`, or `outputModeDefault` directly. Precedence is explicit CLI flag, then environment variable, then the persisted setting, then `normal`.
157
157
 
158
- The browser negotiates compact-v1 per EventSource connection (`outputMode=auto&outputModeProtocol=1`), so normal and compact clients can share one Pi tab. A browser only enables compact handling after the protocol-1 acknowledgement; an older server gets one normal-mode reconnect instead. The server default applies only to `auto` clients, and active auto streams change representation at a semantic boundary.
158
+ The browser negotiates `compact-v1` per EventSource connection (`outputMode=auto&outputModeProtocol=1`), so normal and compact clients can share one Pi tab. A browser only enables compact handling after the protocol-1 acknowledgement; an older server gets one normal-mode reconnect instead. The server default applies only to `auto` clients, and active auto streams change representation at a semantic boundary.
159
159
 
160
- Fast mode keeps live output lightweight, coalesces sustained live DOM/scroll flushes to at most once every 100 ms, preserves Markdown formatting for live and reconciled thinking, and displays only the current transient tool status as a compact labeled row with a state pill; each new tool or assistant delta replaces that status instead of retaining a tool-call history. Final reconciliation keeps visible thinking formatted and renders the final assistant response as Markdown while omitting intermediate tool calls, results, diffs, images, and raw details. The existing final `/api/messages` transcript remains authoritative. Fast mode does not change Pi generation, prompts, tools, models, providers, inference, stored transcript semantics, or the normal renderer.
160
+ Compact mode keeps live output lightweight, coalesces sustained live DOM/scroll flushes to at most once every 100 ms, preserves Markdown formatting for live and reconciled thinking, and displays only the current transient tool status as a compact labeled row with a state pill; each new tool or assistant delta replaces that status instead of retaining a tool-call history. Final reconciliation keeps visible thinking formatted and renders the final assistant response as Markdown while omitting intermediate tool calls, results, diffs, images, and raw details. The existing final `/api/messages` transcript remains authoritative. Compact mode does not change Pi generation, prompts, tools, models, providers, inference, stored transcript semantics, or the normal renderer.
161
161
 
162
- The included fast-mode metric measures deterministic post-parse serialized JSON byte-work only (`R + 2×S`) and semantic parity; it does not claim wall-clock improvement, lower DOM CPU, reduced network latency, or higher model token/s.
162
+ The included compact-mode metric measures deterministic post-parse serialized JSON byte-work only (`R + 2×S`) and semantic parity; it does not claim wall-clock improvement, lower DOM CPU, reduced network latency, or higher model token/s.
163
+
164
+ ### Codex subscription Fast mode
165
+
166
+ The optional `@firstpick/pi-extension-codex-fast-mode` companion adds `/fast-mode` and a **Normal / Fast** selector under **Codex Usage**. Fast mode is off by default and scoped to the active Pi session branch. The browser asks the extension to change mode and renders the extension-published `codex-fast-mode` status; it does not inspect ChatGPT credentials or rewrite provider requests itself.
167
+
168
+ When enabled, the extension marks only subscription-backed `openai-codex` requests using `openai-codex-responses` with `service_tier: "priority"`. Supported models may respond about 1.5× faster while spending 2× Standard credits for GPT-5.4 or 2.5× for GPT-5.5/5.6. Upstream account and model eligibility remains authoritative. Mode changes are blocked while the active tab is busy, and disabling the optional feature turns Fast mode off before hiding its integration.
163
169
 
164
170
  Optional Natural Conversation server-side voice fallback variables:
165
171
 
package/bin/pi-webui.mjs CHANGED
@@ -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,
@@ -378,6 +380,7 @@ const OPTIONAL_FEATURE_PACKAGES = new Map([
378
380
  ["naturalConversation", "@firstpick/pi-package-natural-conversation"],
379
381
  ["gitFooterStatus", "@firstpick/pi-extension-git-footer-status"],
380
382
  ["statsCommand", "@firstpick/pi-extension-stats"],
383
+ ["codexFastMode", "@firstpick/pi-extension-codex-fast-mode"],
381
384
  ["themeBundle", "@firstpick/pi-themes-bundle"],
382
385
  ]);
383
386
  const WEBUI_CONTROLLED_PACKAGES = new Set([
@@ -393,6 +396,15 @@ const UPDATE_PACKAGE_NAMES = [...new Set([
393
396
  ])].sort();
394
397
  const NATURAL_CONVERSATION_STATUS_KEY = "natural-conversation";
395
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.";
396
408
  const PACKAGE_NAME_CACHE = new Map();
397
409
 
398
410
  function usage() {
@@ -5819,6 +5831,7 @@ const GIT_FETCH_TIMEOUT_MS = 2 * 60 * 1000;
5819
5831
  const GIT_CONFLICT_PREVIEW_MAX_BYTES = 200_000;
5820
5832
  const GIT_STASH_PATCH_MAX_OUTPUT = 200_000;
5821
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.";
5822
5835
 
5823
5836
  const sleepMs = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
5824
5837
 
@@ -5889,6 +5902,9 @@ function classifyGitSyncFailure(result, { push = false } = {}) {
5889
5902
  if (/could not resolve host|failed to connect|connection (?:refused|reset|timed out)|network is unreachable|operation timed out/.test(text)) {
5890
5903
  return { code: "NETWORK", hint: "The remote could not be reached. Check connectivity and retry." };
5891
5904
  }
5905
+ if (push && /fatal:\s+no configured push destination\./.test(text)) {
5906
+ return { code: "NO_REMOTE", hint: NO_REMOTE_HINT };
5907
+ }
5892
5908
  if (push && /protected branch|gh006/.test(text)) {
5893
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." };
5894
5910
  }
@@ -6932,18 +6948,71 @@ function normalizeGitBranchList(branchText, current = "") {
6932
6948
  });
6933
6949
  }
6934
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
+
6935
6998
  async function readGitBranches(cwd) {
6936
6999
  const root = await getGitRoot(cwd);
6937
- const [current, branchText, worktreeData] = await Promise.all([
7000
+ const [current, branchText, worktreeData, remoteData] = await Promise.all([
6938
7001
  currentGitBranchForPicker(root),
6939
- runGitReadCommand(root, ["branch", "--format=%(refname:short)"], { timeoutMs: 5000, maxOutputLength: 120_000 }),
7002
+ runGitReadCommand(root, ["branch", "--format=%(refname:lstrip=2)"], { timeoutMs: 5000, maxOutputLength: 120_000 }),
6940
7003
  listGitWorktrees(cwd).catch(() => null),
7004
+ readRemoteGitBranchData(root).catch(() => ({ remoteNames: [], refText: "", truncated: false, unavailable: true })),
6941
7005
  ]);
6942
7006
  const occupiedByBranch = new Map();
6943
7007
  for (const item of worktreeData?.occupiedBranches || []) {
6944
7008
  if (!item?.branch || occupiedByBranch.has(item.branch)) continue;
6945
7009
  occupiedByBranch.set(item.branch, item);
6946
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)));
6947
7016
  return {
6948
7017
  cwd,
6949
7018
  root,
@@ -6953,24 +7022,60 @@ async function readGitBranches(cwd) {
6953
7022
  defaultWorktreesRoot: worktreeData?.defaultWorktreesRoot || "",
6954
7023
  current,
6955
7024
  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
- }),
7025
+ branches: [...localBranches, ...remoteBranches],
7026
+ remoteBranchesTruncated: remoteData.truncated === true,
7027
+ remoteBranchesUnavailable: remoteData.unavailable === true,
6960
7028
  worktrees: worktreeData?.worktrees || [],
6961
7029
  occupiedBranches: worktreeData?.occupiedBranches || [],
6962
7030
  };
6963
7031
  }
6964
7032
 
6965
- 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
+
6966
7071
  const root = await getGitRoot(cwd);
6967
7072
  const targetBranch = cleanGitBranchName(branch);
6968
7073
  await validateGitBranchName(root, targetBranch);
6969
7074
  const branches = await readGitBranches(cwd);
6970
- const branchExists = branches.branches.some((item) => item.name === targetBranch);
7075
+ const branchExists = branches.branches.some((item) => item.remote !== true && item.name === targetBranch);
6971
7076
  if (create && branchExists) throw new Error(`Local git branch already exists: ${targetBranch}`);
6972
7077
  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);
7078
+ const occupied = branches.branches.find((item) => item.remote !== true && item.name === targetBranch && item.occupied && !item.worktreeCurrent);
6974
7079
  if (!create && occupied?.worktreePath) {
6975
7080
  return {
6976
7081
  ok: false,
@@ -7215,9 +7320,13 @@ async function createGitWorkflowBranchWorktree(tab, body = {}) {
7215
7320
  }
7216
7321
 
7217
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 };
7218
7327
  let createdResult = null;
7219
7328
  try {
7220
- createdResult = await createGitWorktree(tab.cwd, body);
7329
+ createdResult = await createGitWorktree(tab.cwd, worktreeRequest);
7221
7330
  const opened = await openWorktreeResultForTab(tab, createdResult, { openTab: body.openTab !== false, ...body });
7222
7331
  if (createdResult.created) {
7223
7332
  recordEvent({ type: "webui_worktree_created", tabId: opened.tab?.id || tab.id, cwd: opened.worktree?.path || opened.path, branch: opened.branch || body.branchName || "" });
@@ -7263,10 +7372,14 @@ function sendGitWorktreeFailure(res, error) {
7263
7372
  sendJson(res, 200, gitWorktreeErrorPayload(error));
7264
7373
  }
7265
7374
 
7266
- async function defaultGitRemote(root) {
7375
+ async function gitRemoteNames(root) {
7267
7376
  const result = await runGitWorkflowCommand(["remote"], { cwd: root, timeoutMs: 5000 });
7268
7377
  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);
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);
7270
7383
  if (!remotes.length) throw new Error("No git remote is configured for this repository");
7271
7384
  return remotes.includes("origin") ? "origin" : remotes[0];
7272
7385
  }
@@ -7381,6 +7494,20 @@ function gitWorkflowCommandPayload(result) {
7381
7494
  };
7382
7495
  }
7383
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
+
7384
7511
  // Read-only workflow lookups are safe over GET; everything else mutates the
7385
7512
  // repository (or process state, for cancel) and must be POST. Method + access
7386
7513
  // guard are enforced at the router before dispatch — never dispatch on path
@@ -7405,6 +7532,7 @@ const GIT_WORKFLOW_MUTATING_PATHS = new Set([
7405
7532
  "/api/git-workflow/branch",
7406
7533
  "/api/git-workflow/commit",
7407
7534
  "/api/git-workflow/push",
7535
+ "/api/git-workflow/publish",
7408
7536
  "/api/git-workflow/create-pr",
7409
7537
  "/api/git-workflow/cancel",
7410
7538
  ]);
@@ -7517,6 +7645,23 @@ async function handleGitWorkflowRequest(pathname, body = {}, tabOrCwd = options.
7517
7645
  }
7518
7646
  return applyGitSyncFailure(payload, { push: true });
7519
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
+ }
7520
7665
  case "/api/git-workflow/create-pr": {
7521
7666
  const root = await getGitRoot(cwd);
7522
7667
  const branch = await currentGitBranch(root);
@@ -9411,6 +9556,7 @@ function attachRpcToTab(tab, rpc) {
9411
9556
  clearExtensionWidgets(tab);
9412
9557
  clearWebuiSubagents(tab);
9413
9558
  resetNaturalConversationMode(tab);
9559
+ resetCodexFastMode(tab);
9414
9560
  } else {
9415
9561
  rememberExtensionStatusEvent(tab, scopedEvent);
9416
9562
  rememberNaturalConversationStatusEvent(tab, scopedEvent);
@@ -9458,6 +9604,7 @@ function createTabRecord({ id, index, title, titleSource, conversationStarted, c
9458
9604
  sseClients: new Set(),
9459
9605
  };
9460
9606
  resetNaturalConversationMode(tab);
9607
+ resetCodexFastMode(tab);
9461
9608
  return tab;
9462
9609
  }
9463
9610
 
@@ -10555,6 +10702,7 @@ async function performTabCwdUpdate(tab, cwd) {
10555
10702
  clearExtensionWidgets(tab);
10556
10703
  clearWebuiSubagents(tab);
10557
10704
  resetNaturalConversationMode(tab);
10705
+ resetCodexFastMode(tab);
10558
10706
 
10559
10707
  let rpc;
10560
10708
  let startDirectRpc = false;
@@ -10617,6 +10765,7 @@ async function restartTabRpc(tab, reason = "reload") {
10617
10765
  clearExtensionWidgets(tab);
10618
10766
  clearWebuiSubagents(tab);
10619
10767
  resetNaturalConversationMode(tab);
10768
+ resetCodexFastMode(tab);
10620
10769
  let rpc;
10621
10770
  if (oldRpc instanceof SupervisorPiRpcProcess) {
10622
10771
  const snapshot = await oldRpc.replace({
@@ -11324,6 +11473,120 @@ async function setNaturalConversationMode(tab, body = {}) {
11324
11473
  return { ...(await naturalConversationFeatureData(tab, { refreshCommands: false })), response };
11325
11474
  }
11326
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
+
11327
11590
  // Piper voice switching for the native /talk audio loop. The WebUI never
11328
11591
  // imports the natural-conversation package; it mirrors the package's small
11329
11592
  // voice catalog for display, reads voice.json / the piper voice dir for
@@ -12651,6 +12914,7 @@ async function handleNativeSlashCommand(tab, body, req) {
12651
12914
  clearExtensionWidgets(tab);
12652
12915
  clearWebuiSubagents(tab);
12653
12916
  resetNaturalConversationMode(tab);
12917
+ resetCodexFastMode(tab);
12654
12918
  return respondNative("new", {
12655
12919
  status: "succeeded",
12656
12920
  message: "Started a new session.",
@@ -12969,6 +13233,20 @@ async function saveOutputModeDefault(value) {
12969
13233
  return outputModeMetadata();
12970
13234
  }
12971
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
+
12972
13250
  const remoteAuth = {
12973
13251
  pin: undefined,
12974
13252
  token: undefined,
@@ -13440,6 +13718,16 @@ const server = createServer(async (req, res) => {
13440
13718
  return;
13441
13719
  }
13442
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
+
13443
13731
  if (url.pathname === "/api/tabs" && req.method === "GET") {
13444
13732
  sendJson(res, 200, { ok: true, data: { tabs: await listTabsWithReconciledActivity() } });
13445
13733
  return;
@@ -14131,6 +14419,19 @@ const server = createServer(async (req, res) => {
14131
14419
  return;
14132
14420
  }
14133
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
+
14134
14435
  if (url.pathname === "/api/conversation-voices" && req.method === "GET") {
14135
14436
  const tab = getRequestedTab(req, url);
14136
14437
  sendJson(res, 200, { ok: true, data: await conversationVoicesData(), tab: tabMeta(tab) });
@@ -14495,7 +14796,8 @@ const server = createServer(async (req, res) => {
14495
14796
  const tab = getRequestedTab(req, url, body);
14496
14797
  ensureNaturalConversationRouteAllowed(tab, "git branch changes are blocked");
14497
14798
  try {
14498
- 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 }));
14499
14801
  } catch (error) {
14500
14802
  sendJson(res, 200, { ok: false, error: sanitizeError(error) });
14501
14803
  }
@@ -14662,6 +14964,7 @@ const server = createServer(async (req, res) => {
14662
14964
  clearExtensionWidgets(tab);
14663
14965
  clearWebuiSubagents(tab);
14664
14966
  resetNaturalConversationMode(tab);
14967
+ resetCodexFastMode(tab);
14665
14968
  }
14666
14969
  sendJson(res, response.success === false ? 400 : 200, responseWithTab(response, tab));
14667
14970
  return;
@@ -26,6 +26,8 @@ export function supportedGitWorkflowThinkingLevels(model) {
26
26
 
27
27
  const WEBUI_SETTINGS_VERSION = 4;
28
28
  const WEBUI_SETTINGS_FILE_ENV = "PI_WEBUI_SETTINGS_FILE";
29
+ export const WEBUI_SIDE_PANEL_WIDTH_MIN_PX = 320;
30
+ export const WEBUI_SIDE_PANEL_WIDTH_MAX_PX = 4096;
29
31
  const webuiSettingsUpdateQueues = new Map();
30
32
 
31
33
  function cleanBoundedString(value, maxLength = 512) {
@@ -138,6 +140,16 @@ export function normalizeResourceDefaults(value) {
138
140
  };
139
141
  }
140
142
 
143
+ export function normalizeInterfacePreferences(value) {
144
+ const rawSidePanelWidth = value?.sidePanelWidth;
145
+ const sidePanelWidth = rawSidePanelWidth === null || rawSidePanelWidth === undefined ? Number.NaN : Number(rawSidePanelWidth);
146
+ return {
147
+ sidePanelWidth: Number.isFinite(sidePanelWidth)
148
+ ? Math.max(WEBUI_SIDE_PANEL_WIDTH_MIN_PX, Math.min(WEBUI_SIDE_PANEL_WIDTH_MAX_PX, Math.round(sidePanelWidth)))
149
+ : null,
150
+ };
151
+ }
152
+
141
153
  function settingsObject(value) {
142
154
  return value && typeof value === "object" && !Array.isArray(value) ? value : {};
143
155
  }
@@ -156,6 +168,7 @@ export function normalizeWebuiSettings(value) {
156
168
  outputModeDefault: normalizeOutputMode(source.outputModeDefault, OUTPUT_MODE_NORMAL),
157
169
  gitWorkflow: normalizeGitWorkflowPreferences(source.gitWorkflow),
158
170
  resourceDefaults: normalizeResourceDefaults(source.resourceDefaults),
171
+ interfacePreferences: normalizeInterfacePreferences(source.interfacePreferences),
159
172
  subagentLaunchSlots: normalizeSubagentLaunchSlots(source.subagentLaunchSlots),
160
173
  };
161
174
  }
@@ -198,6 +211,9 @@ function mergeWebuiSettings(rawCurrent, patch) {
198
211
  skills: { ...current.resourceDefaults.skills, ...(patchValue.resourceDefaults.skills || {}) },
199
212
  }
200
213
  : current.resourceDefaults,
214
+ interfacePreferences: patchValue.interfacePreferences
215
+ ? { ...current.interfacePreferences, ...patchValue.interfacePreferences }
216
+ : current.interfacePreferences,
201
217
  };
202
218
  if (persistLaunchSlots) {
203
219
  source.subagentLaunchSlots = hasLaunchSlotPatch
@@ -342,6 +342,33 @@ async function branchExists(repoRoot, branch) {
342
342
  throw makeGitWorktreeError(WORKTREE_ERROR_CODES.GIT_COMMAND_FAILED, gitFailureMessage(["show-ref", "--verify", "--quiet", `refs/heads/${branch}`], result), { branch });
343
343
  }
344
344
 
345
+ function configuredRemoteForRef(remoteRef, remoteNames = []) {
346
+ return remoteNames
347
+ .filter((remoteName) => remoteRef.startsWith(`${remoteName}/`))
348
+ .sort((left, right) => right.length - left.length || left.localeCompare(right))[0] || "";
349
+ }
350
+
351
+ async function verifyTrackingRemoteRef(repo, branch, value) {
352
+ if (typeof value !== "string" || !value || value !== value.trim() || value.includes("\0")) {
353
+ throw makeGitWorktreeError(WORKTREE_ERROR_CODES.GIT_COMMAND_FAILED, "remoteRef must be a non-empty exact remote-tracking ref", { branch });
354
+ }
355
+ const remoteNames = (await runGit(["remote"], { cwd: repo.repoRoot, timeoutMs: 5000, maxOutputLength: 20_000 }))
356
+ .split(/\r?\n/)
357
+ .map((line) => line.trim())
358
+ .filter(Boolean);
359
+ const remoteName = configuredRemoteForRef(value, remoteNames);
360
+ if (!remoteName || value.slice(remoteName.length + 1) !== branch) {
361
+ throw makeGitWorktreeError(WORKTREE_ERROR_CODES.GIT_COMMAND_FAILED, `Remote git branch ${value} does not match local branch ${branch}`, { branch, remoteRef: value });
362
+ }
363
+ const fullRef = `refs/remotes/${value}`;
364
+ const output = await runGit(["for-each-ref", "--format=%(refname)%09%(symref)", fullRef], { cwd: repo.repoRoot, timeoutMs: 5000, maxOutputLength: 20_000 });
365
+ const exactRef = output.split(/\r?\n/).map((line) => line.split("\t", 2)).find(([ref]) => ref === fullRef);
366
+ if (!exactRef || exactRef[1]) {
367
+ throw makeGitWorktreeError(WORKTREE_ERROR_CODES.GIT_COMMAND_FAILED, `Unknown remote git branch: ${value}`, { branch, remoteRef: value });
368
+ }
369
+ return value;
370
+ }
371
+
345
372
  export function slugifyWorktreeBranch(branch) {
346
373
  const slug = String(branch || "")
347
374
  .toLowerCase()
@@ -416,6 +443,7 @@ function occupiedBranch(worktrees, branch) {
416
443
 
417
444
  export async function createGitWorktree(cwd, request = {}) {
418
445
  const branch = cleanBranchName(request.branchName || request.branch);
446
+ const trackingRemoteRequested = Object.hasOwn(request, "remoteRef");
419
447
  let data = await readWorktreeData(cwd);
420
448
  await validateBranchName(data, branch);
421
449
 
@@ -423,6 +451,9 @@ export async function createGitWorktree(cwd, request = {}) {
423
451
  data = await readWorktreeData(cwd);
424
452
  const existing = occupiedBranch(data.worktrees, branch);
425
453
  if (existing) {
454
+ if (trackingRemoteRequested) {
455
+ throw makeGitWorktreeError(WORKTREE_ERROR_CODES.BRANCH_CHECKED_OUT_ELSEWHERE, `Branch ${branch} is already checked out at ${existing.path}. Refresh the picker and open that worktree instead.`, { branch, remoteRef: request.remoteRef, worktreePath: existing.path });
456
+ }
426
457
  return {
427
458
  ok: true,
428
459
  created: false,
@@ -434,12 +465,20 @@ export async function createGitWorktree(cwd, request = {}) {
434
465
  };
435
466
  }
436
467
 
437
- const targetPath = await resolveCreateTarget(data, branch, data.worktrees, request.path);
438
468
  const exists = await branchExists(data.repoRoot, branch);
469
+ if (trackingRemoteRequested && exists) {
470
+ throw makeGitWorktreeError(WORKTREE_ERROR_CODES.GIT_COMMAND_FAILED, `Local git branch already exists: ${branch}`, { branch, remoteRef: request.remoteRef });
471
+ }
472
+ const targetPath = await resolveCreateTarget(data, branch, data.worktrees, request.path);
473
+ // Re-read the exact remote ref under the mutation lock immediately before
474
+ // `worktree add`; symbolic, stale, and colliding selections fail closed.
475
+ const trackingRemoteRef = trackingRemoteRequested ? await verifyTrackingRemoteRef(data, branch, request.remoteRef) : "";
439
476
  const baseRef = String(request.baseRef || "").trim();
440
- const args = exists
441
- ? ["worktree", "add", targetPath, branch]
442
- : ["worktree", "add", "-b", branch, targetPath, ...(baseRef ? [baseRef] : [])];
477
+ const args = trackingRemoteRef
478
+ ? ["worktree", "add", "--track", "-b", branch, targetPath, trackingRemoteRef]
479
+ : exists
480
+ ? ["worktree", "add", targetPath, branch]
481
+ : ["worktree", "add", "-b", branch, targetPath, ...(baseRef ? [baseRef] : [])];
443
482
  const worktreeAddCwd = data.currentWorktreePath || data.repoRoot;
444
483
 
445
484
  try {