@firstpick/pi-package-webui 0.7.1 → 0.7.3

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
@@ -74,6 +74,12 @@ import {
74
74
  pruneGitWorktrees,
75
75
  removeGitWorktree,
76
76
  } from "../lib/git-worktrees.mjs";
77
+ import { createGitLiveWatcher } from "../lib/git-live-watcher.mjs";
78
+ import {
79
+ gitMessageArtifactPairReadiness,
80
+ readStableGitMessageArtifactPair,
81
+ sameGitMessageArtifactPair,
82
+ } from "../lib/git-message-artifacts.mjs";
77
83
 
78
84
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
79
85
  const require = createRequire(import.meta.url);
@@ -106,6 +112,8 @@ const WEBUI_SUBAGENTS_STATUS_KEY = "webui-subagents";
106
112
  const WEBUI_SUBAGENTS_PAYLOAD_PREFIX = "PI_WEBUI_SUBAGENTS_V1 ";
107
113
  const WEBUI_SUBAGENT_RUN_LIMIT = 128;
108
114
  const WEBUI_SUBAGENT_AGENT_LIMIT = 256;
115
+ const WEBUI_SUBAGENT_GATE_LIMIT = 32;
116
+ const WEBUI_SUBAGENT_GATE_ATTEMPT_LIMIT = 100;
109
117
  const WEBUI_SUBAGENT_OUTPUT_LINE_LIMIT = 120;
110
118
  const WEBUI_SUBAGENT_OUTPUT_LINE_LENGTH = 1000;
111
119
  const PI_CODING_AGENT_PACKAGE = "@earendil-works/pi-coding-agent";
@@ -1482,13 +1490,13 @@ function latestEvents(limit = 40) {
1482
1490
  return eventHistory.slice(-Math.max(0, Math.min(EVENT_HISTORY_LIMIT, limit)));
1483
1491
  }
1484
1492
 
