@firstpick/pi-package-webui 0.5.6 → 0.5.7

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
@@ -152,7 +152,7 @@ Environment variables:
152
152
 
153
153
  ## Native Pi command coverage
154
154
 
155
- Web UI keeps a packaged parity matrix at `dev/docs/WEBUI_TUI_NATIVE_PARITY.json` and exposes it at `GET /api/native-parity`.
155
+ Web UI keeps a packaged parity matrix at `lib/WEBUI_TUI_NATIVE_PARITY.json` and exposes it at `GET /api/native-parity`.
156
156
 
157
157
  | Status | Commands and behavior |
158
158
  | --- | --- |
@@ -329,6 +329,8 @@ For local development, run the checkout helper directly, for example:
329
329
  ./dev/scripts/start-webui.sh --dev --cwd /path/to/project
330
330
  ```
331
331
 
332
+ The `--dev` helper checks this checkout's local npm dependencies before launch, applies available local updates, and force-refreshes `@earendil-works/pi-coding-agent` to the latest npm version so stale bundled Pi runtime packages do not break extension loading. Set `PI_WEBUI_DEV_SKIP_UPDATE=1` to skip this preflight for offline or intentionally pinned local testing.
333
+
332
334
  Run `../dev/scripts/sync-pi-package-symlinks.sh` first when developing companion packages from this workspace. The Web UI manifest loads companions through `node_modules/` paths, and the sync script links those paths to the top-level dev packages so only one copy is loaded.
333
335
 
334
336
  ## Optional companion packages
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,6 +189,8 @@ 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;
184
195
  const APP_RUNNER_PYTHON_ENTRIES = ["Main.py", "main.py", "src/main.py", "src/Main.py", "app.py", "src/app.py"];
185
196
  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"];
@@ -421,6 +432,10 @@ function truncateLongText(value, maxLength = 8000) {
421
432
  return `${text.slice(0, Math.max(0, maxLength - 1))}…`;
422
433
  }
423
434
 
435
+ function stripAnsi(text) {
436
+ return String(text ?? "").replace(/(?:\x1B|\u241B)(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g, "");
437
+ }
438
+
424
439
  function parsePackageVersion(version) {
425
440
  const match = String(version || "").trim().match(/^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+.*)?$/);
426
441
  if (!match) return undefined;
@@ -2556,6 +2571,59 @@ function clearAppRunnerForTab(tab) {
2556
2571
  return true;
2557
2572
  }
2558
2573
 
2574
+ function normalizeAppRunnerContextLineCount(value) {
2575
+ const number = Number.parseInt(String(value ?? ""), 10);
2576
+ if (!Number.isFinite(number)) return APP_RUNNER_CONTEXT_DEFAULT_LINES;
2577
+ return Math.max(1, Math.min(APP_RUNNER_CONTEXT_MAX_LINES, number));
2578
+ }
2579
+
2580
+ function appRunnerOutputLinesForContext(run) {
2581
+ const lines = Array.isArray(run?.lines) ? [...run.lines] : [];
2582
+ const pendingLine = appRunnerPendingLine(run);
2583
+ if (pendingLine) lines.push(pendingLine);
2584
+ return lines.map((line) => stripAnsi(line).replace(/\r\n?/g, "\n"));
2585
+ }
2586
+
2587
+ function formatAppRunnerContextContent(tab, run, { requestedLineCount, lines, totalAvailableLines }) {
2588
+ const status = appRunnerStatusLabel(run);
2589
+ const capturedAt = new Date().toISOString();
2590
+ const header = [
2591
+ "App runner output transferred from Pi Web UI.",
2592
+ `Command: ${stripAnsi(run?.displayCommand || run?.command || "app runner")}`,
2593
+ `Cwd: ${stripAnsi(run?.cwd || tab?.cwd || "")}`,
2594
+ `Status: ${status}`,
2595
+ `Captured: last ${lines.length} of ${totalAvailableLines} available line${totalAvailableLines === 1 ? "" : "s"} (requested ${requestedLineCount})`,
2596
+ run?.truncated ? "Note: earlier app runner output had already been truncated before this capture." : "",
2597
+ `Captured at: ${capturedAt}`,
2598
+ ].filter(Boolean);
2599
+ return `${header.join("\n")}\n\n\`\`\`\`text\n${lines.join("\n").trimEnd()}\n\`\`\`\``;
2600
+ }
2601
+
2602
+ async function transferAppRunnerContext(tab, body = {}) {
2603
+ const run = tab?.appRunner;
2604
+ if (!run) throw makeHttpError(409, "No app runner output is available in this tab");
2605
+ const requestedLineCount = normalizeAppRunnerContextLineCount(body.lineCount ?? body.lines ?? body.count);
2606
+ const allLines = appRunnerOutputLinesForContext(run);
2607
+ const lines = allLines.slice(-requestedLineCount);
2608
+ if (!lines.some((line) => stripAnsi(line).trim())) throw makeHttpError(400, "App runner output is empty");
2609
+ const details = {
2610
+ runId: run.id,
2611
+ runnerId: run.runnerId,
2612
+ command: run.displayCommand || run.command || "",
2613
+ cwd: run.cwd || tab.cwd,
2614
+ status: run.status || "running",
2615
+ requestedLineCount,
2616
+ lineCount: lines.length,
2617
+ totalAvailableLines: allLines.length,
2618
+ truncated: run.truncated === true,
2619
+ capturedAt: new Date().toISOString(),
2620
+ };
2621
+ const content = formatAppRunnerContextContent(tab, run, { requestedLineCount, lines, totalAvailableLines: allLines.length });
2622
+ const helperData = await sendWebuiHelperCommand(tab, "app-runner-context", { content, details });
2623
+ recordEvent({ type: "webui_app_runner_context", tabId: tab.id, tabTitle: tab.title, command: details.command, lineCount: lines.length, requestedLineCount, delivery: helperData?.delivery || "context" });
2624
+ return { ...details, delivery: helperData?.delivery || "context", activeRun: publicAppRunnerState(run) };
2625
+ }
2626
+
2559
2627
  function firstDefined(...values) {
2560
2628
  return values.find((value) => value !== undefined && value !== null);
2561
2629
  }
