@firstpick/pi-package-webui 0.5.6 → 0.5.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/pi-webui.mjs CHANGED
@@ -4,7 +4,7 @@ import { createHash, randomInt, randomUUID, timingSafeEqual } from "node:crypto"
4
4
  import { createReadStream } from "node:fs";
5
5
  import { createServer } from "node:http";
6
6
  import { createRequire } from "node:module";
7
- import { access, copyFile, mkdir, readFile, readdir, realpath, rename, stat, writeFile } from "node:fs/promises";
7
+ import { access, copyFile, mkdir, readFile, readdir, realpath, rename, rm, stat, writeFile } from "node:fs/promises";
8
8
  import { homedir, networkInterfaces, tmpdir } from "node:os";
9
9
  import path from "node:path";
10
10
  import { StringDecoder } from "node:string_decoder";
@@ -36,6 +36,15 @@ import {
36
36
  nativeSlashCommandEntries,
37
37
  parseSlashCommand as parseNativeSlashCommand,
38
38
  } from "../lib/native-command-adapter.mjs";
39
+ import {
40
+ WORKTREE_ERROR_CODES,
41
+ createGitWorktree,
42
+ gitWorktreeErrorPayload,
43
+ listGitWorktrees,
44
+ openGitWorktree,
45
+ pathInside,
46
+ removeGitWorktree,
47
+ } from "../lib/git-worktrees.mjs";
39
48
 
40
49
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
41
50
  const require = createRequire(import.meta.url);
@@ -53,7 +62,7 @@ try {
53
62
  } catch {
54
63
  piPackageJson = {};
55
64
  }
56
- const nativeParityMatrix = JSON.parse(await readFile(path.join(packageRoot, "dev", "docs", "WEBUI_TUI_NATIVE_PARITY.json"), "utf8"));
65
+ const nativeParityMatrix = JSON.parse(await readFile(path.join(packageRoot, "lib", "WEBUI_TUI_NATIVE_PARITY.json"), "utf8"));
57
66
  const webuiDevServer = isTruthyEnv(process.env.PI_WEBUI_DEV) || isSourceCheckout(packageRoot);
58
67
  let remoteQrCorePromise = null;
59
68
 
@@ -180,7 +189,11 @@ const APP_RUNNER_COMMAND_CACHE_TTL_MS = 30_000;
180
189
  const APP_RUNNER_OUTPUT_LINE_LIMIT = 1_000;
181
190
  const APP_RUNNER_OUTPUT_MAX_CHARS = 240_000;
182
191
  const APP_RUNNER_INPUT_MAX_CHARS = 16_000;
192
+ const APP_RUNNER_CONTEXT_DEFAULT_LINES = 80;
193
+ const APP_RUNNER_CONTEXT_MAX_LINES = APP_RUNNER_OUTPUT_LINE_LIMIT;
183
194
  const APP_RUNNER_STOP_GRACE_MS = 2_500;
195
+ const APP_RUNNER_PTY_DISABLED_VALUES = new Set(["0", "false", "no", "off"]);
196
+ const APP_RUNNER_PTY_SCRIPT_CACHE_TTL_MS = 5 * 60 * 1000;
184
197
  const APP_RUNNER_PYTHON_ENTRIES = ["Main.py", "main.py", "src/main.py", "src/Main.py", "app.py", "src/app.py"];
185
198
  const APP_RUNNER_JS_ENTRIES = ["main.js", "src/main.js", "index.js", "src/index.js", "server.js", "src/server.js", "app.js", "src/app.js"];
186
199
  const APP_RUNNER_ZIG_ENTRIES = ["src/main.zig", "main.zig"];
@@ -421,6 +434,10 @@ function truncateLongText(value, maxLength = 8000) {
421
434
  return `${text.slice(0, Math.max(0, maxLength - 1))}…`;
422
435
  }
423
436
 