1485
- function runCommand(command, args, { cwd, timeoutMs = 2000, maxOutputLength = 20000 } = {}) {
1493
+ function runCommand(command, args, { cwd, timeoutMs = 2000, maxOutputLength = 20000, env = {} } = {}) {
1486
1494
  return new Promise((resolve) => {
1487
1495
  const child = spawn(command, args, {
1488
1496
  cwd,
1489
1497
  // LC_ALL=C keeps tool output in English so error classification works
1490
1498
  // regardless of locale.
1491
- env: { ...process.env, LC_ALL: "C" },
1499
+ env: { ...process.env, ...env, LC_ALL: "C" },
1492
1500
  stdio: ["ignore", "pipe", "pipe"],
1493
1501
  windowsHide: true,
1494
1502
  });
@@ -2096,6 +2104,23 @@ async function restoreGitWorkflowGenerationProfile(tab) {
2096
2104
  }
2097
2105
  }
2098
2106
 
2107
+ async function createGitWorkflowMessageGeneration(tab) {
2108
+ // Keep generation dispatch backward-compatible for tabs whose cwd has not
2109
+ // become a repository yet; the Guided Git flow itself still verifies Git
2110
+ // state at its staging/review boundaries.
2111
+ const root = await getGitRoot(tab.cwd).catch(() => path.resolve(tab.cwd));
2112
+ const cwd = gitWorkflowMessageCwd(root, tab.cwd);
2113
+ const paths = commitMessagePaths(cwd);
2114
+ return {
2115
+ id: randomUUID(),
2116
+ kind: "commit",
2117
+ root,
2118
+ cwd,
2119
+ createdAt: Date.now(),
2120
+ baseline: await readStableGitMessageArtifactPair(paths),
2121
+ };
2122
+ }
2123
+
2099
2124
  async function startGitWorkflowGeneration(tab, body = {}) {
2100
2125
  if (tab.gitWorkflowGenerationRestore) throw makeHttpError(409, "A guided Git generation request is already active in this tab");
2101
2126
  // Browser state is untrusted. When it claims an approved content token,
@@ -2103,6 +2128,8 @@ async function startGitWorkflowGeneration(tab, body = {}) {
2103
2128
  await assertExpectedStagedContentHash(tab, body);
2104
2129
  const preferences = await readGitWorkflowPreferences();
2105
2130
  if (!isGitWorkflowSetupComplete(preferences)) throw makeHttpError(409, "Run /git-workflow-setup or open Guided Git Setup before generating Git text");
2131
+ const kind = String(body.kind || "").trim();
2132
+ const message = gitWorkflowGenerationPrompt(kind, preferences);
2106
2133
 
2107
2134
  const state = await currentSessionState(tab);
2108
2135
  if (stateIsBusyForSettings(state)) throw makeHttpError(409, "Wait for the current agent run to finish before generating Git text");
@@ -2115,7 +2142,10 @@ async function startGitWorkflowGeneration(tab, body = {}) {
2115
2142
  }
2116
2143
 
2117
2144
  const restore = { model: state.model || null, thinkingLevel: state.thinkingLevel || "off" };
2145
+ const previousMessageGeneration = tab.gitWorkflowMessageGeneration || null;
2146
+ const messageGeneration = kind === "commit" ? await createGitWorkflowMessageGeneration(tab) : null;
2118
2147
  tab.gitWorkflowGenerationRestore = restore;
2148
+ if (messageGeneration) tab.gitWorkflowMessageGeneration = messageGeneration;
2119
2149
  try {
2120
2150
  if (gitWorkflowModelKey(state.model) !== gitWorkflowModelKey(selectedModel)) {
2121
2151
  const modelResponse = await tab.rpc.send({ type: "set_model", provider: selectedModel.provider, modelId: selectedModel.id });
@@ -2124,8 +2154,6 @@ async function startGitWorkflowGeneration(tab, body = {}) {
2124
2154
  const thinkingResponse = await setThinkingLevelForTab(tab, preferences.generation.thinkingLevel, { allowPending: false });
2125
2155
  if (thinkingResponse.success === false) throw new Error(thinkingResponse.error || `Failed to select thinking level ${preferences.generation.thinkingLevel}`);
2126
2156
 
2127
- const kind = String(body.kind || "").trim();
2128
- const message = gitWorkflowGenerationPrompt(kind, preferences);
2129
2157
  markTabWorking(tab);
2130
2158
  const response = await tab.rpc.send({ type: "prompt", message });
2131
2159
  if (response.success === false) throw new Error(response.error || "Guided Git generation prompt was rejected");
@@ -2133,6 +2161,7 @@ async function startGitWorkflowGeneration(tab, body = {}) {
2133
2161
  accepted: true,
2134
2162
  kind,
2135
2163
  message,
2164
+ generationId: messageGeneration?.id || "",
2136
2165
  generation: {
2137
2166
  provider: selectedModel.provider,
2138
2167
  modelId: selectedModel.id,
@@ -2140,6 +2169,9 @@ async function startGitWorkflowGeneration(tab, body = {}) {
2140
2169
  },
2141
2170
  };
2142
2171
  } catch (error) {
2172
+ if (messageGeneration && tab.gitWorkflowMessageGeneration?.id === messageGeneration.id) {
2173
+ tab.gitWorkflowMessageGeneration = previousMessageGeneration;
2174
+ }
2143
2175
  markTabIdle(tab);
2144
2176
  await restoreGitWorkflowGenerationProfile(tab);
2145
2177
  throw error;
@@ -2167,6 +2199,7 @@ async function readJsonFileIfExists(filePath) {
2167
2199
 
2168
2200
  const appRunnerCommandAvailability = new Map();
2169
2201
  let appRunnerPtyScriptAvailability = { available: false, expiresAt: 0 };
2202
+ let appRunnerNodePtyPromise = null;
2170
2203
 
2171
2204
  async function fileStatsIfExists(filePath) {
2172
2205
  try {
@@ -2226,6 +2259,40 @@ function appRunnerPtyDisabled() {
2226
2259
  return APP_RUNNER_PTY_DISABLED_VALUES.has(String(process.env.PI_WEBUI_APP_RUNNER_PTY || "").trim().toLowerCase());
2227
2260
  }
2228
2261
 
2262
+ async function appRunnerWindowsPty() {
2263
+ if (process.platform !== "win32" || appRunnerPtyDisabled()) return null;
2264
+ if (!appRunnerNodePtyPromise) {
2265
+ appRunnerNodePtyPromise = import("node-pty")
2266
+ .then((module) => module?.spawn ? module : module?.default?.spawn ? module.default : null)
2267
+ .catch(() => null);
2268
+ }
2269
+ return appRunnerNodePtyPromise;
2270
+ }
2271
+
2272
+ async function resolveWindowsAppRunnerExecutable(command, cwd) {
2273
+ const value = String(command || "").trim();
2274
+ if (process.platform !== "win32" || !value) return value;
2275
+ const hasDirectory = path.isAbsolute(value) || value.includes("/") || value.includes("\\");
2276
+ const bases = hasDirectory
2277
+ ? [path.isAbsolute(value) ? value : path.resolve(cwd, value)]
2278
+ : String(process.env.PATH || process.env.Path || "").split(path.delimiter).filter(Boolean).map((directory) => path.join(directory, value));
2279
+ const extensions = path.extname(value)
2280
+ ? [""]
2281
+ : String(process.env.PATHEXT || ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean).map((extension) => extension.toLowerCase()).concat("");
2282
+ for (const base of bases) {
2283
+ for (const extension of extensions) {
2284
+ const candidate = `${base}${extension}`;
2285
+ try {
2286
+ await access(candidate);
2287
+ return candidate;
2288
+ } catch {
2289
+ // Keep searching PATH/PATHEXT.
2290
+ }
2291
+ }
2292
+ }
2293
+ return value;
2294
+ }
2295
+
2229
2296
  async function appRunnerScriptPtyAvailable(cwd) {
2230
2297
  if (process.platform === "win32" || appRunnerPtyDisabled()) return false;
2231
2298
  const now = Date.now();
@@ -2287,6 +2354,19 @@ async function spawnAppRunnerChild(run) {
2287
2354
  windowsHide: true,
2288
2355
  detached: process.platform !== "win32",
2289
2356
  };
2357
+ const windowsPty = await appRunnerWindowsPty();
2358
+ if (windowsPty) {
2359
+ run.executionMode = "conpty";
2360
+ const command = await resolveWindowsAppRunnerExecutable(run.command, run.cwd);
2361
+ return windowsPty.spawn(command, run.args || [], {
2362
+ name: process.env.TERM || "xterm-256color",
2363
+ cols: Math.max(20, Number.parseInt(process.env.COLUMNS || "120", 10) || 120),
2364
+ rows: Math.max(5, Number.parseInt(process.env.LINES || "40", 10) || 40),
2365
+ cwd: run.cwd,
2366
+ env: process.env,
2367
+ useConpty: true,
2368
+ });
2369
+ }
2290
2370
  if (await appRunnerScriptPtyAvailable(run.cwd)) {
2291
2371
  run.executionMode = "pty";
2292
2372
  return spawn("script", [
@@ -3184,18 +3264,34 @@ function scheduleAppRunnerBroadcast(tab) {
3184
3264
  }, 120);
3185
3265
  }
3186
3266
 
3267
+ function appRunnerChildActive(run) {
3268
+ if (!run?.child || run.settled) return false;
3269
+ if (run.executionMode === "conpty") return true;
3270
+ return run.child.exitCode === null && run.child.signalCode === null;
3271
+ }
3272
+
3187
3273
  function terminateAppRunnerChild(run, signal = "SIGTERM") {
3188
- if (!run?.child || run.child.exitCode !== null || run.child.signalCode !== null) return false;
3274
+ if (!appRunnerChildActive(run)) return false;
3189
3275
  return terminateProcessTree(run.child, signal);
3190
3276
  }
3191
3277
 
3192
3278
  function appRunnerStdinWritable(run) {
3193
- const stdin = run?.child?.stdin;
3194
- return !!stdin && !stdin.destroyed && !stdin.writableEnded && run.stdinClosed !== true;
3279
+ if (!appRunnerChildActive(run) || run.stdinClosed === true) return false;
3280
+ if (run.executionMode === "conpty") return typeof run.child.write === "function";
3281
+ const stdin = run.child.stdin;
3282
+ return !!stdin && !stdin.destroyed && !stdin.writableEnded;
3195
3283
  }
3196
3284
 
3197
3285
  function interruptAppRunnerChild(run) {
3198
- if (!run?.child || run.child.exitCode !== null || run.child.signalCode !== null) return false;
3286
+ if (!appRunnerChildActive(run)) return false;
3287
+ if (run.executionMode === "conpty" && appRunnerStdinWritable(run)) {
3288
+ try {
3289
+ run.child.write("\x03");
3290
+ return true;
3291
+ } catch {
3292
+ // Fall back to process-tree termination below.
3293
+ }
3294
+ }
3199
3295
  // Writing ETX to a Windows pipe is data, not a console Ctrl+C event. Kill the
3200
3296
  // complete tree there so npm/bash wrappers cannot leave orphaned servers.
3201
3297
  if (process.platform === "win32") return terminateAppRunnerChild(run, "SIGKILL");
@@ -3220,6 +3316,14 @@ function finishAppRunner(tab, run, patch = {}) {
3220
3316
  run.signal = patch.signal;
3221
3317
  run.error = patch.error;
3222
3318
  run.status = patch.error ? "error" : patch.exitCode === 0 ? "done" : "failed";
3319
+ for (const disposable of run.ptyDisposables || []) {
3320
+ try {
3321
+ disposable?.dispose?.();
3322
+ } catch {
3323
+ // The PTY has already exited; listener cleanup is best effort.
3324
+ }
3325
+ }
3326
+ run.ptyDisposables = [];
3223
3327
  run.child = null;
3224
3328
  run.stdinClosed = true;
3225
3329
  run.stopping = false;
@@ -3241,19 +3345,26 @@ function normalizeAppRunnerInputText(value) {
3241
3345
  function sendAppRunnerInput(tab, value, { appendNewline = true, closeStdin = false } = {}) {
3242
3346
  const run = tab?.appRunner;
3243
3347
  if (!run || run.status !== "running") throw makeHttpError(409, "No app runner is running in this tab");
3244
- const stdin = run.child?.stdin;
3245
- if (!stdin || stdin.destroyed || stdin.writableEnded || run.stdinClosed === true) throw makeHttpError(409, "App runner stdin is closed");
3348
+ if (!appRunnerStdinWritable(run)) throw makeHttpError(409, "App runner stdin is closed");
3246
3349
  const text = normalizeAppRunnerInputText(value);
3247
- const chunk = `${text}${appendNewline === false ? "" : "\n"}`;
3350
+ const newline = run.executionMode === "conpty" && process.platform === "win32" ? "\r" : "\n";
3351
+ const chunk = `${text}${appendNewline === false ? "" : newline}`;
3248
3352
  if (!chunk && !closeStdin) throw makeHttpError(400, "App runner input is empty");
3249
3353
  let buffered = false;
3250
3354
  try {
3251
- if (closeStdin) {
3252
- if (chunk) stdin.end(chunk, "utf8");
3253
- else stdin.end();
3254
- run.stdinClosed = true;
3355
+ if (run.executionMode === "conpty") {
3356
+ if (chunk) run.child.write(chunk);
3357
+ else if (closeStdin) run.child.write("\x04");
3358
+ if (closeStdin) run.stdinClosed = true;
3255
3359
  } else {
3256
- buffered = stdin.write(chunk, "utf8") === false;
3360
+ const stdin = run.child.stdin;
3361
+ if (closeStdin) {
3362
+ if (chunk) stdin.end(chunk, "utf8");
3363
+ else stdin.end();
3364
+ run.stdinClosed = true;
3365
+ } else {
3366
+ buffered = stdin.write(chunk, "utf8") === false;
3367
+ }
3257
3368
  }
3258
3369
  } catch (error) {
3259
3370
  run.stdinClosed = true;
@@ -3299,22 +3410,29 @@ async function startAppRunner(tab, runnerId) {
3299
3410
  run.pid = child.pid;
3300
3411
  tab.appRunner = run;
3301
3412
 
3302
- child.stdin?.on("error", (error) => {
3303
- run.stdinClosed = true;
3304
- run.stdinError = sanitizeError(error);
3305
- if (run.status === "running") {
3306
- appendAppRunnerLine(run, `# stdin error: ${run.stdinError}`);
3307
- scheduleAppRunnerBroadcast(tab);
3308
- }
3309
- });
3310
- child.stdin?.on("close", () => {
3311
- run.stdinClosed = true;
3312
- if (run.status === "running") scheduleAppRunnerBroadcast(tab);
3313
- });
3314
- child.stdout.on("data", (chunk) => appendAppRunnerChunk(tab, run, chunk, "stdout"));
3315
- child.stderr.on("data", (chunk) => appendAppRunnerChunk(tab, run, chunk, "stderr"));
3316
- child.on("error", (error) => finishAppRunner(tab, run, { error: sanitizeError(error) }));
3317
- child.on("exit", (exitCode, signal) => finishAppRunner(tab, run, { exitCode, signal }));
3413
+ if (run.executionMode === "conpty") {
3414
+ run.ptyDisposables = [
3415
+ child.onData((chunk) => appendAppRunnerChunk(tab, run, chunk, "stdout")),
3416
+ child.onExit(({ exitCode, signal }) => finishAppRunner(tab, run, { exitCode, signal })),
3417
+ ];
3418
+ } else {
3419
+ child.stdin?.on("error", (error) => {
3420
+ run.stdinClosed = true;
3421
+ run.stdinError = sanitizeError(error);
3422
+ if (run.status === "running") {
3423
+ appendAppRunnerLine(run, `# stdin error: ${run.stdinError}`);
3424
+ scheduleAppRunnerBroadcast(tab);
3425
+ }
3426
+ });
3427
+ child.stdin?.on("close", () => {
3428
+ run.stdinClosed = true;
3429
+ if (run.status === "running") scheduleAppRunnerBroadcast(tab);
3430
+ });
3431
+ child.stdout.on("data", (chunk) => appendAppRunnerChunk(tab, run, chunk, "stdout"));
3432
+ child.stderr.on("data", (chunk) => appendAppRunnerChunk(tab, run, chunk, "stderr"));
3433
+ child.on("error", (error) => finishAppRunner(tab, run, { error: sanitizeError(error) }));
3434
+ child.on("exit", (exitCode, signal) => finishAppRunner(tab, run, { exitCode, signal }));
3435
+ }
3318
3436
 
3319
3437
  recordEvent({ type: "webui_app_runner_start", tabId: tab.id, tabTitle: tab.title, command: run.displayCommand, cwd: run.cwd, pid: run.pid });
3320
3438
  broadcastAppRunnerState(tab);
@@ -3325,7 +3443,9 @@ function stopAppRunnerForTab(tab, reason = "stop requested", { force = false } =
3325
3443
  const run = tab?.appRunner;
3326
3444
  if (!run || run.status !== "running") return false;
3327
3445
  run.stopping = true;
3328
- const action = process.platform === "win32" ? "terminating Windows process tree" : `sending ${force ? "SIGKILL" : "Ctrl+C"}`;
3446
+ const action = run.executionMode === "conpty" && !force
3447
+ ? "sending Ctrl+C"
3448
+ : process.platform === "win32" ? "terminating Windows process tree" : `sending ${force ? "SIGKILL" : "Ctrl+C"}`;
3329
3449
  appendAppRunnerLine(run, `# ${reason}; ${action}`);
3330
3450
  if (force) terminateAppRunnerChild(run, "SIGKILL");
3331
3451
  else interruptAppRunnerChild(run);
@@ -4503,7 +4623,14 @@ async function getGitRoot(cwd) {
4503
4623
  }
4504
4624
 
4505
4625
  async function runGitReadCommandDetailed(root, args, { timeoutMs = GIT_CHANGES_COMMAND_TIMEOUT_MS, maxOutputLength = GIT_CHANGES_DIFF_MAX_OUTPUT } = {}) {
4506
- const result = await runCommand("git", args, { cwd: root, timeoutMs, maxOutputLength });
4626
+ const result = await runCommand("git", args, {
4627
+ cwd: root,
4628
+ timeoutMs,
4629
+ maxOutputLength,
4630
+ // Prevent read-only status/diff commands from refreshing the index and
4631
+ // feeding their own metadata writes back into the live Git watcher.
4632
+ env: { GIT_OPTIONAL_LOCKS: "0" },
4633
+ });
4507
4634
  if (result.exitCode === 0 && !result.timedOut && !result.error) {
4508
4635
  return { output: result.stdout, truncated: result.stdoutTruncated === true, capBytes: maxOutputLength };
4509
4636
  }
@@ -4907,6 +5034,144 @@ async function readGitChanges(cwd) {
4907
5034
  };
4908
5035
  }
4909
5036
 
5037
+ const GIT_PANEL_HISTORY_LIMIT = 30;
5038
+ const GIT_PANEL_MAX_OUTPUT = 240_000;
5039
+
5040
+ function parseGitNumstatZ(text = "") {
5041
+ const stats = new Map();
5042
+ for (const record of String(text || "").split("\0")) {
5043
+ if (!record) continue;
5044
+ const firstTab = record.indexOf("\t");
5045
+ const secondTab = firstTab < 0 ? -1 : record.indexOf("\t", firstTab + 1);
5046
+ if (firstTab < 0 || secondTab < 0) continue;
5047
+ const additionsText = record.slice(0, firstTab);
5048
+ const deletionsText = record.slice(firstTab + 1, secondTab);
5049
+ const filePath = normalizeGitStatusPath(record.slice(secondTab + 1));
5050
+ if (!filePath) continue;
5051
+ const binary = additionsText === "-" || deletionsText === "-";
5052
+ stats.set(filePath, {
5053
+ additions: binary ? 0 : Number.parseInt(additionsText || "0", 10) || 0,
5054
+ deletions: binary ? 0 : Number.parseInt(deletionsText || "0", 10) || 0,
5055
+ binary,
5056
+ });
5057
+ }
5058
+ return stats;
5059
+ }
5060
+
5061
+ function gitPanelPathStats(entry, stagedStats, unstagedStats) {
5062
+ const paths = [entry.path, entry.oldPath].map(normalizeGitStatusPath).filter(Boolean);
5063
+ const aggregate = (stats) => {
5064
+ const value = { additions: 0, deletions: 0, binary: false };
5065
+ for (const filePath of paths) {
5066
+ const current = stats.get(filePath);
5067
+ if (!current) continue;
5068
+ value.additions += Number(current.additions || 0) || 0;
5069
+ value.deletions += Number(current.deletions || 0) || 0;
5070
+ value.binary ||= current.binary === true;
5071
+ }
5072
+ return value;
5073
+ };
5074
+ const staged = aggregate(stagedStats);
5075
+ const unstaged = aggregate(unstagedStats);
5076
+ return {
5077
+ additions: staged.additions + unstaged.additions,
5078
+ deletions: staged.deletions + unstaged.deletions,
5079
+ binary: staged.binary || unstaged.binary,
5080
+ stagedAdditions: staged.additions,
5081
+ stagedDeletions: staged.deletions,
5082
+ stagedBinary: staged.binary,
5083
+ unstagedAdditions: unstaged.additions,
5084
+ unstagedDeletions: unstaged.deletions,
5085
+ unstagedBinary: unstaged.binary,
5086
+ };
5087
+ }
5088
+
5089
+ function gitPanelChangeEntry(entry, stagedStats, unstagedStats) {
5090
+ const x = entry.x || " ";
5091
+ const y = entry.y || " ";
5092
+ const untracked = x === "?" && y === "?";
5093
+ const conflicted = x === "U" || y === "U" || (x === "A" && y === "A") || (x === "D" && y === "D");
5094
+ return {
5095
+ path: normalizeGitStatusPath(entry.path),
5096
+ oldPath: normalizeGitStatusPath(entry.oldPath || ""),
5097
+ status: `${x}${y}`,
5098
+ staged: !untracked && x !== " " && x !== "?",
5099
+ unstaged: !untracked && y !== " " && y !== "?",
5100
+ untracked,
5101
+ conflicted,
5102
+ ...gitPanelPathStats(entry, stagedStats, unstagedStats),
5103
+ };
5104
+ }
5105
+
5106
+ function parseGitPanelHistory(text = "") {
5107
+ const fields = String(text || "").split("\0").filter(Boolean);
5108
+ const history = [];
5109
+ for (let index = 0; index + 4 < fields.length && history.length < GIT_PANEL_HISTORY_LIMIT; index += 5) {
5110
+ const [hash, shortHash, author, authoredAt, subject] = fields.slice(index, index + 5);
5111
+ if (!hash) continue;
5112
+ history.push({ hash, shortHash, author, authoredAt, subject });
5113
+ }
5114
+ return history;
5115
+ }
5116
+
5117
+ async function readGitPanel(cwd) {
5118
+ const root = await getGitRoot(cwd);
5119
+ const historyPromise = runGitReadCommand(root, [
5120
+ "log", `-n${GIT_PANEL_HISTORY_LIMIT}`, "-z", "--date=iso-strict", "--format=%H%x00%h%x00%an%x00%aI%x00%s",
5121
+ ], { maxOutputLength: GIT_PANEL_MAX_OUTPUT }).catch(() => "");
5122
+ const [statusText, porcelainStatusText, stagedNumstatText, unstagedNumstatText, historyText] = await Promise.all([
5123
+ runGitReadCommand(root, ["status", "--porcelain=v1", "-z", "--untracked-files=all"], { maxOutputLength: GIT_PANEL_MAX_OUTPUT }),
5124
+ runGitReadCommand(root, ["status", "--porcelain=2", "--branch", "--untracked-files=all"], { maxOutputLength: GIT_PANEL_MAX_OUTPUT }),
5125
+ runGitReadCommand(root, ["diff", "--cached", "--numstat", "-z", "--no-renames", "--"], { maxOutputLength: GIT_PANEL_MAX_OUTPUT }),
5126
+ runGitReadCommand(root, ["diff", "--numstat", "-z", "--no-renames", "--"], { maxOutputLength: GIT_PANEL_MAX_OUTPUT }),
5127
+ historyPromise,
5128
+ ]);
5129
+ const stagedStats = parseGitNumstatZ(stagedNumstatText);
5130
+ const unstagedStats = parseGitNumstatZ(unstagedNumstatText);
5131
+ const changes = parseGitPorcelainZEntries(statusText)
5132
+ .map((entry) => gitPanelChangeEntry(entry, stagedStats, unstagedStats))
5133
+ .filter((entry) => entry.path);
5134
+ return {
5135
+ cwd,
5136
+ root,
5137
+ branch: gitBranchFromPorcelainStatus(porcelainStatusText),
5138
+ generatedAt: new Date().toISOString(),
5139
+ summary: summarizeGitPorcelainStatus(porcelainStatusText),
5140
+ changes,
5141
+ history: parseGitPanelHistory(historyText),
5142
+ };
5143
+ }
5144
+
5145
+ async function readGitCommit(cwd, requestedHash) {
5146
+ const hash = String(requestedHash || "").trim().toLowerCase();
5147
+ if (!/^[a-f0-9]{40}([a-f0-9]{24})?$/.test(hash)) throw makeHttpError(400, "A full Git commit hash is required");
5148
+ const root = await getGitRoot(cwd);
5149
+ const verified = (await runGitReadCommand(root, ["rev-parse", "--verify", `${hash}^{commit}`], { maxOutputLength: 1000 })).trim();
5150
+ if (verified.toLowerCase() !== hash) throw makeHttpError(404, "Git commit not found in this repository");
5151
+ const [metaText, diff] = await Promise.all([
5152
+ runGitReadCommand(root, ["show", "-s", "-z", "--date=iso-strict", "--format=%H%x00%h%x00%an%x00%aI%x00%s", hash], { maxOutputLength: 20_000 }),
5153
+ runGitReadCommandDetailed(root, ["show", "--format=", "--no-ext-diff", "--no-color", "--find-renames", "--unified=0", "--src-prefix=a/", "--dst-prefix=b/", hash]),
5154
+ ]);
5155
+ const [commit] = parseGitPanelHistory(metaText);
5156
+ return {
5157
+ root,
5158
+ branch: "",
5159
+ generatedAt: new Date().toISOString(),
5160
+ commit: commit || { hash, shortHash: hash.slice(0, 12), author: "", authoredAt: "", subject: "" },
5161
+ summary: { staged: 0, unstaged: 0, untracked: 0, conflicted: 0, ahead: 0, behind: 0 },
5162
+ remote: { upstream: "", ahead: 0, behind: 0, diverged: false, canPull: false },
5163
+ sections: [{
5164
+ key: "commit",
5165
+ label: `Commit ${commit?.shortHash || hash.slice(0, 12)}`,
5166
+ command: `git show --unified=0 ${hash}`,
5167
+ diff: diff.output.trimEnd(),
5168
+ truncated: diff.truncated,
5169
+ capBytes: diff.capBytes,
5170
+ }],
5171
+ untracked: [],
5172
+ };
5173
+ }
5174
+
4910
5175
  const GIT_LOCK_RETRY_ATTEMPTS = 3;
4911
5176
  const GIT_LOCK_RETRY_DELAY_MS = 250;
4912
5177
  const GIT_FETCH_TIMEOUT_MS = 2 * 60 * 1000;
@@ -5415,6 +5680,23 @@ async function unstageGitFile(cwd, body = {}) {
5415
5680
  return payload;
5416
5681
  }
5417
5682
 
5683
+ async function stageAllGitChanges(cwd) {
5684
+ const root = await getGitRoot(cwd);
5685
+ const payload = await gitAddAllPayload(root);
5686
+ if (payload.data) payload.data.root = root;
5687
+ return payload;
5688
+ }
5689
+
5690
+ async function unstageAllGitChanges(cwd) {
5691
+ const root = await getGitRoot(cwd);
5692
+ let payload = await runGuardedGitMutation(["restore", "--staged", "--", "."], { cwd: root, label: "git restore --staged -- ." });
5693
+ if (!payload.ok && /HEAD/.test(payload.error || "")) {
5694
+ payload = await runGuardedGitMutation(["rm", "--cached", "-r", "--", "."], { cwd: root, label: "git rm --cached -r -- ." });
5695
+ }
5696
+ if (payload.data) payload.data.root = root;
5697
+ return payload;
5698
+ }
5699
+
5418
5700
  async function discardGitFile(cwd, body = {}) {
5419
5701
  requireConfirmed(body, "Discarding file changes is destructive and");
5420
5702
  const root = await getGitRoot(cwd);
@@ -5682,35 +5964,73 @@ async function readGitWorkflowBranchName(cwd) {
5682
5964
  }
5683
5965
  }
5684
5966
 
5685
- async function readGitWorkflowMessages(cwd) {
5967
+ const GIT_WORKFLOW_MESSAGE_PAIR_SETTLE_MS = 80;
5968
+
5969
+ function gitWorkflowMessagePendingPayload(root, messageCwd, paths, generationId, reason, details = {}) {
5970
+ const shortFile = gitWorkflowMessageFileMeta(root, messageCwd, paths.shortPath);
5971
+ const longFile = gitWorkflowMessageFileMeta(root, messageCwd, paths.longPath);
5972
+ return {
5973
+ ready: false,
5974
+ generationId,
5975
+ reason,
5976
+ root,
5977
+ cwd: messageCwd,
5978
+ shortPath: paths.shortPath,
5979
+ longPath: paths.longPath,
5980
+ shortRelativePath: shortFile.relativePath,
5981
+ longRelativePath: longFile.relativePath,
5982
+ shortRepoRelativePath: shortFile.repoRelativePath,
5983
+ longRepoRelativePath: longFile.repoRelativePath,
5984
+ ...details,
5985
+ };
5986
+ }
5987
+
5988
+ async function readGitWorkflowMessages(cwd, { generationId = "", generation = null } = {}) {
5686
5989
  const root = await getGitRoot(cwd);
5687
5990
  const messageCwd = gitWorkflowMessageCwd(root, cwd);
5688
- const { shortPath, longPath } = commitMessagePaths(messageCwd);
5991
+ const paths = commitMessagePaths(messageCwd);
5992
+ if (generationId && (!generation || generation.id !== generationId || generation.kind !== "commit" || generation.cwd !== messageCwd)) {
5993
+ return gitWorkflowMessagePendingPayload(root, messageCwd, paths, generationId, "This commit-message generation is no longer active. Regenerate the message files.", { expired: true });
5994
+ }
5689
5995
  try {
5690
- const [shortText, longText, shortStat, longStat] = await Promise.all([
5691
- readFile(shortPath, "utf8"),
5692
- readFile(longPath, "utf8"),
5693
- stat(shortPath),
5694
- stat(longPath),
5695
- ]);
5696
- const shortFile = gitWorkflowMessageFileMeta(root, messageCwd, shortPath);
5697
- const longFile = gitWorkflowMessageFileMeta(root, messageCwd, longPath);
5996
+ let pair = await readStableGitMessageArtifactPair(paths);
5997
+ if (generationId) {
5998
+ const readiness = gitMessageArtifactPairReadiness(generation.baseline, pair);
5999
+ if (!readiness.ready) return gitWorkflowMessagePendingPayload(root, messageCwd, paths, generationId, readiness.reason, readiness);
6000
+ await new Promise((resolve) => setTimeout(resolve, GIT_WORKFLOW_MESSAGE_PAIR_SETTLE_MS));
6001
+ const settledPair = await readStableGitMessageArtifactPair(paths);
6002
+ if (!sameGitMessageArtifactPair(pair, settledPair)) {
6003
+ return gitWorkflowMessagePendingPayload(root, messageCwd, paths, generationId, "Generated commit message files are still settling.");
6004
+ }
6005
+ const settledReadiness = gitMessageArtifactPairReadiness(generation.baseline, settledPair);
6006
+ if (!settledReadiness.ready) return gitWorkflowMessagePendingPayload(root, messageCwd, paths, generationId, settledReadiness.reason, settledReadiness);
6007
+ pair = settledPair;
6008
+ }
6009
+ if (!pair.short.exists || !pair.long.exists) {
6010
+ throw new Error(`Missing ${!pair.short.exists ? paths.shortPath : paths.longPath}`);
6011
+ }
6012
+ const shortFile = gitWorkflowMessageFileMeta(root, messageCwd, paths.shortPath);
6013
+ const longFile = gitWorkflowMessageFileMeta(root, messageCwd, paths.longPath);
5698
6014
  return {
6015
+ ready: true,
6016
+ generationId,
5699
6017
  root,
5700
6018
  cwd: messageCwd,
5701
- shortPath,
5702
- longPath,
6019
+ shortPath: paths.shortPath,
6020
+ longPath: paths.longPath,
5703
6021
  shortRelativePath: shortFile.relativePath,
5704
6022
  longRelativePath: longFile.relativePath,
5705
6023
  shortRepoRelativePath: shortFile.repoRelativePath,
5706
6024
  longRepoRelativePath: longFile.repoRelativePath,
5707
- short: shortText.trimEnd(),
5708
- long: longText.trimEnd(),
5709
- shortMtimeMs: shortStat.mtimeMs,
5710
- longMtimeMs: longStat.mtimeMs,
6025
+ short: pair.short.text.trimEnd(),
6026
+ long: pair.long.text.trimEnd(),
6027
+ shortMtimeMs: Number(BigInt(pair.short.mtimeNs) / 1_000_000n),
6028
+ longMtimeMs: Number(BigInt(pair.long.mtimeNs) / 1_000_000n),
6029
+ shortSha256: pair.short.sha256,
6030
+ longSha256: pair.long.sha256,
5711
6031
  };
5712
6032
  } catch (error) {
5713
- throw new Error(`Missing generated commit message files in ${path.join(messageCwd, "dev", "COMMIT")}. Run /git-staged-msg first. ${sanitizeError(error)}`);
6033
+ throw new Error(`Missing or unstable generated commit message files in ${path.join(messageCwd, "dev", "COMMIT")}. Run /git-staged-msg first. ${sanitizeError(error)}`);
5714
6034
  }
5715
6035
  }
5716
6036
 
@@ -6454,8 +6774,11 @@ async function handleGitWorkflowRequest(pathname, body = {}, tabOrCwd = options.
6454
6774
  case "/api/git-workflow/staged-content":
6455
6775
  if (!tab) throw new Error("Staged-content lookup requires a Web UI tab");
6456
6776
  return { ok: true, data: await stagedContentHashForTab(tab) };
6457
- case "/api/git-workflow/message":
6458
- return { ok: true, data: await readGitWorkflowMessages(cwd) };
6777
+ case "/api/git-workflow/message": {
6778
+ const generationId = String(body.generationId || "").trim();
6779
+ if (generationId && !tab) throw new Error("Fresh commit-message lookup requires a Web UI tab");
6780
+ return { ok: true, data: await readGitWorkflowMessages(cwd, { generationId, generation: tab?.gitWorkflowMessageGeneration || null }) };
6781
+ }
6459
6782
  case "/api/git-workflow/default-commit-message":
6460
6783
  return { ok: true, data: await readGitWorkflowDefaultCommitMessage(cwd) };
6461
6784
  case "/api/git-workflow/branch-name":
@@ -6780,11 +7103,21 @@ function stripDataUrlPrefix(data) {
6780
7103
  return comma === -1 ? text : text.slice(comma + 1);
6781
7104
  }
6782
7105
 
6783
- function decodeAttachmentData(data) {
7106
+ function decodeCanonicalBase64(data, label) {
6784
7107
  const base64 = stripDataUrlPrefix(data).replace(/\s+/g, "");
6785
- if (!base64) throw new Error("attachment data is required");
6786
- if (!/^[A-Za-z0-9+/]*={0,2}$/.test(base64)) throw new Error("attachment data must be base64 encoded");
6787
- return Buffer.from(base64, "base64");
7108
+ if (!base64) throw makeHttpError(400, `${label} data is required`);
7109
+ if (base64.length % 4 !== 0 || !/^[A-Za-z0-9+/]+={0,2}$/.test(base64)) {
7110
+ throw makeHttpError(400, `${label} data must be canonical base64`);
7111
+ }
7112
+ const buffer = Buffer.from(base64, "base64");
7113
+ if (buffer.length === 0 || buffer.toString("base64") !== base64) {
7114
+ throw makeHttpError(400, `${label} data must be canonical base64`);
7115
+ }
7116
+ return { base64, buffer };
7117
+ }
7118
+
7119
+ function decodeAttachmentData(data) {
7120
+ return decodeCanonicalBase64(data, "attachment").buffer;
6788
7121
  }
6789
7122
 
6790
7123
  async function saveUploadedAttachments(body) {
@@ -6828,13 +7161,10 @@ function normalizeRpcImages(value) {
6828
7161
  let totalBytes = 0;
6829
7162
  for (const [index, image] of value.entries()) {
6830
7163
  const mimeType = normalizeMimeType(image?.mimeType);
6831
- if (!RPC_IMAGE_MIME_TYPES.has(mimeType)) throw new Error(`image ${index + 1} has unsupported MIME type ${mimeType}`);
6832
- const data = stripDataUrlPrefix(image?.data).replace(/\s+/g, "");
6833
- if (!data) throw new Error(`image ${index + 1} data is required`);
6834
- if (!/^[A-Za-z0-9+/]*={0,2}$/.test(data)) throw new Error(`image ${index + 1} data must be base64 encoded`);
6835
- const approxBytes = Math.floor((data.length * 3) / 4);
6836
- if (approxBytes > INLINE_IMAGE_MAX_BYTES) throw new Error(`image ${index + 1} exceeds ${formatBytes(INLINE_IMAGE_MAX_BYTES)} inline limit`);
6837
- totalBytes += approxBytes;
7164
+ if (!RPC_IMAGE_MIME_TYPES.has(mimeType)) throw makeHttpError(400, `image ${index + 1} has unsupported MIME type ${mimeType}`);
7165
+ const { base64: data, buffer } = decodeCanonicalBase64(image?.data, `image ${index + 1}`);
7166
+ if (buffer.length > INLINE_IMAGE_MAX_BYTES) throw new Error(`image ${index + 1} exceeds ${formatBytes(INLINE_IMAGE_MAX_BYTES)} inline limit`);
7167
+ totalBytes += buffer.length;
6838
7168
  if (totalBytes > INLINE_IMAGE_TOTAL_MAX_BYTES) throw new Error(`inline images exceed ${formatBytes(INLINE_IMAGE_TOTAL_MAX_BYTES)} total`);
6839
7169
  images.push({ type: "image", data, mimeType });
6840
7170
  }
@@ -7403,6 +7733,8 @@ function normalizeWebuiSubagentPayload(value) {
7403
7733
  index: Number.isInteger(rawAgent.index) ? rawAgent.index : agents.length,
7404
7734
  currentTool: normalizeWebuiSubagentText(rawAgent.currentTool, 120) || undefined,
7405
7735
  activityState: normalizeWebuiSubagentText(rawAgent.activityState, 80) || undefined,
7736
+ model: normalizeWebuiSubagentText(rawAgent.model, 240) || undefined,
7737
+ thinking: normalizeWebuiSubagentText(rawAgent.thinking, 40) || undefined,
7406
7738
  nested: rawAgent.nested === true,
7407
7739
  });
7408
7740
  }
@@ -7416,12 +7748,56 @@ function normalizeWebuiSubagentPayload(value) {
7416
7748
  agents: agents.sort((a, b) => a.index - b.index || a.name.localeCompare(b.name)),
7417
7749
  });
7418
7750
  }
7751
+ const gates = [];
7752
+ for (const rawGate of Array.isArray(value.gates) ? value.gates.slice(-WEBUI_SUBAGENT_GATE_LIMIT) : []) {
7753
+ if (!rawGate || typeof rawGate !== "object") continue;
7754
+ const id = normalizeWebuiSubagentText(rawGate.id, 160);
7755
+ if (!id) continue;
7756
+ const attempts = [];
7757
+ for (const rawAttempt of Array.isArray(rawGate.attempts) ? rawGate.attempts.slice(-WEBUI_SUBAGENT_GATE_ATTEMPT_LIMIT) : []) {
7758
+ if (!rawAttempt || typeof rawAttempt !== "object") continue;
7759
+ const attemptId = normalizeWebuiSubagentText(rawAttempt.id || `${id}:${attempts.length}`, 240);
7760
+ const agent = normalizeWebuiSubagentText(rawAttempt.agent, 160) || "subagent";
7761
+ attempts.push({
7762
+ id: attemptId,
7763
+ taskIndex: Number.isInteger(rawAttempt.taskIndex) ? rawAttempt.taskIndex : attempts.length,
7764
+ attempt: Number.isInteger(rawAttempt.attempt) ? Math.max(1, rawAttempt.attempt) : 1,
7765
+ maxAttempts: Number.isInteger(rawAttempt.maxAttempts) ? Math.max(1, rawAttempt.maxAttempts) : 1,
7766
+ agent,
7767
+ label: normalizeWebuiSubagentText(rawAttempt.label, 200) || undefined,
7768
+ phase: normalizeWebuiSubagentText(rawAttempt.phase, 120) || undefined,
7769
+ retrySafety: rawAttempt.retrySafety === "read-only" ? "read-only" : "may-write",
7770
+ runId: normalizeWebuiSubagentText(rawAttempt.runId, 160) || undefined,
7771
+ retryOf: normalizeWebuiSubagentText(rawAttempt.retryOf, 160) || undefined,
7772
+ model: normalizeWebuiSubagentText(rawAttempt.model, 240) || undefined,
7773
+ provider: normalizeWebuiSubagentText(rawAttempt.provider, 80) || undefined,
7774
+ status: ["launching", "running", "succeeded", "failed", "not-qualifying", "cancelled"].includes(rawAttempt.status) ? rawAttempt.status : "failed",
7775
+ failureKind: normalizeWebuiSubagentText(rawAttempt.failureKind, 80) || undefined,
7776
+ error: normalizeWebuiSubagentText(rawAttempt.error, 1000) || undefined,
7777
+ startedAt: Number.isFinite(rawAttempt.startedAt) ? rawAttempt.startedAt : undefined,
7778
+ endedAt: Number.isFinite(rawAttempt.endedAt) ? rawAttempt.endedAt : undefined,
7779
+ });
7780
+ }
7781
+ gates.push({
7782
+ version: 1,
7783
+ id,
7784
+ status: ["running", "satisfied", "failed", "cancelled"].includes(rawGate.status) ? rawGate.status : "failed",
7785
+ requiredSuccesses: Number.isInteger(rawGate.requiredSuccesses) ? Math.max(1, rawGate.requiredSuccesses) : 1,
7786
+ qualifyingSuccesses: Number.isInteger(rawGate.qualifyingSuccesses) ? Math.max(0, rawGate.qualifyingSuccesses) : 0,
7787
+ requireDistinctProviders: rawGate.requireDistinctProviders === true,
7788
+ startedAt: Number.isFinite(rawGate.startedAt) ? rawGate.startedAt : Date.now(),
7789
+ updatedAt: Number.isFinite(rawGate.updatedAt) ? rawGate.updatedAt : Date.now(),
7790
+ endedAt: Number.isFinite(rawGate.endedAt) ? rawGate.endedAt : undefined,
7791
+ attempts,
7792
+ });
7793
+ }
7419
7794
  return {
7420
7795
  version: 1,
7421
7796
  available: value.available === true,
7422
7797
  updatedAt: Number.isFinite(value.updatedAt) ? value.updatedAt : Date.now(),
7423
7798
  receivedAt: Date.now(),
7424
7799
  runs: runs.sort((a, b) => a.startedAt - b.startedAt || a.id.localeCompare(b.id)),
7800
+ gates: gates.sort((a, b) => a.startedAt - b.startedAt || a.id.localeCompare(b.id)),
7425
7801
  };
7426
7802
  }
7427
7803
 
@@ -8026,6 +8402,7 @@ function attachRpcToTab(tab, rpc) {
8026
8402
  let scopedEvent = eventForTabClients(tab, event);
8027
8403
  if (event?.type === "pi_process_exit" || event?.type === "pi_process_error") {
8028
8404
  tab.gitWorkflowGenerationRestore = null;
8405
+ tab.gitWorkflowMessageGeneration = null;
8029
8406
  clearPendingExtensionUiRequests(tab);
8030
8407
  clearExtensionStatuses(tab);
8031
8408
  clearExtensionWidgets(tab);
@@ -8072,6 +8449,7 @@ async function createTab({ id: requestedId, index, title, titleSource, conversat
8072
8449
  lastState: null,
8073
8450
  pendingThinkingLevel: undefined,
8074
8451
  gitWorkflowGenerationRestore: null,
8452
+ gitWorkflowMessageGeneration: null,
8075
8453
  activity: createTabActivity(createdAt),
8076
8454
  pendingExtensionUiRequests: new Map(),
8077
8455
  extensionStatuses: new Map(),
@@ -8097,6 +8475,7 @@ async function createTab({ id: requestedId, index, title, titleSource, conversat
8097
8475
  } catch (error) {
8098
8476
  if (!tab.rpc.isRunning()) {
8099
8477
  tab.rpcUnsubscribe?.();
8478
+ gitLiveWatcher.unsubscribe(id);
8100
8479
  tabs.delete(id);
8101
8480
  throw new Error(`Pi RPC process failed while starting ${tabTitle}: ${sanitizeError(error)}`);
8102
8481
  }
@@ -8142,8 +8521,9 @@ function listTabs() {
8142
8521
  function webuiSubagentsData() {
8143
8522
  const sortedTabs = [...tabs.values()].sort((a, b) => a.index - b.index || a.title.localeCompare(b.title));
8144
8523
  const tabSummaries = sortedTabs.map((tab) => {
8145
- const status = tab.webuiSubagents || { version: 1, available: false, updatedAt: null, receivedAt: null, runs: [] };
8524
+ const status = tab.webuiSubagents || { version: 1, available: false, updatedAt: null, receivedAt: null, runs: [], gates: [] };
8146
8525
  const runs = Array.isArray(status.runs) ? status.runs : [];
8526
+ const gates = Array.isArray(status.gates) ? status.gates : [];
8147
8527
  return {
8148
8528
  tabId: tab.id,
8149
8529
  tabIndex: tab.index,
@@ -8156,7 +8536,9 @@ function webuiSubagentsData() {
8156
8536
  updatedAt: status.updatedAt || null,
8157
8537
  receivedAt: status.receivedAt || null,
8158
8538
  runs,
8539
+ gates,
8159
8540
  agentCount: runs.reduce((count, run) => count + run.agents.length, 0),
8541
+ gateCount: gates.length,
8160
8542
  };
8161
8543
  });
8162
8544
  return {
@@ -8165,6 +8547,7 @@ function webuiSubagentsData() {
8165
8547
  available: tabSummaries.some((tab) => tab.available),
8166
8548
  totalRuns: tabSummaries.reduce((count, tab) => count + tab.runs.length, 0),
8167
8549
  totalAgents: tabSummaries.reduce((count, tab) => count + tab.agentCount, 0),
8550
+ totalGates: tabSummaries.reduce((count, tab) => count + tab.gateCount, 0),
8168
8551
  tabs: tabSummaries,
8169
8552
  };
8170
8553
  }
@@ -8274,6 +8657,8 @@ function normalizeWebuiSubagentOutput(value, selection) {
8274
8657
  turnCount: Number.isFinite(rawAgent.turnCount) ? rawAgent.turnCount : undefined,
8275
8658
  toolCount: Number.isFinite(rawAgent.toolCount) ? rawAgent.toolCount : undefined,
8276
8659
  tokens: Number.isFinite(rawAgent.tokens) ? rawAgent.tokens : undefined,
8660
+ model: normalizeWebuiSubagentText(rawAgent.model, 240) || selection.agent.model || undefined,
8661
+ thinking: normalizeWebuiSubagentText(rawAgent.thinking, 40) || selection.agent.thinking || undefined,
8277
8662
  recentTools,
8278
8663
  recentOutput,
8279
8664
  transcript,
@@ -8850,6 +9235,22 @@ function broadcastServerEvent(event) {
8850
9235
  for (const client of clients) sendSse(client, event);
8851
9236
  }
8852
9237
 
9238
+ const gitLiveWatcher = createGitLiveWatcher({
9239
+ onChange: ({ root, changedAt }) => {
9240
+ broadcastServerEvent({ type: "webui_git_changed", root, changedAt });
9241
+ },
9242
+ onError: ({ root, error }) => {
9243
+ const message = sanitizeError(error);
9244
+ recordEvent({ type: "webui_git_watch_error", root, error: message });
9245
+ console.warn(`Git live watcher disabled for ${root}: ${message}`);
9246
+ },
9247
+ });
9248
+
9249
+ function trackGitRepositoryForTab(tab, root) {
9250
+ if (tab?.id && root) gitLiveWatcher.subscribe(tab.id, root);
9251
+ return root;
9252
+ }
9253
+
8853
9254
  function renameTab(tab, title, { source = "explicit", maxLength, unique = source === "auto" } = {}) {
8854
9255
  if (!tab) return false;
8855
9256
  const rawTitle = maxLength ? truncateTabTitle(title, maxLength) : String(title || "").replace(/\s+/g, " ").trim();
@@ -8903,6 +9304,7 @@ async function updateTabCwd(id, cwd) {
8903
9304
  const piArgs = await buildPiArgsForTab(tab.index, tab.title, nextCwd);
8904
9305
  if (sessionFile && !options.noSession) piArgs.push("--session", sessionFile);
8905
9306
  const piCommand = await resolvePiCommand(piArgs);
9307
+ gitLiveWatcher.unsubscribe(tab.id);
8906
9308
  const restartingEvent = { type: "webui_tab_restarting", tabId: tab.id, tabTitle: tab.title, cwd: nextCwd, sessionFile };
8907
9309
  recordEvent(restartingEvent);
8908
9310
  for (const client of tab.sseClients) {
@@ -11074,6 +11476,7 @@ async function closeTab(id) {
11074
11476
  if (stateResult.ok) restorableState = stateResult.data;
11075
11477
  }
11076
11478
  rememberClosedRestorableTab(tab, restorableState);
11479
+ gitLiveWatcher.unsubscribe(tab.id);
11077
11480
 
11078
11481
  const closingEvent = { type: "webui_tab_closing", tabId: tab.id, tabTitle: tab.title };
11079
11482
  recordEvent(closingEvent);
@@ -11092,6 +11495,7 @@ async function closeTab(id) {
11092
11495
 
11093
11496
  async function discardTab(tab) {
11094
11497
  if (!tab || !tabs.has(tab.id)) return;
11498
+ gitLiveWatcher.unsubscribe(tab.id);
11095
11499
  tab.rpcUnsubscribe?.();
11096
11500
  rejectTabBashQueue(tab, new Error("Pi recovery tab initialization failed"));
11097
11501
  stopAppRunnerForTab(tab, "recovery initialization failed", { force: true });
@@ -12423,6 +12827,40 @@ const server = createServer(async (req, res) => {
12423
12827
  return;
12424
12828
  }
12425
12829
 
12830
+ if (url.pathname === "/api/git-root" && req.method === "GET") {
12831
+ const tab = getRequestedTab(req, url);
12832
+ try {
12833
+ const root = trackGitRepositoryForTab(tab, await getGitRoot(tab.cwd));
12834
+ sendJson(res, 200, { ok: true, data: { cwd: tab.cwd, root } });
12835
+ } catch (error) {
12836
+ sendJson(res, 200, { ok: false, error: sanitizeError(error) });
12837
+ }
12838
+ return;
12839
+ }
12840
+
12841
+ if (url.pathname === "/api/git-panel" && req.method === "GET") {
12842
+ const tab = getRequestedTab(req, url);
12843
+ try {
12844
+ const data = await readGitPanel(tab.cwd);
12845
+ trackGitRepositoryForTab(tab, data.root);
12846
+ sendJson(res, 200, { ok: true, data });
12847
+ } catch (error) {
12848
+ sendJson(res, 200, { ok: false, error: sanitizeError(error) });
12849
+ }
12850
+ return;
12851
+ }
12852
+
12853
+ if (url.pathname === "/api/git-commit" && req.method === "GET") {
12854
+ const tab = getRequestedTab(req, url);
12855
+ try {
12856
+ sendJson(res, 200, { ok: true, data: await readGitCommit(tab.cwd, url.searchParams.get("hash") || "") });
12857
+ } catch (error) {
12858
+ const statusCode = Number(error?.statusCode || error?.status || 200) || 200;
12859
+ sendJson(res, statusCode, { ok: false, error: sanitizeError(error) });
12860
+ }
12861
+ return;
12862
+ }
12863
+
12426
12864
  if (url.pathname === "/api/git-changes/untracked-file" && req.method === "GET") {
12427
12865
  const tab = getRequestedTab(req, url);
12428
12866
  try {
@@ -12544,6 +12982,8 @@ const server = createServer(async (req, res) => {
12544
12982
  "/api/git-changes/integrate": (cwd, body) => integrateGitUpstream(cwd, body),
12545
12983
  "/api/git-changes/stage-file": (cwd, body) => stageGitFile(cwd, body),
12546
12984
  "/api/git-changes/unstage-file": (cwd, body) => unstageGitFile(cwd, body),
12985
+ "/api/git-changes/stage-all": (cwd) => stageAllGitChanges(cwd),
12986
+ "/api/git-changes/unstage-all": (cwd) => unstageAllGitChanges(cwd),
12547
12987
  "/api/git-changes/discard-file": (cwd, body) => discardGitFile(cwd, body),
12548
12988
  "/api/git-changes/delete-untracked": (cwd, body) => deleteGitUntrackedFile(cwd, body),
12549
12989
  "/api/git-operation/continue": (cwd, body) => gitOperationAction(cwd, "continue", body),
@@ -12589,7 +13029,7 @@ const server = createServer(async (req, res) => {
12589
13029
  sendJson(res, 405, { ok: false, error: `${url.pathname} requires ${requiredMethod}` });
12590
13030
  return;
12591
13031
  }
12592
- const body = mutatingWorkflow ? await readJsonBody(req) : {};
13032
+ const body = mutatingWorkflow ? await readJsonBody(req) : { generationId: url.searchParams.get("generationId") || "" };
12593
13033
  const tab = getRequestedTab(req, url, body);
12594
13034
  if (mutatingWorkflow) ensureNaturalConversationRouteAllowed(tab, "git workflow actions are blocked");
12595
13035
  const response = await handleGitWorkflowRequest(url.pathname, body, tab);
@@ -12721,6 +13161,7 @@ server.listen(options.port, currentHost, () => {
12721
13161
 
12722
13162
  function shutdown(signal) {
12723
13163
  console.log(`\n${signal}: shutting down Pi Web UI...`);
13164
+ gitLiveWatcher.closeAll();
12724
13165
  const forceCloseTimer = setTimeout(() => {
12725
13166
  server.closeAllConnections?.();
12726
13167
  }, NETWORK_REBIND_FORCE_CLOSE_MS);