@@ -3707,16 +3775,31 @@ function normalizeGitBranchList(branchText, current = "") {
3707
3775
 
3708
3776
  async function readGitBranches(cwd) {
3709
3777
  const root = await getGitRoot(cwd);
3710
- const [current, branchText] = await Promise.all([
3778
+ const [current, branchText, worktreeData] = await Promise.all([
3711
3779
  currentGitBranchForPicker(root),
3712
3780
  runGitReadCommand(root, ["branch", "--format=%(refname:short)"], { timeoutMs: 5000, maxOutputLength: 120_000 }),
3781
+ listGitWorktrees(cwd).catch(() => null),
3713
3782
  ]);
3783
+ const occupiedByBranch = new Map();
3784
+ for (const item of worktreeData?.occupiedBranches || []) {
3785
+ if (!item?.branch || occupiedByBranch.has(item.branch)) continue;
3786
+ occupiedByBranch.set(item.branch, item);
3787
+ }
3714
3788
  return {
3715
3789
  cwd,
3716
3790
  root,
3791
+ repoRoot: worktreeData?.repoRoot || root,
3792
+ commonGitDir: worktreeData?.commonGitDir || "",
3793
+ currentWorktreePath: worktreeData?.currentWorktreePath || root,
3794
+ defaultWorktreesRoot: worktreeData?.defaultWorktreesRoot || "",
3717
3795
  current,
3718
3796
  generatedAt: new Date().toISOString(),
3719
- branches: normalizeGitBranchList(branchText, current),
3797
+ branches: normalizeGitBranchList(branchText, current).map((branch) => {
3798
+ const occupied = occupiedByBranch.get(branch.name);
3799
+ return occupied ? { ...branch, occupied: true, worktreePath: occupied.path, worktreeCurrent: occupied.current === true, mainWorktree: occupied.isMainWorktree === true } : branch;
3800
+ }),
3801
+ worktrees: worktreeData?.worktrees || [],
3802
+ occupiedBranches: worktreeData?.occupiedBranches || [],
3720
3803
  };
3721
3804
  }
3722
3805
 
@@ -3728,6 +3811,15 @@ async function switchGitBranch(cwd, branch, { create = false } = {}) {
3728
3811
  const branchExists = branches.branches.some((item) => item.name === targetBranch);
3729
3812
  if (create && branchExists) throw new Error(`Local git branch already exists: ${targetBranch}`);
3730
3813
  if (!create && !branchExists) throw new Error(`Unknown local git branch: ${targetBranch}`);
3814
+ const occupied = branches.branches.find((item) => item.name === targetBranch && item.occupied && !item.worktreeCurrent);
3815
+ if (!create && occupied?.worktreePath) {
3816
+ return {
3817
+ ok: false,
3818
+ code: WORKTREE_ERROR_CODES.BRANCH_CHECKED_OUT_ELSEWHERE,
3819
+ error: `Branch ${targetBranch} is already checked out at ${occupied.worktreePath}. Open that worktree instead of switching this checkout.`,
3820
+ data: { branch: targetBranch, root, worktreePath: occupied.worktreePath },
3821
+ };
3822
+ }
3731
3823
  if (!create && branches.current === targetBranch) {
3732
3824
  return { ok: true, data: { command: `git switch ${targetBranch}`, stdout: "", stderr: "", exitCode: 0, branch: targetBranch, root, switched: false, created: false } };
3733
3825
  }
@@ -3744,6 +3836,271 @@ async function switchGitBranch(cwd, branch, { create = false } = {}) {
3744
3836
  return payload;
3745
3837
  }
3746
3838
 
3839
+ function normalizeWorktreeSessionMode(value) {
3840
+ const mode = String(value || "fork-current").trim().toLowerCase();
3841
+ if (!mode || mode === "fork" || mode === "fork-current") return "fork-current";
3842
+ if (mode === "empty" || mode === "new") return "empty";
3843
+ if (mode === "clone-current" || mode === "parent-only") {
3844
+ throw makeHttpError(400, `sessionMode ${mode} is not supported yet; use fork-current or empty.`);
3845
+ }
3846
+ throw makeHttpError(400, "sessionMode must be fork-current or empty");
3847
+ }
3848
+
3849
+ async function createEmptySessionFileForCwd(cwd) {
3850
+ const manager = SessionManager.create(cwd, configuredSessionDir());
3851
+ const sessionFile = manager.getSessionFile();
3852
+ const header = manager.getHeader();
3853
+ if (!sessionFile || !header) return undefined;
3854
+ await mkdir(path.dirname(sessionFile), { recursive: true });
3855
+ await writeFile(sessionFile, `${JSON.stringify(header)}\n`, { encoding: "utf8", flag: "wx" });
3856
+ return sessionFile;
3857
+ }
3858
+
3859
+ async function prepareWorktreeSessionFile(sourceTab, targetCwd, requestedMode = "fork-current") {
3860
+ if (options.noSession) return { mode: "none", requestedMode: "none", sessionFile: undefined, warning: "Web UI was started with --no-session." };
3861
+ const mode = normalizeWorktreeSessionMode(requestedMode);
3862
+ if (mode === "empty") {
3863
+ return { mode, requestedMode: mode, sessionFile: await createEmptySessionFileForCwd(targetCwd) };
3864
+ }
3865
+
3866
+ const state = await currentSessionState(sourceTab).catch(() => sourceTab?.lastState || {});
3867
+ const sourceSessionFile = state.sessionFile || tabRestorableSessionFile(sourceTab);
3868
+ if (sourceSessionFile) {
3869
+ requireAllowedSessionPath(sourceSessionFile);
3870
+ const sourceInfo = await stat(sourceSessionFile).catch(() => null);
3871
+ if (sourceInfo?.isFile()) {
3872
+ const manager = SessionManager.forkFrom(sourceSessionFile, targetCwd, configuredSessionDir());
3873
+ return { mode, requestedMode: mode, sessionFile: manager.getSessionFile(), parentSession: sourceSessionFile };
3874
+ }
3875
+ }
3876
+
3877
+ return {
3878
+ mode: "empty",
3879
+ requestedMode: mode,
3880
+ sessionFile: await createEmptySessionFileForCwd(targetCwd),
3881
+ warning: "Current session is not persisted yet; opened an empty session rooted at the worktree.",
3882
+ };
3883
+ }
3884
+
3885
+ function gitWorkspaceFromWorktreeResult(result, worktree = result?.worktree) {
3886
+ if (!worktree?.path) return null;
3887
+ return {
3888
+ repoRoot: result.repoRoot || worktree.repoRoot || "",
3889
+ commonGitDir: result.commonGitDir || worktree.commonGitDir || "",
3890
+ worktreePath: worktree.path,
3891
+ branch: worktree.branch || result.branch || null,
3892
+ worktreeCount: Array.isArray(result.worktrees) ? result.worktrees.length : undefined,
3893
+ isMainWorktree: worktree.isMainWorktree === true,
3894
+ };
3895
+ }
3896
+
3897
+ async function openWorktreeResultForTab(sourceTab, result, body = {}) {
3898
+ const worktree = result?.worktree;
3899
+ const worktreePath = worktree?.path || result?.path;
3900
+ if (!worktreePath) throw makeHttpError(500, "Git worktree operation did not return a path");
3901
+ if (body.openTab === false) return { ...result, session: null, tab: null, tabs: listTabs(), openedTab: false };
3902
+
3903
+ if (sameResolvedPath(worktreePath, sourceTab.cwd)) {
3904
+ sourceTab.gitWorkspace = gitWorkspaceFromWorktreeResult(result, worktree);
3905
+ return { ...result, session: null, tab: tabMeta(sourceTab), tabs: listTabs(), openedTab: false, openedCurrent: true };
3906
+ }
3907
+
3908
+ const existingTab = [...tabs.values()].find((item) => sameResolvedPath(item.cwd, worktreePath));
3909
+ if (existingTab) {
3910
+ existingTab.gitWorkspace = gitWorkspaceFromWorktreeResult(result, worktree);
3911
+ return { ...result, session: null, tab: tabMeta(existingTab), tabs: listTabs(), openedTab: false, openedExistingTab: true };
3912
+ }
3913
+
3914
+ const session = await prepareWorktreeSessionFile(sourceTab, worktreePath, body.sessionMode || "fork-current");
3915
+ const tab = await createTab({
3916
+ title: body.title,
3917
+ titleSource: body.title ? "explicit" : undefined,
3918
+ cwd: worktreePath,
3919
+ sessionFile: session.sessionFile,
3920
+ gitWorkspace: gitWorkspaceFromWorktreeResult(result, worktree),
3921
+ });
3922
+ recordEvent({ type: "webui_worktree_opened", tabId: tab.id, tabTitle: tab.title, cwd: tab.cwd, branch: worktree.branch || result.branch || "", sessionMode: session.mode });
3923
+ return {
3924
+ ...result,
3925
+ session,
3926
+ tab: tabMeta(tab),
3927
+ tabs: listTabs(),
3928
+ openedTab: true,
3929
+ dependencyHint: "Git worktrees do not share ignored dependency directories such as node_modules or .venv; install/bootstrap dependencies manually if needed.",
3930
+ };
3931
+ }
3932
+
3933
+ async function cleanupCreatedWorktreeAfterFailure(sourceCwd, worktreePath) {
3934
+ try {
3935
+ return await removeGitWorktree(sourceCwd, worktreePath, { force: true });
3936
+ } catch (error) {
3937
+ return { ok: false, error: sanitizeError(error), code: error?.code || WORKTREE_ERROR_CODES.GIT_COMMAND_FAILED };
3938
+ }
3939
+ }
3940
+
3941
+ async function readGitWorkflowMessageFilesForTransfer(root) {
3942
+ const { shortPath, longPath } = commitMessagePaths(root);
3943
+ const files = [];
3944
+ for (const sourcePath of [shortPath, longPath]) {
3945
+ try {
3946
+ const content = await readFile(sourcePath, "utf8");
3947
+ files.push({ relativePath: path.relative(root, sourcePath).split(path.sep).join("/"), content });
3948
+ } catch (error) {
3949
+ if (error?.code !== "ENOENT") throw error;
3950
+ }
3951
+ }
3952
+ return files;
3953
+ }
3954
+
3955
+ async function snapshotGitWorkflowBranchState(root) {
3956
+ const diffResult = await runGitWorkflowCommand(["diff", "--cached", "--binary", "--full-index"], {
3957
+ cwd: root,
3958
+ label: "git diff --cached --binary --full-index",
3959
+ timeoutMs: 60 * 1000,
3960
+ });
3961
+ if (diffResult.exitCode !== 0 || diffResult.timedOut || diffResult.cancelled || diffResult.error) {
3962
+ throw new Error((diffResult.stderr || diffResult.stdout || diffResult.error || "Unable to read staged changes for the PR worktree").trim());
3963
+ }
3964
+ return {
3965
+ stagedPatch: diffResult.stdout || "",
3966
+ messageFiles: await readGitWorkflowMessageFilesForTransfer(root),
3967
+ };
3968
+ }
3969
+
3970
+ async function applyGitWorkflowBranchStateToWorktree(snapshot, worktreePath) {
3971
+ const copiedMessageFiles = [];
3972
+ let appliedStagedPatch = false;
3973
+ const patchText = String(snapshot?.stagedPatch || "");
3974
+ if (patchText.trim()) {
3975
+ const patchPath = path.join(tmpdir(), `pi-webui-staged-worktree-${process.pid}-${Date.now()}-${randomUUID()}.patch`);
3976
+ await writeFile(patchPath, patchText, "utf8");
3977
+ try {
3978
+ const applyResult = await runGitWorkflowCommand(["apply", "--index", "--whitespace=nowarn", patchPath], {
3979
+ cwd: worktreePath,
3980
+ label: "git apply --index <staged diff>",
3981
+ timeoutMs: 5 * 60 * 1000,
3982
+ });
3983
+ if (applyResult.exitCode !== 0 || applyResult.timedOut || applyResult.cancelled || applyResult.error) {
3984
+ throw new Error((applyResult.stderr || applyResult.stdout || applyResult.error || "Unable to apply staged changes in the PR worktree").trim());
3985
+ }
3986
+ appliedStagedPatch = true;
3987
+ } finally {
3988
+ await rm(patchPath, { force: true }).catch(() => {});
3989
+ }
3990
+ }
3991
+
3992
+ for (const file of snapshot?.messageFiles || []) {
3993
+ const relativePath = String(file.relativePath || "").replace(/\\/g, "/");
3994
+ const targetPath = path.resolve(worktreePath, relativePath);
3995
+ if (!relativePath || !pathInside(worktreePath, targetPath)) throw new Error(`Refusing to copy Git workflow file outside the worktree: ${relativePath}`);
3996
+ await mkdir(path.dirname(targetPath), { recursive: true });
3997
+ await writeFile(targetPath, file.content, "utf8");
3998
+ copiedMessageFiles.push(relativePath);
3999
+ }
4000
+
4001
+ return { appliedStagedPatch, copiedMessageFiles };
4002
+ }
4003
+
4004
+ function gitWorkflowBranchWorktreeStdout({ branch, worktreePath, createdResult, opened, transfer }) {
4005
+ const lines = [];
4006
+ if (createdResult?.created) lines.push(`Created branch worktree ${branch} at ${worktreePath}.`);
4007
+ else if (createdResult?.openedExisting) lines.push(`Opened existing branch worktree ${branch} at ${worktreePath}.`);
4008
+ else lines.push(`Opened branch worktree ${branch} at ${worktreePath}.`);
4009
+ if (transfer?.appliedStagedPatch) lines.push("Copied the source checkout's staged changes into the worktree index.");
4010
+ else if (createdResult?.openedExisting) lines.push("Existing worktree was reused; source staged changes were not copied automatically.");
4011
+ else lines.push("No staged changes were copied because the source index was clean.");
4012
+ if (transfer?.copiedMessageFiles?.length) lines.push(`Copied ${transfer.copiedMessageFiles.join(", ")} for commit message selection.`);
4013
+ if (opened?.tab?.id) lines.push(`Continue the guided Git workflow in Web UI tab ${opened.tab.title || opened.tab.id}.`);
4014
+ lines.push("The source checkout was left on its current branch.");
4015
+ return lines.join("\n");
4016
+ }
4017
+
4018
+ async function createGitWorkflowBranchWorktree(tab, body = {}) {
4019
+ const root = await getGitRoot(tab.cwd);
4020
+ const branch = cleanGitBranchName(body.branch || body.branchName);
4021
+ await validateGitBranchName(root, branch);
4022
+ const snapshot = await snapshotGitWorkflowBranchState(root);
4023
+ let createdResult = null;
4024
+ try {
4025
+ createdResult = await createGitWorktree(tab.cwd, { ...body, branchName: branch });
4026
+ const worktreePath = createdResult.worktree?.path || createdResult.path;
4027
+ if (!worktreePath) throw makeHttpError(500, "Git workflow worktree creation did not return a path");
4028
+ const transfer = createdResult.created
4029
+ ? await applyGitWorkflowBranchStateToWorktree(snapshot, worktreePath)
4030
+ : { appliedStagedPatch: false, copiedMessageFiles: [] };
4031
+ const opened = await openWorktreeResultForTab(tab, createdResult, { openTab: body.openTab !== false, sessionMode: body.sessionMode || "fork-current", ...body });
4032
+ if (createdResult.created) {
4033
+ recordEvent({ type: "webui_worktree_created", tabId: opened.tab?.id || tab.id, cwd: opened.worktree?.path || opened.path, branch });
4034
+ }
4035
+ recordEvent({ type: "webui_git_workflow_worktree", tabId: opened.tab?.id || tab.id, cwd: worktreePath, branch, transferredStagedChanges: transfer.appliedStagedPatch });
4036
+ return {
4037
+ ...opened,
4038
+ command: createdResult.created ? formatGitCommand(["worktree", "add", "-b", branch, worktreePath]) : formatGitCommand(["worktree", "list", "--porcelain"]),
4039
+ stdout: gitWorkflowBranchWorktreeStdout({ branch, worktreePath, createdResult, opened, transfer }),
4040
+ stderr: "",
4041
+ exitCode: 0,
4042
+ branch: opened.branch || branch,
4043
+ carriedStagedChanges: transfer.appliedStagedPatch,
4044
+ copiedMessageFiles: transfer.copiedMessageFiles,
4045
+ };
4046
+ } catch (error) {
4047
+ let cleanup = null;
4048
+ const createdPath = createdResult?.created && !createdResult?.openedExisting ? createdResult.worktree?.path || createdResult.path : "";
4049
+ if (createdPath) cleanup = await cleanupCreatedWorktreeAfterFailure(tab.cwd, createdPath);
4050
+ recordEvent({ type: "webui_git_workflow_worktree_failed", tabId: tab.id, cwd: createdPath || tab.cwd, branch, error: sanitizeError(error), cleanup });
4051
+ throw error;
4052
+ }
4053
+ }
4054
+
4055
+ async function createGitWorktreeTab(tab, body = {}) {
4056
+ let createdResult = null;
4057
+ try {
4058
+ createdResult = await createGitWorktree(tab.cwd, body);
4059
+ const opened = await openWorktreeResultForTab(tab, createdResult, { openTab: body.openTab !== false, ...body });
4060
+ if (createdResult.created) {
4061
+ recordEvent({ type: "webui_worktree_created", tabId: opened.tab?.id || tab.id, cwd: opened.worktree?.path || opened.path, branch: opened.branch || body.branchName || "" });
4062
+ }
4063
+ return opened;
4064
+ } catch (error) {
4065
+ let cleanup = null;
4066
+ const createdPath = createdResult?.created && !createdResult?.openedExisting ? createdResult.worktree?.path || createdResult.path : "";
4067
+ if (createdPath) cleanup = await cleanupCreatedWorktreeAfterFailure(tab.cwd, createdPath);
4068
+ recordEvent({ type: "webui_worktree_create_failed", tabId: tab.id, cwd: createdPath || tab.cwd, branch: body.branchName || body.branch || "", error: sanitizeError(error), cleanup });
4069
+ throw error;
4070
+ }
4071
+ }
4072
+
4073
+ async function openExistingGitWorktreeTab(tab, body = {}) {
4074
+ const requestedPath = String(body.path || body.worktreePath || "").trim();
4075
+ if (!requestedPath) throw makeHttpError(400, "worktree path is required");
4076
+ const result = await openGitWorktree(tab.cwd, requestedPath);
4077
+ return openWorktreeResultForTab(tab, result, { openTab: body.openTab !== false, ...body });
4078
+ }
4079
+
4080
+ function openTabsInsideWorktree(worktreePath) {
4081
+ return [...tabs.values()].filter((tab) => pathInside(worktreePath, tab.cwd));
4082
+ }
4083
+
4084
+ async function removeGitWorktreeForTab(tab, body = {}) {
4085
+ if (body.confirmed !== true) throw makeHttpError(409, "Removing a worktree requires confirmed: true because it deletes files under the worktree path.");
4086
+ const requestedPath = String(body.path || body.worktreePath || "").trim();
4087
+ if (!requestedPath) throw makeHttpError(400, "worktree path is required");
4088
+ const activeTabs = openTabsInsideWorktree(requestedPath);
4089
+ if (activeTabs.length) {
4090
+ const error = makeHttpError(409, `Refusing to remove a worktree that is open in ${activeTabs.length} Web UI tab${activeTabs.length === 1 ? "" : "s"}.`);
4091
+ error.code = WORKTREE_ERROR_CODES.WORKTREE_BUSY;
4092
+ error.details = { path: requestedPath, tabIds: activeTabs.map((item) => item.id) };
4093
+ throw error;
4094
+ }
4095
+ const result = await removeGitWorktree(tab.cwd, requestedPath, { force: body.force === true });
4096
+ recordEvent({ type: "webui_worktree_removed", tabId: tab.id, cwd: result.path || requestedPath, branch: result.branch || "" });
4097
+ return { ...result, tabs: listTabs() };
4098
+ }
4099
+
4100
+ function sendGitWorktreeFailure(res, error) {
4101
+ sendJson(res, 200, gitWorktreeErrorPayload(error));
4102
+ }
4103
+
3747
4104
  async function defaultGitRemote(root) {
3748
4105
  const result = await runGitWorkflowCommand(["remote"], { cwd: root, timeoutMs: 5000 });
3749
4106
  if (result.exitCode !== 0) throw new Error((result.stderr || result.stdout || "Cannot list git remotes").trim());
@@ -3855,7 +4212,9 @@ function gitWorkflowCommandPayload(result) {
3855
4212
  };
3856
4213
  }
3857
4214
 
3858
- async function handleGitWorkflowRequest(pathname, body = {}, cwd = options.cwd) {
4215
+ async function handleGitWorkflowRequest(pathname, body = {}, tabOrCwd = options.cwd) {
4216
+ const tab = tabOrCwd && typeof tabOrCwd === "object" ? tabOrCwd : null;
4217
+ const cwd = tab?.cwd || tabOrCwd || options.cwd;
3859
4218
  try {
3860
4219
  switch (pathname) {
3861
4220
  case "/api/git-workflow/message":
@@ -3904,12 +4263,8 @@ async function handleGitWorkflowRequest(pathname, body = {}, cwd = options.cwd)
3904
4263
  await getGitRoot(cwd);
3905
4264
  return gitWorkflowCommandPayload(await runGitWorkflowCommand(["add", "."], { cwd }));
3906
4265
  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;
4266
+ if (!tab) throw new Error("Git workflow branch worktree requires a Web UI tab");
4267
+ return { ok: true, data: await createGitWorkflowBranchWorktree(tab, body) };
3913
4268
  }
3914
4269
  case "/api/git-workflow/commit": {
3915
4270
  const variant = String(body.variant || "").trim();
@@ -5078,7 +5433,7 @@ function attachRpcToTab(tab, rpc) {
5078
5433
  });
5079
5434
  }
5080
5435
 
5081
- async function createTab({ id: requestedId, index, title, titleSource, conversationStarted, cwd, sessionFile } = {}) {
5436
+ async function createTab({ id: requestedId, index, title, titleSource, conversationStarted, cwd, sessionFile, gitWorkspace } = {}) {
5082
5437
  const tabIndex = Number.isInteger(index) && index > 0 ? index : nextTabIndex;
5083
5438
  nextTabIndex = Math.max(nextTabIndex, tabIndex + 1);
5084
5439
  const explicitTitle = String(title || "").trim();
@@ -5101,6 +5456,7 @@ async function createTab({ id: requestedId, index, title, titleSource, conversat
5101
5456
  cwd: tabCwd,
5102
5457
  createdAt,
5103
5458
  sessionFile: options.noSession ? undefined : normalizedRestoreString(sessionFile, 4096),
5459
+ gitWorkspace: gitWorkspace || null,
5104
5460
  lastState: null,
5105
5461
  pendingThinkingLevel: undefined,
5106
5462
  activity: createTabActivity(createdAt),
@@ -5147,6 +5503,7 @@ function tabMeta(tab) {
5147
5503
  conversationStarted: !!tab.conversationStarted,
5148
5504
  cwd: tab.cwd,
5149
5505
  sessionFile: tabRestorableSessionFile(tab),
5506
+ gitWorkspace: tab.gitWorkspace || null,
5150
5507
  pendingThinkingLevel: tab.pendingThinkingLevel || null,
5151
5508
  createdAt: tab.createdAt,
5152
5509
  startedAt: tab.rpc.startedAt,
@@ -5156,6 +5513,7 @@ function tabMeta(tab) {
5156
5513
  clientCount: tab.sseClients.size,
5157
5514
  pendingExtensionUiRequestCount: pendingExtensionUiRequests(tab).length,
5158
5515
  activity: tabActivitySnapshot(tab),
5516
+ appRunner: publicAppRunnerState(tab.appRunner),
5159
5517
  };
5160
5518
  }
5161
5519
 
@@ -7583,6 +7941,13 @@ const server = createServer(async (req, res) => {
7583
7941
  return;
7584
7942
  }
7585
7943
 
7944
+ if (url.pathname === "/api/app-runner/context" && req.method === "POST") {
7945
+ const body = await readJsonBody(req);
7946
+ const tab = getRequestedTab(req, url, body);
7947
+ sendJson(res, 200, { ok: true, data: await transferAppRunnerContext(tab, body) });
7948
+ return;
7949
+ }
7950
+
7586
7951
  if (url.pathname === "/api/app-runner/stop" && req.method === "POST") {
7587
7952
  const body = await readJsonBody(req);
7588
7953
  const tab = getRequestedTab(req, url, body);
@@ -7839,6 +8204,18 @@ const server = createServer(async (req, res) => {
7839
8204
  return;
7840
8205
  }
7841
8206
 
8207
+ if (url.pathname === "/api/queue/remove" && req.method === "POST") {
8208
+ const body = await readJsonBody(req);
8209
+ const tab = getRequestedTab(req, url, body);
8210
+ const data = await sendWebuiHelperCommand(tab, "queue-remove", {
8211
+ kind: body.kind || "followUp",
8212
+ index: body.index,
8213
+ message: body.message,
8214
+ });
8215
+ sendJson(res, 200, { ok: true, data });
8216
+ return;
8217
+ }
8218
+
7842
8219
  if (url.pathname === "/api/prompt" && req.method === "POST") {
7843
8220
  const body = await readJsonBody(req, { limitBytes: requestBodyLimitForPath(url.pathname) });
7844
8221
  const tab = getRequestedTab(req, url, body);
@@ -7895,6 +8272,50 @@ const server = createServer(async (req, res) => {
7895
8272
  return;
7896
8273
  }
7897
8274
 
8275
+ if (url.pathname === "/api/git-worktrees" && req.method === "GET") {
8276
+ const tab = getRequestedTab(req, url);
8277
+ try {
8278
+ sendJson(res, 200, { ok: true, data: await listGitWorktrees(tab.cwd) });
8279
+ } catch (error) {
8280
+ sendGitWorktreeFailure(res, error);
8281
+ }
8282
+ return;
8283
+ }
8284
+
8285
+ if (url.pathname === "/api/git-worktrees" && req.method === "POST") {
8286
+ const body = await readJsonBody(req);
8287
+ const tab = getRequestedTab(req, url, body);
8288
+ try {
8289
+ sendJson(res, 200, { ok: true, data: await createGitWorktreeTab(tab, body) });
8290
+ } catch (error) {
8291
+ sendGitWorktreeFailure(res, error);
8292
+ }
8293
+ return;
8294
+ }
8295
+
8296
+ if (url.pathname === "/api/git-worktrees/open" && req.method === "POST") {
8297
+ const body = await readJsonBody(req);
8298
+ const tab = getRequestedTab(req, url, body);
8299
+ try {
8300
+ sendJson(res, 200, { ok: true, data: await openExistingGitWorktreeTab(tab, body) });
8301
+ } catch (error) {
8302
+ sendGitWorktreeFailure(res, error);
8303
+ }
8304
+ return;
8305
+ }
8306
+
8307
+ if (url.pathname === "/api/git-worktrees" && req.method === "DELETE") {
8308
+ requireLocalhost(req, "Removing Git worktrees is only allowed from localhost");
8309
+ const body = await readJsonBody(req);
8310
+ const tab = getRequestedTab(req, url, body);
8311
+ try {
8312
+ sendJson(res, 200, { ok: true, data: await removeGitWorktreeForTab(tab, body) });
8313
+ } catch (error) {
8314
+ sendGitWorktreeFailure(res, error);
8315
+ }
8316
+ return;
8317
+ }
8318
+
7898
8319
  if (url.pathname === "/api/git-branches" && req.method === "GET") {
7899
8320
  const tab = getRequestedTab(req, url);
7900
8321
  try {
@@ -7919,7 +8340,7 @@ const server = createServer(async (req, res) => {
7919
8340
  if (url.pathname.startsWith("/api/git-workflow/")) {
7920
8341
  const body = req.method === "POST" ? await readJsonBody(req) : {};
7921
8342
  const tab = getRequestedTab(req, url, body);
7922
- const response = await handleGitWorkflowRequest(url.pathname, body, tab.cwd);
8343
+ const response = await handleGitWorkflowRequest(url.pathname, body, tab);
7923
8344
  if (response) {
7924
8345
  sendJson(res, 200, response);
7925
8346
  return;