437
+ function stripAnsi(text) {
438
+ return String(text ?? "").replace(/(?:\x1B|\u241B)(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g, "");
439
+ }
440
+
424
441
  function parsePackageVersion(version) {
425
442
  const match = String(version || "").trim().match(/^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+.*)?$/);
426
443
  if (!match) return undefined;
@@ -1434,6 +1451,7 @@ async function readJsonFileIfExists(filePath) {
1434
1451
  }
1435
1452
 
1436
1453
  const appRunnerCommandAvailability = new Map();
1454
+ let appRunnerPtyScriptAvailability = { available: false, expiresAt: 0 };
1437
1455
 
1438
1456
  async function fileStatsIfExists(filePath) {
1439
1457
  try {
@@ -1489,6 +1507,25 @@ async function appRunnerCommandAvailable(command, cwd) {
1489
1507
  return available;
1490
1508
  }
1491
1509
 
1510
+ function appRunnerPtyDisabled() {
1511
+ return APP_RUNNER_PTY_DISABLED_VALUES.has(String(process.env.PI_WEBUI_APP_RUNNER_PTY || "").trim().toLowerCase());
1512
+ }
1513
+
1514
+ async function appRunnerScriptPtyAvailable(cwd) {
1515
+ if (process.platform === "win32" || appRunnerPtyDisabled()) return false;
1516
+ const now = Date.now();
1517
+ if (appRunnerPtyScriptAvailability.expiresAt > now) return appRunnerPtyScriptAvailability.available;
1518
+ const result = await runCommand("script", ["--version"], {
1519
+ cwd,
1520
+ timeoutMs: APP_RUNNER_DETECTION_TIMEOUT_MS,
1521
+ maxOutputLength: 4_000,
1522
+ });
1523
+ const output = `${result.stdout || ""}\n${result.stderr || ""}`;
1524
+ const available = !result.error && !result.timedOut && /util-linux/i.test(output);
1525
+ appRunnerPtyScriptAvailability = { available, expiresAt: now + APP_RUNNER_PTY_SCRIPT_CACHE_TTL_MS };
1526
+ return available;
1527
+ }
1528
+
1492
1529
  function appRunnerPackageScripts(pkg) {
1493
1530
  return pkg && typeof pkg.scripts === "object" && pkg.scripts ? pkg.scripts : {};
1494
1531
  }
@@ -1523,6 +1560,41 @@ function shellQuote(value) {
1523
1560
  return `'${String(value ?? "").replace(/'/g, `'\\''`)}'`;
1524
1561
  }
1525
1562
 
1563
+ function appRunnerShellCommandLine(command, args = []) {
1564
+ return [command, ...args].map(shellQuote).join(" ");
1565
+ }
1566
+
1567
+ async function spawnAppRunnerChild(run) {
1568
+ const baseOptions = {
1569
+ cwd: run.cwd,
1570
+ env: process.env,
1571
+ stdio: ["pipe", "pipe", "pipe"],
1572
+ windowsHide: true,
1573
+ detached: process.platform !== "win32",
1574
+ };
1575
+ if (await appRunnerScriptPtyAvailable(run.cwd)) {
1576
+ run.executionMode = "pty";
1577
+ return spawn("script", [
1578
+ "-q",
1579
+ "-e",
1580
+ "-f",
1581
+ "-c",
1582
+ `stty -echo 2>/dev/null || true; exec ${appRunnerShellCommandLine(run.command, run.args || [])}`,
1583
+ "/dev/null",
1584
+ ], {
1585
+ ...baseOptions,
1586
+ env: {
1587
+ ...process.env,
1588
+ TERM: process.env.TERM || "xterm-256color",
1589
+ COLUMNS: process.env.COLUMNS || "120",
1590
+ LINES: process.env.LINES || "40",
1591
+ },
1592
+ });
1593
+ }
1594
+ run.executionMode = "pipe";
1595
+ return spawn(run.command, run.args || [], baseOptions);
1596
+ }
1597
+
1526
1598
  function appRunnerCandidate({ id, label, kind, command, args = [], projectFile = "", description = "", shortDisplayCommand = "", priority = 100, cwd = "", custom = false, configFile = "" }) {
1527
1599
  return {
1528
1600
  id,
@@ -2307,6 +2379,7 @@ function publicAppRunnerState(run) {
2307
2379
  cwd: run.cwd,
2308
2380
  pid: run.pid,
2309
2381
  status: run.status,
2382
+ executionMode: run.executionMode || "pipe",
2310
2383
  startedAt: run.startedAt,
2311
2384
  endedAt: run.endedAt,
2312
2385
  exitCode: run.exitCode,
@@ -2496,13 +2569,7 @@ async function startAppRunner(tab, runnerId) {
2496
2569
  stdinWrites: 0,
2497
2570
  };
2498
2571
  appendAppRunnerLine(run, `$ ${run.displayCommand}`);
2499
- const child = spawn(run.command, run.args, {
2500
- cwd: run.cwd,
2501
- env: process.env,
2502
- stdio: ["pipe", "pipe", "pipe"],
2503
- windowsHide: true,
2504
- detached: process.platform !== "win32",
2505
- });
2572
+ const child = await spawnAppRunnerChild(run);
2506
2573
  run.child = child;
2507
2574
  run.pid = child.pid;
2508
2575
  tab.appRunner = run;
@@ -2556,6 +2623,59 @@ function clearAppRunnerForTab(tab) {
2556
2623
  return true;
2557
2624
  }
2558
2625
 
2626
+ function normalizeAppRunnerContextLineCount(value) {
2627
+ const number = Number.parseInt(String(value ?? ""), 10);
2628
+ if (!Number.isFinite(number)) return APP_RUNNER_CONTEXT_DEFAULT_LINES;
2629
+ return Math.max(1, Math.min(APP_RUNNER_CONTEXT_MAX_LINES, number));
2630
+ }
2631
+
2632
+ function appRunnerOutputLinesForContext(run) {
2633
+ const lines = Array.isArray(run?.lines) ? [...run.lines] : [];
2634
+ const pendingLine = appRunnerPendingLine(run);
2635
+ if (pendingLine) lines.push(pendingLine);
2636
+ return lines.map((line) => stripAnsi(line).replace(/\r\n?/g, "\n"));
2637
+ }
2638
+
2639
+ function formatAppRunnerContextContent(tab, run, { requestedLineCount, lines, totalAvailableLines }) {
2640
+ const status = appRunnerStatusLabel(run);
2641
+ const capturedAt = new Date().toISOString();
2642
+ const header = [
2643
+ "App runner output transferred from Pi Web UI.",
2644
+ `Command: ${stripAnsi(run?.displayCommand || run?.command || "app runner")}`,
2645
+ `Cwd: ${stripAnsi(run?.cwd || tab?.cwd || "")}`,
2646
+ `Status: ${status}`,
2647
+ `Captured: last ${lines.length} of ${totalAvailableLines} available line${totalAvailableLines === 1 ? "" : "s"} (requested ${requestedLineCount})`,
2648
+ run?.truncated ? "Note: earlier app runner output had already been truncated before this capture." : "",
2649
+ `Captured at: ${capturedAt}`,
2650
+ ].filter(Boolean);
2651
+ return `${header.join("\n")}\n\n\`\`\`\`text\n${lines.join("\n").trimEnd()}\n\`\`\`\``;
2652
+ }
2653
+
2654
+ async function transferAppRunnerContext(tab, body = {}) {
2655
+ const run = tab?.appRunner;
2656
+ if (!run) throw makeHttpError(409, "No app runner output is available in this tab");
2657
+ const requestedLineCount = normalizeAppRunnerContextLineCount(body.lineCount ?? body.lines ?? body.count);
2658
+ const allLines = appRunnerOutputLinesForContext(run);
2659
+ const lines = allLines.slice(-requestedLineCount);
2660
+ if (!lines.some((line) => stripAnsi(line).trim())) throw makeHttpError(400, "App runner output is empty");
2661
+ const details = {
2662
+ runId: run.id,
2663
+ runnerId: run.runnerId,
2664
+ command: run.displayCommand || run.command || "",
2665
+ cwd: run.cwd || tab.cwd,
2666
+ status: run.status || "running",
2667
+ requestedLineCount,
2668
+ lineCount: lines.length,
2669
+ totalAvailableLines: allLines.length,
2670
+ truncated: run.truncated === true,
2671
+ capturedAt: new Date().toISOString(),
2672
+ };
2673
+ const content = formatAppRunnerContextContent(tab, run, { requestedLineCount, lines, totalAvailableLines: allLines.length });
2674
+ const helperData = await sendWebuiHelperCommand(tab, "app-runner-context", { content, details });
2675
+ recordEvent({ type: "webui_app_runner_context", tabId: tab.id, tabTitle: tab.title, command: details.command, lineCount: lines.length, requestedLineCount, delivery: helperData?.delivery || "context" });
2676
+ return { ...details, delivery: helperData?.delivery || "context", activeRun: publicAppRunnerState(run) };
2677
+ }
2678
+
2559
2679
  function firstDefined(...values) {
2560
2680
  return values.find((value) => value !== undefined && value !== null);
2561
2681
  }
@@ -3403,22 +3523,38 @@ async function readGitChanges(cwd) {
3403
3523
  };
3404
3524
  }
3405
3525
 
3406
- function commitMessagePaths(root) {
3526
+ function gitWorkflowMessageCwd(root, cwd) {
3527
+ const messageCwd = path.resolve(String(cwd || root));
3528
+ if (!pathInside(root, messageCwd)) throw new Error(`Git workflow cwd must stay inside repository root: ${messageCwd}`);
3529
+ return messageCwd;
3530
+ }
3531
+
3532
+ function gitWorkflowMessageFileMeta(root, messageCwd, filePath) {
3533
+ return {
3534
+ path: filePath,
3535
+ relativePath: path.relative(messageCwd, filePath).split(path.sep).join("/"),
3536
+ repoRelativePath: path.relative(root, filePath).split(path.sep).join("/"),
3537
+ };
3538
+ }
3539
+
3540
+ function commitMessagePaths(baseDir) {
3407
3541
  return {
3408
- shortPath: path.join(root, "dev", "COMMIT", "staged-commit-short.txt"),
3409
- longPath: path.join(root, "dev", "COMMIT", "staged-commit-long.txt"),
3410
- branchPath: path.join(root, "dev", "COMMIT", "staged-branch-name.txt"),
3542
+ shortPath: path.join(baseDir, "dev", "COMMIT", "staged-commit-short.txt"),
3543
+ longPath: path.join(baseDir, "dev", "COMMIT", "staged-commit-long.txt"),
3544
+ branchPath: path.join(baseDir, "dev", "COMMIT", "staged-branch-name.txt"),
3411
3545
  };
3412
3546
  }
3413
3547
 
3414
3548
  async function readGitWorkflowBranchName(cwd) {
3415
3549
  const root = await getGitRoot(cwd);
3416
- const { branchPath } = commitMessagePaths(root);
3550
+ const messageCwd = gitWorkflowMessageCwd(root, cwd);
3551
+ const { branchPath } = commitMessagePaths(messageCwd);
3417
3552
  try {
3418
3553
  const [branchText, branchStat] = await Promise.all([readFile(branchPath, "utf8"), stat(branchPath)]);
3419
3554
  const branch = branchText.split(/\r?\n/).find((line) => line.trim())?.trim() || "";
3420
3555
  if (!branch) throw new Error(`${branchPath} is empty`);
3421
- return { root, branchPath, branch, mtimeMs: branchStat.mtimeMs };
3556
+ const branchFile = gitWorkflowMessageFileMeta(root, messageCwd, branchPath);
3557
+ return { root, cwd: messageCwd, branchPath, branchRelativePath: branchFile.relativePath, branchRepoRelativePath: branchFile.repoRelativePath, branch, mtimeMs: branchStat.mtimeMs };
3422
3558
  } catch (error) {
3423
3559
  throw new Error(`Missing generated branch name file ${branchPath}. Run /git-branch-name first. ${sanitizeError(error)}`);
3424
3560
  }
@@ -3426,7 +3562,8 @@ async function readGitWorkflowBranchName(cwd) {
3426
3562
 
3427
3563
  async function readGitWorkflowMessages(cwd) {
3428
3564
  const root = await getGitRoot(cwd);
3429
- const { shortPath, longPath } = commitMessagePaths(root);
3565
+ const messageCwd = gitWorkflowMessageCwd(root, cwd);
3566
+ const { shortPath, longPath } = commitMessagePaths(messageCwd);
3430
3567
  try {
3431
3568
  const [shortText, longText, shortStat, longStat] = await Promise.all([
3432
3569
  readFile(shortPath, "utf8"),
@@ -3434,17 +3571,24 @@ async function readGitWorkflowMessages(cwd) {
3434
3571
  stat(shortPath),
3435
3572
  stat(longPath),
3436
3573
  ]);
3574
+ const shortFile = gitWorkflowMessageFileMeta(root, messageCwd, shortPath);
3575
+ const longFile = gitWorkflowMessageFileMeta(root, messageCwd, longPath);
3437
3576
  return {
3438
3577
  root,
3578
+ cwd: messageCwd,
3439
3579
  shortPath,
3440
3580
  longPath,
3581
+ shortRelativePath: shortFile.relativePath,
3582
+ longRelativePath: longFile.relativePath,
3583
+ shortRepoRelativePath: shortFile.repoRelativePath,
3584
+ longRepoRelativePath: longFile.repoRelativePath,
3441
3585
  short: shortText.trimEnd(),
3442
3586
  long: longText.trimEnd(),
3443
3587
  shortMtimeMs: shortStat.mtimeMs,
3444
3588
  longMtimeMs: longStat.mtimeMs,
3445
3589
  };
3446
3590
  } catch (error) {
3447
- throw new Error(`Missing generated commit message files in ${path.join(root, "dev", "COMMIT")}. Run /git-staged-msg first. ${sanitizeError(error)}`);
3591
+ throw new Error(`Missing generated commit message files in ${path.join(messageCwd, "dev", "COMMIT")}. Run /git-staged-msg first. ${sanitizeError(error)}`);
3448
3592
  }
3449
3593
  }
3450
3594
 
@@ -3707,16 +3851,31 @@ function normalizeGitBranchList(branchText, current = "") {
3707
3851
 
3708
3852
  async function readGitBranches(cwd) {
3709
3853
  const root = await getGitRoot(cwd);
3710
- const [current, branchText] = await Promise.all([
3854
+ const [current, branchText, worktreeData] = await Promise.all([
3711
3855
  currentGitBranchForPicker(root),
3712
3856
  runGitReadCommand(root, ["branch", "--format=%(refname:short)"], { timeoutMs: 5000, maxOutputLength: 120_000 }),
3857
+ listGitWorktrees(cwd).catch(() => null),
3713
3858
  ]);
3859
+ const occupiedByBranch = new Map();
3860
+ for (const item of worktreeData?.occupiedBranches || []) {
3861
+ if (!item?.branch || occupiedByBranch.has(item.branch)) continue;
3862
+ occupiedByBranch.set(item.branch, item);
3863
+ }
3714
3864
  return {
3715
3865
  cwd,
3716
3866
  root,
3867
+ repoRoot: worktreeData?.repoRoot || root,
3868
+ commonGitDir: worktreeData?.commonGitDir || "",
3869
+ currentWorktreePath: worktreeData?.currentWorktreePath || root,
3870
+ defaultWorktreesRoot: worktreeData?.defaultWorktreesRoot || "",
3717
3871
  current,
3718
3872
  generatedAt: new Date().toISOString(),
3719
- branches: normalizeGitBranchList(branchText, current),
3873
+ branches: normalizeGitBranchList(branchText, current).map((branch) => {
3874
+ const occupied = occupiedByBranch.get(branch.name);
3875
+ return occupied ? { ...branch, occupied: true, worktreePath: occupied.path, worktreeCurrent: occupied.current === true, mainWorktree: occupied.isMainWorktree === true } : branch;
3876
+ }),
3877
+ worktrees: worktreeData?.worktrees || [],
3878
+ occupiedBranches: worktreeData?.occupiedBranches || [],
3720
3879
  };
3721
3880
  }
3722
3881
 
@@ -3728,6 +3887,15 @@ async function switchGitBranch(cwd, branch, { create = false } = {}) {
3728
3887
  const branchExists = branches.branches.some((item) => item.name === targetBranch);
3729
3888
  if (create && branchExists) throw new Error(`Local git branch already exists: ${targetBranch}`);
3730
3889
  if (!create && !branchExists) throw new Error(`Unknown local git branch: ${targetBranch}`);
3890
+ const occupied = branches.branches.find((item) => item.name === targetBranch && item.occupied && !item.worktreeCurrent);
3891
+ if (!create && occupied?.worktreePath) {
3892
+ return {
3893
+ ok: false,
3894
+ code: WORKTREE_ERROR_CODES.BRANCH_CHECKED_OUT_ELSEWHERE,
3895
+ error: `Branch ${targetBranch} is already checked out at ${occupied.worktreePath}. Open that worktree instead of switching this checkout.`,
3896
+ data: { branch: targetBranch, root, worktreePath: occupied.worktreePath },
3897
+ };
3898
+ }
3731
3899
  if (!create && branches.current === targetBranch) {
3732
3900
  return { ok: true, data: { command: `git switch ${targetBranch}`, stdout: "", stderr: "", exitCode: 0, branch: targetBranch, root, switched: false, created: false } };
3733
3901
  }
@@ -3744,6 +3912,272 @@ async function switchGitBranch(cwd, branch, { create = false } = {}) {
3744
3912
  return payload;
3745
3913
  }
3746
3914
 
3915
+ function normalizeWorktreeSessionMode(value) {
3916
+ const mode = String(value || "fork-current").trim().toLowerCase();
3917
+ if (!mode || mode === "fork" || mode === "fork-current") return "fork-current";
3918
+ if (mode === "empty" || mode === "new") return "empty";
3919
+ if (mode === "clone-current" || mode === "parent-only") {
3920
+ throw makeHttpError(400, `sessionMode ${mode} is not supported yet; use fork-current or empty.`);
3921
+ }
3922
+ throw makeHttpError(400, "sessionMode must be fork-current or empty");
3923
+ }
3924
+
3925
+ async function createEmptySessionFileForCwd(cwd) {
3926
+ const manager = SessionManager.create(cwd, configuredSessionDir());
3927
+ const sessionFile = manager.getSessionFile();
3928
+ const header = manager.getHeader();
3929
+ if (!sessionFile || !header) return undefined;
3930
+ await mkdir(path.dirname(sessionFile), { recursive: true });
3931
+ await writeFile(sessionFile, `${JSON.stringify(header)}\n`, { encoding: "utf8", flag: "wx" });
3932
+ return sessionFile;
3933
+ }
3934
+
3935
+ async function prepareWorktreeSessionFile(sourceTab, targetCwd, requestedMode = "fork-current") {
3936
+ if (options.noSession) return { mode: "none", requestedMode: "none", sessionFile: undefined, warning: "Web UI was started with --no-session." };
3937
+ const mode = normalizeWorktreeSessionMode(requestedMode);
3938
+ if (mode === "empty") {
3939
+ return { mode, requestedMode: mode, sessionFile: await createEmptySessionFileForCwd(targetCwd) };
3940
+ }
3941
+
3942
+ const state = await currentSessionState(sourceTab).catch(() => sourceTab?.lastState || {});
3943
+ const sourceSessionFile = state.sessionFile || tabRestorableSessionFile(sourceTab);
3944
+ if (sourceSessionFile) {
3945
+ requireAllowedSessionPath(sourceSessionFile);
3946
+ const sourceInfo = await stat(sourceSessionFile).catch(() => null);
3947
+ if (sourceInfo?.isFile()) {
3948
+ const manager = SessionManager.forkFrom(sourceSessionFile, targetCwd, configuredSessionDir());
3949
+ return { mode, requestedMode: mode, sessionFile: manager.getSessionFile(), parentSession: sourceSessionFile };
3950
+ }
3951
+ }
3952
+
3953
+ return {
3954
+ mode: "empty",
3955
+ requestedMode: mode,
3956
+ sessionFile: await createEmptySessionFileForCwd(targetCwd),
3957
+ warning: "Current session is not persisted yet; opened an empty session rooted at the worktree.",
3958
+ };
3959
+ }
3960
+
3961
+ function gitWorkspaceFromWorktreeResult(result, worktree = result?.worktree) {
3962
+ if (!worktree?.path) return null;
3963
+ return {
3964
+ repoRoot: result.repoRoot || worktree.repoRoot || "",
3965
+ commonGitDir: result.commonGitDir || worktree.commonGitDir || "",
3966
+ worktreePath: worktree.path,
3967
+ branch: worktree.branch || result.branch || null,
3968
+ worktreeCount: Array.isArray(result.worktrees) ? result.worktrees.length : undefined,
3969
+ isMainWorktree: worktree.isMainWorktree === true,
3970
+ };
3971
+ }
3972
+
3973
+ async function openWorktreeResultForTab(sourceTab, result, body = {}) {
3974
+ const worktree = result?.worktree;
3975
+ const worktreePath = worktree?.path || result?.path;
3976
+ if (!worktreePath) throw makeHttpError(500, "Git worktree operation did not return a path");
3977
+ if (body.openTab === false) return { ...result, session: null, tab: null, tabs: listTabs(), openedTab: false };
3978
+
3979
+ if (sameResolvedPath(worktreePath, sourceTab.cwd)) {
3980
+ sourceTab.gitWorkspace = gitWorkspaceFromWorktreeResult(result, worktree);
3981
+ return { ...result, session: null, tab: tabMeta(sourceTab), tabs: listTabs(), openedTab: false, openedCurrent: true };
3982
+ }
3983
+
3984
+ const existingTab = [...tabs.values()].find((item) => sameResolvedPath(item.cwd, worktreePath));
3985
+ if (existingTab) {
3986
+ existingTab.gitWorkspace = gitWorkspaceFromWorktreeResult(result, worktree);
3987
+ return { ...result, session: null, tab: tabMeta(existingTab), tabs: listTabs(), openedTab: false, openedExistingTab: true };
3988
+ }
3989
+
3990
+ const session = await prepareWorktreeSessionFile(sourceTab, worktreePath, body.sessionMode || "fork-current");
3991
+ const tab = await createTab({
3992
+ title: body.title,
3993
+ titleSource: body.title ? "explicit" : undefined,
3994
+ cwd: worktreePath,
3995
+ sessionFile: session.sessionFile,
3996
+ gitWorkspace: gitWorkspaceFromWorktreeResult(result, worktree),
3997
+ });
3998
+ recordEvent({ type: "webui_worktree_opened", tabId: tab.id, tabTitle: tab.title, cwd: tab.cwd, branch: worktree.branch || result.branch || "", sessionMode: session.mode });
3999
+ return {
4000
+ ...result,
4001
+ session,
4002
+ tab: tabMeta(tab),
4003
+ tabs: listTabs(),
4004
+ openedTab: true,
4005
+ dependencyHint: "Git worktrees do not share ignored dependency directories such as node_modules or .venv; install/bootstrap dependencies manually if needed.",
4006
+ };
4007
+ }
4008
+
4009
+ async function cleanupCreatedWorktreeAfterFailure(sourceCwd, worktreePath) {
4010
+ try {
4011
+ return await removeGitWorktree(sourceCwd, worktreePath, { force: true });
4012
+ } catch (error) {
4013
+ return { ok: false, error: sanitizeError(error), code: error?.code || WORKTREE_ERROR_CODES.GIT_COMMAND_FAILED };
4014
+ }
4015
+ }
4016
+
4017
+ async function readGitWorkflowMessageFilesForTransfer(root, messageCwd = root) {
4018
+ const { shortPath, longPath } = commitMessagePaths(messageCwd);
4019
+ const files = [];
4020
+ for (const sourcePath of [shortPath, longPath]) {
4021
+ try {
4022
+ const content = await readFile(sourcePath, "utf8");
4023
+ files.push({ relativePath: path.relative(root, sourcePath).split(path.sep).join("/"), content });
4024
+ } catch (error) {
4025
+ if (error?.code !== "ENOENT") throw error;
4026
+ }
4027
+ }
4028
+ return files;
4029
+ }
4030
+
4031
+ async function snapshotGitWorkflowBranchState(root, cwd = root) {
4032
+ const messageCwd = gitWorkflowMessageCwd(root, cwd);
4033
+ const diffResult = await runGitWorkflowCommand(["diff", "--cached", "--binary", "--full-index"], {
4034
+ cwd: root,
4035
+ label: "git diff --cached --binary --full-index",
4036
+ timeoutMs: 60 * 1000,
4037
+ });
4038
+ if (diffResult.exitCode !== 0 || diffResult.timedOut || diffResult.cancelled || diffResult.error) {
4039
+ throw new Error((diffResult.stderr || diffResult.stdout || diffResult.error || "Unable to read staged changes for the PR worktree").trim());
4040
+ }
4041
+ return {
4042
+ stagedPatch: diffResult.stdout || "",
4043
+ messageFiles: await readGitWorkflowMessageFilesForTransfer(root, messageCwd),
4044
+ };
4045
+ }
4046
+
4047
+ async function applyGitWorkflowBranchStateToWorktree(snapshot, worktreePath) {
4048
+ const copiedMessageFiles = [];
4049
+ let appliedStagedPatch = false;
4050
+ const patchText = String(snapshot?.stagedPatch || "");
4051
+ if (patchText.trim()) {
4052
+ const patchPath = path.join(tmpdir(), `pi-webui-staged-worktree-${process.pid}-${Date.now()}-${randomUUID()}.patch`);
4053
+ await writeFile(patchPath, patchText, "utf8");
4054
+ try {
4055
+ const applyResult = await runGitWorkflowCommand(["apply", "--index", "--whitespace=nowarn", patchPath], {
4056
+ cwd: worktreePath,
4057
+ label: "git apply --index <staged diff>",
4058
+ timeoutMs: 5 * 60 * 1000,
4059
+ });
4060
+ if (applyResult.exitCode !== 0 || applyResult.timedOut || applyResult.cancelled || applyResult.error) {
4061
+ throw new Error((applyResult.stderr || applyResult.stdout || applyResult.error || "Unable to apply staged changes in the PR worktree").trim());
4062
+ }
4063
+ appliedStagedPatch = true;
4064
+ } finally {
4065
+ await rm(patchPath, { force: true }).catch(() => {});
4066
+ }
4067
+ }
4068
+
4069
+ for (const file of snapshot?.messageFiles || []) {
4070
+ const relativePath = String(file.relativePath || "").replace(/\\/g, "/");
4071
+ const targetPath = path.resolve(worktreePath, relativePath);
4072
+ if (!relativePath || !pathInside(worktreePath, targetPath)) throw new Error(`Refusing to copy Git workflow file outside the worktree: ${relativePath}`);
4073
+ await mkdir(path.dirname(targetPath), { recursive: true });
4074
+ await writeFile(targetPath, file.content, "utf8");
4075
+ copiedMessageFiles.push(relativePath);
4076
+ }
4077
+
4078
+ return { appliedStagedPatch, copiedMessageFiles };
4079
+ }
4080
+
4081
+ function gitWorkflowBranchWorktreeStdout({ branch, worktreePath, createdResult, opened, transfer }) {
4082
+ const lines = [];
4083
+ if (createdResult?.created) lines.push(`Created branch worktree ${branch} at ${worktreePath}.`);
4084
+ else if (createdResult?.openedExisting) lines.push(`Opened existing branch worktree ${branch} at ${worktreePath}.`);
4085
+ else lines.push(`Opened branch worktree ${branch} at ${worktreePath}.`);
4086
+ if (transfer?.appliedStagedPatch) lines.push("Copied the source checkout's staged changes into the worktree index.");
4087
+ else if (createdResult?.openedExisting) lines.push("Existing worktree was reused; source staged changes were not copied automatically.");
4088
+ else lines.push("No staged changes were copied because the source index was clean.");
4089
+ if (transfer?.copiedMessageFiles?.length) lines.push(`Copied ${transfer.copiedMessageFiles.join(", ")} for commit message selection.`);
4090
+ if (opened?.tab?.id) lines.push(`Continue the guided Git workflow in Web UI tab ${opened.tab.title || opened.tab.id}.`);
4091
+ lines.push("The source checkout was left on its current branch.");
4092
+ return lines.join("\n");
4093
+ }
4094
+
4095
+ async function createGitWorkflowBranchWorktree(tab, body = {}) {
4096
+ const root = await getGitRoot(tab.cwd);
4097
+ const branch = cleanGitBranchName(body.branch || body.branchName);
4098
+ await validateGitBranchName(root, branch);
4099
+ const snapshot = await snapshotGitWorkflowBranchState(root, tab.cwd);
4100
+ let createdResult = null;
4101
+ try {
4102
+ createdResult = await createGitWorktree(tab.cwd, { ...body, branchName: branch });
4103
+ const worktreePath = createdResult.worktree?.path || createdResult.path;
4104
+ if (!worktreePath) throw makeHttpError(500, "Git workflow worktree creation did not return a path");
4105
+ const transfer = createdResult.created
4106
+ ? await applyGitWorkflowBranchStateToWorktree(snapshot, worktreePath)
4107
+ : { appliedStagedPatch: false, copiedMessageFiles: [] };
4108
+ const opened = await openWorktreeResultForTab(tab, createdResult, { openTab: body.openTab !== false, sessionMode: body.sessionMode || "fork-current", ...body });
4109
+ if (createdResult.created) {
4110
+ recordEvent({ type: "webui_worktree_created", tabId: opened.tab?.id || tab.id, cwd: opened.worktree?.path || opened.path, branch });
4111
+ }
4112
+ recordEvent({ type: "webui_git_workflow_worktree", tabId: opened.tab?.id || tab.id, cwd: worktreePath, branch, transferredStagedChanges: transfer.appliedStagedPatch });
4113
+ return {
4114
+ ...opened,
4115
+ command: createdResult.created ? formatGitCommand(["worktree", "add", "-b", branch, worktreePath]) : formatGitCommand(["worktree", "list", "--porcelain"]),
4116
+ stdout: gitWorkflowBranchWorktreeStdout({ branch, worktreePath, createdResult, opened, transfer }),
4117
+ stderr: "",
4118
+ exitCode: 0,
4119
+ branch: opened.branch || branch,
4120
+ carriedStagedChanges: transfer.appliedStagedPatch,
4121
+ copiedMessageFiles: transfer.copiedMessageFiles,
4122
+ };
4123
+ } catch (error) {
4124
+ let cleanup = null;
4125
+ const createdPath = createdResult?.created && !createdResult?.openedExisting ? createdResult.worktree?.path || createdResult.path : "";
4126
+ if (createdPath) cleanup = await cleanupCreatedWorktreeAfterFailure(tab.cwd, createdPath);
4127
+ recordEvent({ type: "webui_git_workflow_worktree_failed", tabId: tab.id, cwd: createdPath || tab.cwd, branch, error: sanitizeError(error), cleanup });
4128
+ throw error;
4129
+ }
4130
+ }
4131
+
4132
+ async function createGitWorktreeTab(tab, body = {}) {
4133
+ let createdResult = null;
4134
+ try {
4135
+ createdResult = await createGitWorktree(tab.cwd, body);
4136
+ const opened = await openWorktreeResultForTab(tab, createdResult, { openTab: body.openTab !== false, ...body });
4137
+ if (createdResult.created) {
4138
+ recordEvent({ type: "webui_worktree_created", tabId: opened.tab?.id || tab.id, cwd: opened.worktree?.path || opened.path, branch: opened.branch || body.branchName || "" });
4139
+ }
4140
+ return opened;
4141
+ } catch (error) {
4142
+ let cleanup = null;
4143
+ const createdPath = createdResult?.created && !createdResult?.openedExisting ? createdResult.worktree?.path || createdResult.path : "";
4144
+ if (createdPath) cleanup = await cleanupCreatedWorktreeAfterFailure(tab.cwd, createdPath);
4145
+ recordEvent({ type: "webui_worktree_create_failed", tabId: tab.id, cwd: createdPath || tab.cwd, branch: body.branchName || body.branch || "", error: sanitizeError(error), cleanup });
4146
+ throw error;
4147
+ }
4148
+ }
4149
+
4150
+ async function openExistingGitWorktreeTab(tab, body = {}) {
4151
+ const requestedPath = String(body.path || body.worktreePath || "").trim();
4152
+ if (!requestedPath) throw makeHttpError(400, "worktree path is required");
4153
+ const result = await openGitWorktree(tab.cwd, requestedPath);
4154
+ return openWorktreeResultForTab(tab, result, { openTab: body.openTab !== false, ...body });
4155
+ }
4156
+
4157
+ function openTabsInsideWorktree(worktreePath) {
4158
+ return [...tabs.values()].filter((tab) => pathInside(worktreePath, tab.cwd));
4159
+ }
4160
+
4161
+ async function removeGitWorktreeForTab(tab, body = {}) {
4162
+ if (body.confirmed !== true) throw makeHttpError(409, "Removing a worktree requires confirmed: true because it deletes files under the worktree path.");
4163
+ const requestedPath = String(body.path || body.worktreePath || "").trim();
4164
+ if (!requestedPath) throw makeHttpError(400, "worktree path is required");
4165
+ const activeTabs = openTabsInsideWorktree(requestedPath);
4166
+ if (activeTabs.length) {
4167
+ const error = makeHttpError(409, `Refusing to remove a worktree that is open in ${activeTabs.length} Web UI tab${activeTabs.length === 1 ? "" : "s"}.`);
4168
+ error.code = WORKTREE_ERROR_CODES.WORKTREE_BUSY;
4169
+ error.details = { path: requestedPath, tabIds: activeTabs.map((item) => item.id) };
4170
+ throw error;
4171
+ }
4172
+ const result = await removeGitWorktree(tab.cwd, requestedPath, { force: body.force === true });
4173
+ recordEvent({ type: "webui_worktree_removed", tabId: tab.id, cwd: result.path || requestedPath, branch: result.branch || "" });
4174
+ return { ...result, tabs: listTabs() };
4175
+ }
4176
+
4177
+ function sendGitWorktreeFailure(res, error) {
4178
+ sendJson(res, 200, gitWorktreeErrorPayload(error));
4179
+ }
4180
+
3747
4181
  async function defaultGitRemote(root) {
3748
4182
  const result = await runGitWorkflowCommand(["remote"], { cwd: root, timeoutMs: 5000 });
3749
4183
  if (result.exitCode !== 0) throw new Error((result.stderr || result.stdout || "Cannot list git remotes").trim());
@@ -3855,7 +4289,9 @@ function gitWorkflowCommandPayload(result) {
3855
4289
  };
3856
4290
  }
3857
4291
 
3858
- async function handleGitWorkflowRequest(pathname, body = {}, cwd = options.cwd) {
4292
+ async function handleGitWorkflowRequest(pathname, body = {}, tabOrCwd = options.cwd) {
4293
+ const tab = tabOrCwd && typeof tabOrCwd === "object" ? tabOrCwd : null;
4294
+ const cwd = tab?.cwd || tabOrCwd || options.cwd;
3859
4295
  try {
3860
4296
  switch (pathname) {
3861
4297
  case "/api/git-workflow/message":
@@ -3904,12 +4340,8 @@ async function handleGitWorkflowRequest(pathname, body = {}, cwd = options.cwd)
3904
4340
  await getGitRoot(cwd);
3905
4341
  return gitWorkflowCommandPayload(await runGitWorkflowCommand(["add", "."], { cwd }));
3906
4342
  case "/api/git-workflow/branch": {
3907
- const root = await getGitRoot(cwd);
3908
- const branch = cleanGitBranchName(body.branch);
3909
- await validateGitBranchName(root, branch);
3910
- const payload = gitWorkflowCommandPayload(await runGitWorkflowCommand(["switch", "-c", branch], { cwd: root }));
3911
- if (payload.ok) payload.data.branch = branch;
3912
- return payload;
4343
+ if (!tab) throw new Error("Git workflow branch worktree requires a Web UI tab");
4344
+ return { ok: true, data: await createGitWorkflowBranchWorktree(tab, body) };
3913
4345
  }
3914
4346
  case "/api/git-workflow/commit": {
3915
4347
  const variant = String(body.variant || "").trim();
@@ -5078,7 +5510,7 @@ function attachRpcToTab(tab, rpc) {
5078
5510
  });
5079
5511
  }
5080
5512
 
5081
- async function createTab({ id: requestedId, index, title, titleSource, conversationStarted, cwd, sessionFile } = {}) {
5513
+ async function createTab({ id: requestedId, index, title, titleSource, conversationStarted, cwd, sessionFile, gitWorkspace } = {}) {
5082
5514
  const tabIndex = Number.isInteger(index) && index > 0 ? index : nextTabIndex;
5083
5515
  nextTabIndex = Math.max(nextTabIndex, tabIndex + 1);
5084
5516
  const explicitTitle = String(title || "").trim();
@@ -5101,6 +5533,7 @@ async function createTab({ id: requestedId, index, title, titleSource, conversat
5101
5533
  cwd: tabCwd,
5102
5534
  createdAt,
5103
5535
  sessionFile: options.noSession ? undefined : normalizedRestoreString(sessionFile, 4096),
5536
+ gitWorkspace: gitWorkspace || null,
5104
5537
  lastState: null,
5105
5538
  pendingThinkingLevel: undefined,
5106
5539
  activity: createTabActivity(createdAt),
@@ -5147,6 +5580,7 @@ function tabMeta(tab) {
5147
5580
  conversationStarted: !!tab.conversationStarted,
5148
5581
  cwd: tab.cwd,
5149
5582
  sessionFile: tabRestorableSessionFile(tab),
5583
+ gitWorkspace: tab.gitWorkspace || null,
5150
5584
  pendingThinkingLevel: tab.pendingThinkingLevel || null,
5151
5585
  createdAt: tab.createdAt,
5152
5586
  startedAt: tab.rpc.startedAt,
@@ -5156,6 +5590,7 @@ function tabMeta(tab) {
5156
5590
  clientCount: tab.sseClients.size,
5157
5591
  pendingExtensionUiRequestCount: pendingExtensionUiRequests(tab).length,
5158
5592
  activity: tabActivitySnapshot(tab),
5593
+ appRunner: publicAppRunnerState(tab.appRunner),
5159
5594
  };
5160
5595
  }
5161
5596
 
@@ -7583,6 +8018,13 @@ const server = createServer(async (req, res) => {
7583
8018
  return;
7584
8019
  }
7585
8020
 
8021
+ if (url.pathname === "/api/app-runner/context" && req.method === "POST") {
8022
+ const body = await readJsonBody(req);
8023
+ const tab = getRequestedTab(req, url, body);
8024
+ sendJson(res, 200, { ok: true, data: await transferAppRunnerContext(tab, body) });
8025
+ return;
8026
+ }
8027
+
7586
8028
  if (url.pathname === "/api/app-runner/stop" && req.method === "POST") {
7587
8029
  const body = await readJsonBody(req);
7588
8030
  const tab = getRequestedTab(req, url, body);
@@ -7839,6 +8281,18 @@ const server = createServer(async (req, res) => {
7839
8281
  return;
7840
8282
  }
7841
8283
 
8284
+ if (url.pathname === "/api/queue/remove" && req.method === "POST") {
8285
+ const body = await readJsonBody(req);
8286
+ const tab = getRequestedTab(req, url, body);
8287
+ const data = await sendWebuiHelperCommand(tab, "queue-remove", {
8288
+ kind: body.kind || "followUp",
8289
+ index: body.index,
8290
+ message: body.message,
8291
+ });
8292
+ sendJson(res, 200, { ok: true, data });
8293
+ return;
8294
+ }
8295
+
7842
8296
  if (url.pathname === "/api/prompt" && req.method === "POST") {
7843
8297
  const body = await readJsonBody(req, { limitBytes: requestBodyLimitForPath(url.pathname) });
7844
8298
  const tab = getRequestedTab(req, url, body);
@@ -7895,6 +8349,50 @@ const server = createServer(async (req, res) => {
7895
8349
  return;
7896
8350
  }
7897
8351
 
8352
+ if (url.pathname === "/api/git-worktrees" && req.method === "GET") {
8353
+ const tab = getRequestedTab(req, url);
8354
+ try {
8355
+ sendJson(res, 200, { ok: true, data: await listGitWorktrees(tab.cwd) });
8356
+ } catch (error) {
8357
+ sendGitWorktreeFailure(res, error);
8358
+ }
8359
+ return;
8360
+ }
8361
+
8362
+ if (url.pathname === "/api/git-worktrees" && req.method === "POST") {
8363
+ const body = await readJsonBody(req);
8364
+ const tab = getRequestedTab(req, url, body);
8365
+ try {
8366
+ sendJson(res, 200, { ok: true, data: await createGitWorktreeTab(tab, body) });
8367
+ } catch (error) {
8368
+ sendGitWorktreeFailure(res, error);
8369
+ }
8370
+ return;
8371
+ }
8372
+
8373
+ if (url.pathname === "/api/git-worktrees/open" && req.method === "POST") {
8374
+ const body = await readJsonBody(req);
8375
+ const tab = getRequestedTab(req, url, body);
8376
+ try {
8377
+ sendJson(res, 200, { ok: true, data: await openExistingGitWorktreeTab(tab, body) });
8378
+ } catch (error) {
8379
+ sendGitWorktreeFailure(res, error);
8380
+ }
8381
+ return;
8382
+ }
8383
+
8384
+ if (url.pathname === "/api/git-worktrees" && req.method === "DELETE") {
8385
+ requireLocalhost(req, "Removing Git worktrees is only allowed from localhost");
8386
+ const body = await readJsonBody(req);
8387
+ const tab = getRequestedTab(req, url, body);
8388
+ try {
8389
+ sendJson(res, 200, { ok: true, data: await removeGitWorktreeForTab(tab, body) });
8390
+ } catch (error) {
8391
+ sendGitWorktreeFailure(res, error);
8392
+ }
8393
+ return;
8394
+ }
8395
+
7898
8396
  if (url.pathname === "/api/git-branches" && req.method === "GET") {
7899
8397
  const tab = getRequestedTab(req, url);
7900
8398
  try {
@@ -7919,7 +8417,7 @@ const server = createServer(async (req, res) => {
7919
8417
  if (url.pathname.startsWith("/api/git-workflow/")) {
7920
8418
  const body = req.method === "POST" ? await readJsonBody(req) : {};
7921
8419
  const tab = getRequestedTab(req, url, body);
7922
- const response = await handleGitWorkflowRequest(url.pathname, body, tab.cwd);
8420
+ const response = await handleGitWorkflowRequest(url.pathname, body, tab);
7923
8421
  if (response) {
7924
8422
  sendJson(res, 200, response);
7925
8423
  return;