@firstpick/pi-package-webui 0.7.2 → 0.7.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/README.md +38 -25
  2. package/bin/pi-webui.mjs +469 -106
  3. package/index.ts +10 -1
  4. package/lib/git-live-watcher.mjs +135 -0
  5. package/lib/git-message-artifacts.mjs +103 -0
  6. package/lib/git-workflow-preferences.mjs +10 -3
  7. package/lib/process-tree.mjs +3 -1
  8. package/lib/webui-output-mode.mjs +97 -0
  9. package/package.json +7 -6
  10. package/public/app.js +1170 -97
  11. package/public/fast-output-live.mjs +179 -0
  12. package/public/index.html +31 -5
  13. package/public/service-worker.js +2 -1
  14. package/public/styles.css +474 -12
  15. package/tests/app-runner-windows-conpty-harness.test.mjs +140 -0
  16. package/tests/danger-button-contrast-static.test.mjs +32 -0
  17. package/tests/fast-mode-client-static.test.mjs +121 -0
  18. package/tests/fast-mode-output-work.test.mjs +69 -0
  19. package/tests/fast-mode-sse-harness.test.mjs +204 -0
  20. package/tests/fast-output-live.test.mjs +106 -0
  21. package/tests/fixtures/fake-pi.mjs +59 -0
  22. package/tests/fixtures/fast-mode-output-events.mjs +50 -0
  23. package/tests/footer-middle-truncation.test.mjs +118 -0
  24. package/tests/git-live-watcher.test.mjs +93 -0
  25. package/tests/git-message-artifacts.test.mjs +59 -0
  26. package/tests/git-panel-live-updates-static.test.mjs +54 -0
  27. package/tests/git-panel-render-stability-static.test.mjs +1 -1
  28. package/tests/git-workflow-preferences.test.mjs +8 -2
  29. package/tests/guided-git-message-reliability-static.test.mjs +38 -0
  30. package/tests/http-endpoints-harness.test.mjs +61 -5
  31. package/tests/image-payload-hardening-harness.test.mjs +115 -0
  32. package/tests/mobile-static.test.mjs +79 -20
  33. package/tests/pi-footer-calibration-static.test.mjs +55 -0
  34. package/tests/remote-auth-settings-harness.test.mjs +1 -1
  35. package/tests/runtime-error-visibility.test.mjs +63 -0
  36. package/tests/side-panel-context-menu-static.test.mjs +74 -0
  37. package/tests/webui-output-mode.test.mjs +73 -0
package/bin/pi-webui.mjs CHANGED
@@ -48,6 +48,16 @@ import {
48
48
  writeGitWorkflowPreferences,
49
49
  writeWebuiSettings,
50
50
  } from "../lib/git-workflow-preferences.mjs";
51
+ import {
52
+ encodeBrowserSseEvent,
53
+ isOutputModeSemanticBarrier,
54
+ negotiateOutputMode,
55
+ normalizeOutputMode,
56
+ OUTPUT_MODE_COMPACT_V1,
57
+ OUTPUT_MODE_NORMAL,
58
+ OUTPUT_MODE_PROTOCOL_VERSION,
59
+ resolveOutputModeDefault,
60
+ } from "../lib/webui-output-mode.mjs";
51
61
  import {
52
62
  evaluateDispatchTrustGuards,
53
63
  guardsForNativeCommand,
@@ -74,6 +84,12 @@ import {
74
84
  pruneGitWorktrees,
75
85
  removeGitWorktree,
76
86
  } from "../lib/git-worktrees.mjs";
87
+ import { createGitLiveWatcher } from "../lib/git-live-watcher.mjs";
88
+ import {
89
+ gitMessageArtifactPairReadiness,
90
+ readStableGitMessageArtifactPair,
91
+ sameGitMessageArtifactPair,
92
+ } from "../lib/git-message-artifacts.mjs";
77
93
 
78
94
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
79
95
  const require = createRequire(import.meta.url);
@@ -296,7 +312,13 @@ function isTruthyEnv(value) {
296
312
 
297
313
  function isSourceCheckout(root) {
298
314
  const normalized = String(root || "").replace(/\\/g, "/");
299
- return normalized.includes("/npm-packages/") && !normalized.includes("/node_modules/");
315
+ if (normalized.includes("/node_modules/")) return false;
316
+ try {
317
+ const gitMarker = statSync(path.join(root, "..", ".git"));
318
+ return gitMarker.isDirectory() || gitMarker.isFile();
319
+ } catch {
320
+ return false;
321
+ }
300
322
  }
301
323
 
302
324
  const NATIVE_SLASH_COMMANDS = nativeSlashCommandEntries(nativeParityMatrix);
@@ -359,6 +381,7 @@ Options:
359
381
  --name <name> Initial Web UI tab display name
360
382
  --remote-auth Enable startup PIN authentication for non-local clients
361
383
  --no-remote-auth Disable startup PIN authentication
384
+ --output-mode <mode> Web UI output default: normal or compact-v1
362
385
  -h, --help Show this help
363
386
  -v, --version Print version
364
387
 
@@ -386,6 +409,14 @@ function takeValue(argv, index, flag) {
386
409
  return value;
387
410
  }
388
411
 
412
+ function requiredOutputMode(value, source) {
413
+ const mode = String(value || "").trim();
414
+ if (![OUTPUT_MODE_NORMAL, OUTPUT_MODE_COMPACT_V1].includes(mode)) {
415
+ throw new Error(`${source} must be one of: ${OUTPUT_MODE_NORMAL}, ${OUTPUT_MODE_COMPACT_V1}`);
416
+ }
417
+ return mode;
418
+ }
419
+
389
420
  function parseArgs(argv) {
390
421
  const options = {
391
422
  host: process.env.PI_WEBUI_HOST || DEFAULT_HOST,
@@ -398,6 +429,8 @@ function parseArgs(argv) {
398
429
  name: undefined,
399
430
  remoteAuth: isTruthyEnv(process.env.PI_WEBUI_REMOTE_AUTH),
400
431
  remoteAuthExplicit: process.env.PI_WEBUI_REMOTE_AUTH !== undefined,
432
+ outputMode: undefined,
433
+ envOutputMode: process.env.PI_WEBUI_OUTPUT_MODE === undefined ? undefined : requiredOutputMode(process.env.PI_WEBUI_OUTPUT_MODE, "PI_WEBUI_OUTPUT_MODE"),
401
434
  piArgs: [],
402
435
  help: false,
403
436
  version: false,
@@ -452,6 +485,11 @@ function parseArgs(argv) {
452
485
  i++;
453
486
  continue;
454
487
  }
488
+ if (arg === "--output-mode") {
489
+ options.outputMode = requiredOutputMode(takeValue(argv, i, arg), "--output-mode");
490
+ i++;
491
+ continue;
492
+ }
455
493
  if (arg === "--remote-auth") {
456
494
  options.remoteAuth = true;
457
495
  options.remoteAuthExplicit = true;
@@ -1089,8 +1127,12 @@ function sendRemoteAuthRequired(req, res, url) {
1089
1127
  sendJson(res, 401, { ok: false, error: "Remote PIN required", remoteAuthRequired: true }, { "www-authenticate": "PiRemotePin" });
1090
1128
  }
1091
1129
 
1092
- function sendSse(res, event) {
1093
- res.write(`data: ${JSON.stringify(event)}\n\n`);
1130
+ function sendSse(client, event) {
1131
+ const res = client?.res || client;
1132
+ const payload = encodeBrowserSseEvent(event, { outputMode: client?.activeMode || OUTPUT_MODE_NORMAL });
1133
+ if (payload === undefined) return false;
1134
+ res.write(`data: ${payload}\n\n`);
1135
+ return true;
1094
1136
  }
1095
1137
 
1096
1138
  function rpcSuccess(command, data = {}) {
@@ -1475,8 +1517,33 @@ function statusEventSummary(event) {
1475
1517
  return summary;
1476
1518
  }
1477
1519
 
1520
+ function deltaHistorySummary(event) {
1521
+ const update = event?.assistantMessageEvent;
1522
+ if (event?.type !== "message_update" || !update || typeof update !== "object" || !["text_delta", "thinking_delta", "toolcall_delta"].includes(update.type) || typeof update.delta !== "string") return null;
1523
+ return {
1524
+ type: "message_update",
1525
+ firstTimestamp: new Date().toISOString(),
1526
+ lastTimestamp: new Date().toISOString(),
1527
+ tabId: event.tabId,
1528
+ updateType: update.type,
1529
+ contentIndex: update.contentIndex ?? event.contentIndex ?? null,
1530
+ deltaCount: 1,
1531
+ deltaChars: update.delta.length,
1532
+ deltaUtf8Bytes: Buffer.byteLength(update.delta),
1533
+ };
1534
+ }
1535
+
1478
1536
  function recordEvent(event) {
1479
- eventHistory.push(statusEventSummary(event));
1537
+ const delta = deltaHistorySummary(event);
1538
+ const previous = eventHistory.at(-1);
1539
+ if (delta && previous?.type === delta.type && previous.tabId === delta.tabId && previous.updateType === delta.updateType && previous.contentIndex === delta.contentIndex && Number.isInteger(previous.deltaCount)) {
1540
+ previous.lastTimestamp = delta.lastTimestamp;
1541
+ previous.deltaCount += delta.deltaCount;
1542
+ previous.deltaChars += delta.deltaChars;
1543
+ previous.deltaUtf8Bytes += delta.deltaUtf8Bytes;
1544
+ } else {
1545
+ eventHistory.push(delta || statusEventSummary(event));
1546
+ }
1480
1547
  if (eventHistory.length > EVENT_HISTORY_LIMIT) eventHistory.splice(0, eventHistory.length - EVENT_HISTORY_LIMIT);
1481
1548
  }
1482
1549
 
@@ -1484,13 +1551,13 @@ function latestEvents(limit = 40) {
1484
1551
  return eventHistory.slice(-Math.max(0, Math.min(EVENT_HISTORY_LIMIT, limit)));
1485
1552
  }
1486
1553
 
1487
- function runCommand(command, args, { cwd, timeoutMs = 2000, maxOutputLength = 20000 } = {}) {
1554
+ function runCommand(command, args, { cwd, timeoutMs = 2000, maxOutputLength = 20000, env = {} } = {}) {
1488
1555
  return new Promise((resolve) => {
1489
1556
  const child = spawn(command, args, {
1490
1557
  cwd,
1491
1558
  // LC_ALL=C keeps tool output in English so error classification works
1492
1559
  // regardless of locale.
1493
- env: { ...process.env, LC_ALL: "C" },
1560
+ env: { ...process.env, ...env, LC_ALL: "C" },
1494
1561
  stdio: ["ignore", "pipe", "pipe"],
1495
1562
  windowsHide: true,
1496
1563
  });
@@ -2098,6 +2165,23 @@ async function restoreGitWorkflowGenerationProfile(tab) {
2098
2165
  }
2099
2166
  }
2100
2167
 
2168
+ async function createGitWorkflowMessageGeneration(tab) {
2169
+ // Keep generation dispatch backward-compatible for tabs whose cwd has not
2170
+ // become a repository yet; the Guided Git flow itself still verifies Git
2171
+ // state at its staging/review boundaries.
2172
+ const root = await getGitRoot(tab.cwd).catch(() => path.resolve(tab.cwd));
2173
+ const cwd = gitWorkflowMessageCwd(root, tab.cwd);
2174
+ const paths = commitMessagePaths(cwd);
2175
+ return {
2176
+ id: randomUUID(),
2177
+ kind: "commit",
2178
+ root,
2179
+ cwd,
2180
+ createdAt: Date.now(),
2181
+ baseline: await readStableGitMessageArtifactPair(paths),
2182
+ };
2183
+ }
2184
+
2101
2185
  async function startGitWorkflowGeneration(tab, body = {}) {
2102
2186
  if (tab.gitWorkflowGenerationRestore) throw makeHttpError(409, "A guided Git generation request is already active in this tab");
2103
2187
  // Browser state is untrusted. When it claims an approved content token,
@@ -2105,6 +2189,8 @@ async function startGitWorkflowGeneration(tab, body = {}) {
2105
2189
  await assertExpectedStagedContentHash(tab, body);
2106
2190
  const preferences = await readGitWorkflowPreferences();
2107
2191
  if (!isGitWorkflowSetupComplete(preferences)) throw makeHttpError(409, "Run /git-workflow-setup or open Guided Git Setup before generating Git text");
2192
+ const kind = String(body.kind || "").trim();
2193
+ const message = gitWorkflowGenerationPrompt(kind, preferences);
2108
2194
 
2109
2195
  const state = await currentSessionState(tab);
2110
2196
  if (stateIsBusyForSettings(state)) throw makeHttpError(409, "Wait for the current agent run to finish before generating Git text");
@@ -2117,7 +2203,10 @@ async function startGitWorkflowGeneration(tab, body = {}) {
2117
2203
  }
2118
2204
 
2119
2205
  const restore = { model: state.model || null, thinkingLevel: state.thinkingLevel || "off" };
2206
+ const previousMessageGeneration = tab.gitWorkflowMessageGeneration || null;
2207
+ const messageGeneration = kind === "commit" ? await createGitWorkflowMessageGeneration(tab) : null;
2120
2208
  tab.gitWorkflowGenerationRestore = restore;
2209
+ if (messageGeneration) tab.gitWorkflowMessageGeneration = messageGeneration;
2121
2210
  try {
2122
2211
  if (gitWorkflowModelKey(state.model) !== gitWorkflowModelKey(selectedModel)) {
2123
2212
  const modelResponse = await tab.rpc.send({ type: "set_model", provider: selectedModel.provider, modelId: selectedModel.id });
@@ -2126,8 +2215,6 @@ async function startGitWorkflowGeneration(tab, body = {}) {
2126
2215
  const thinkingResponse = await setThinkingLevelForTab(tab, preferences.generation.thinkingLevel, { allowPending: false });
2127
2216
  if (thinkingResponse.success === false) throw new Error(thinkingResponse.error || `Failed to select thinking level ${preferences.generation.thinkingLevel}`);
2128
2217
 
2129
- const kind = String(body.kind || "").trim();
2130
- const message = gitWorkflowGenerationPrompt(kind, preferences);
2131
2218
  markTabWorking(tab);
2132
2219
  const response = await tab.rpc.send({ type: "prompt", message });
2133
2220
  if (response.success === false) throw new Error(response.error || "Guided Git generation prompt was rejected");
@@ -2135,6 +2222,7 @@ async function startGitWorkflowGeneration(tab, body = {}) {
2135
2222
  accepted: true,
2136
2223
  kind,
2137
2224
  message,
2225
+ generationId: messageGeneration?.id || "",
2138
2226
  generation: {
2139
2227
  provider: selectedModel.provider,
2140
2228
  modelId: selectedModel.id,
@@ -2142,6 +2230,9 @@ async function startGitWorkflowGeneration(tab, body = {}) {
2142
2230
  },
2143
2231
  };
2144
2232
  } catch (error) {
2233
+ if (messageGeneration && tab.gitWorkflowMessageGeneration?.id === messageGeneration.id) {
2234
+ tab.gitWorkflowMessageGeneration = previousMessageGeneration;
2235
+ }
2145
2236
  markTabIdle(tab);
2146
2237
  await restoreGitWorkflowGenerationProfile(tab);
2147
2238
  throw error;
@@ -2169,6 +2260,7 @@ async function readJsonFileIfExists(filePath) {
2169
2260
 
2170
2261
  const appRunnerCommandAvailability = new Map();
2171
2262
  let appRunnerPtyScriptAvailability = { available: false, expiresAt: 0 };
2263
+ let appRunnerNodePtyPromise = null;
2172
2264
 
2173
2265
  async function fileStatsIfExists(filePath) {
2174
2266
  try {
@@ -2228,6 +2320,40 @@ function appRunnerPtyDisabled() {
2228
2320
  return APP_RUNNER_PTY_DISABLED_VALUES.has(String(process.env.PI_WEBUI_APP_RUNNER_PTY || "").trim().toLowerCase());
2229
2321
  }
2230
2322
 
2323
+ async function appRunnerWindowsPty() {
2324
+ if (process.platform !== "win32" || appRunnerPtyDisabled()) return null;
2325
+ if (!appRunnerNodePtyPromise) {
2326
+ appRunnerNodePtyPromise = import("node-pty")
2327
+ .then((module) => module?.spawn ? module : module?.default?.spawn ? module.default : null)
2328
+ .catch(() => null);
2329
+ }
2330
+ return appRunnerNodePtyPromise;
2331
+ }
2332
+
2333
+ async function resolveWindowsAppRunnerExecutable(command, cwd) {
2334
+ const value = String(command || "").trim();
2335
+ if (process.platform !== "win32" || !value) return value;
2336
+ const hasDirectory = path.isAbsolute(value) || value.includes("/") || value.includes("\\");
2337
+ const bases = hasDirectory
2338
+ ? [path.isAbsolute(value) ? value : path.resolve(cwd, value)]
2339
+ : String(process.env.PATH || process.env.Path || "").split(path.delimiter).filter(Boolean).map((directory) => path.join(directory, value));
2340
+ const extensions = path.extname(value)
2341
+ ? [""]
2342
+ : String(process.env.PATHEXT || ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean).map((extension) => extension.toLowerCase()).concat("");
2343
+ for (const base of bases) {
2344
+ for (const extension of extensions) {
2345
+ const candidate = `${base}${extension}`;
2346
+ try {
2347
+ await access(candidate);
2348
+ return candidate;
2349
+ } catch {
2350
+ // Keep searching PATH/PATHEXT.
2351
+ }
2352
+ }
2353
+ }
2354
+ return value;
2355
+ }
2356
+
2231
2357
  async function appRunnerScriptPtyAvailable(cwd) {
2232
2358
  if (process.platform === "win32" || appRunnerPtyDisabled()) return false;
2233
2359
  const now = Date.now();
@@ -2289,6 +2415,19 @@ async function spawnAppRunnerChild(run) {
2289
2415
  windowsHide: true,
2290
2416
  detached: process.platform !== "win32",
2291
2417
  };
2418
+ const windowsPty = await appRunnerWindowsPty();
2419
+ if (windowsPty) {
2420
+ run.executionMode = "conpty";
2421
+ const command = await resolveWindowsAppRunnerExecutable(run.command, run.cwd);
2422
+ return windowsPty.spawn(command, run.args || [], {
2423
+ name: process.env.TERM || "xterm-256color",
2424
+ cols: Math.max(20, Number.parseInt(process.env.COLUMNS || "120", 10) || 120),
2425
+ rows: Math.max(5, Number.parseInt(process.env.LINES || "40", 10) || 40),
2426
+ cwd: run.cwd,
2427
+ env: process.env,
2428
+ useConpty: true,
2429
+ });
2430
+ }
2292
2431
  if (await appRunnerScriptPtyAvailable(run.cwd)) {
2293
2432
  run.executionMode = "pty";
2294
2433
  return spawn("script", [
@@ -3186,18 +3325,34 @@ function scheduleAppRunnerBroadcast(tab) {
3186
3325
  }, 120);
3187
3326
  }
3188
3327
 
3328
+ function appRunnerChildActive(run) {
3329
+ if (!run?.child || run.settled) return false;
3330
+ if (run.executionMode === "conpty") return true;
3331
+ return run.child.exitCode === null && run.child.signalCode === null;
3332
+ }
3333
+
3189
3334
  function terminateAppRunnerChild(run, signal = "SIGTERM") {
3190
- if (!run?.child || run.child.exitCode !== null || run.child.signalCode !== null) return false;
3335
+ if (!appRunnerChildActive(run)) return false;
3191
3336
  return terminateProcessTree(run.child, signal);
3192
3337
  }
3193
3338
 
3194
3339
  function appRunnerStdinWritable(run) {
3195
- const stdin = run?.child?.stdin;
3196
- return !!stdin && !stdin.destroyed && !stdin.writableEnded && run.stdinClosed !== true;
3340
+ if (!appRunnerChildActive(run) || run.stdinClosed === true) return false;
3341
+ if (run.executionMode === "conpty") return typeof run.child.write === "function";
3342
+ const stdin = run.child.stdin;
3343
+ return !!stdin && !stdin.destroyed && !stdin.writableEnded;
3197
3344
  }
3198
3345
 
3199
3346
  function interruptAppRunnerChild(run) {
3200
- if (!run?.child || run.child.exitCode !== null || run.child.signalCode !== null) return false;
3347
+ if (!appRunnerChildActive(run)) return false;
3348
+ if (run.executionMode === "conpty" && appRunnerStdinWritable(run)) {
3349
+ try {
3350
+ run.child.write("\x03");
3351
+ return true;
3352
+ } catch {
3353
+ // Fall back to process-tree termination below.
3354
+ }
3355
+ }
3201
3356
  // Writing ETX to a Windows pipe is data, not a console Ctrl+C event. Kill the
3202
3357
  // complete tree there so npm/bash wrappers cannot leave orphaned servers.
3203
3358
  if (process.platform === "win32") return terminateAppRunnerChild(run, "SIGKILL");
@@ -3222,6 +3377,14 @@ function finishAppRunner(tab, run, patch = {}) {
3222
3377
  run.signal = patch.signal;
3223
3378
  run.error = patch.error;
3224
3379
  run.status = patch.error ? "error" : patch.exitCode === 0 ? "done" : "failed";
3380
+ for (const disposable of run.ptyDisposables || []) {
3381
+ try {
3382
+ disposable?.dispose?.();
3383
+ } catch {
3384
+ // The PTY has already exited; listener cleanup is best effort.
3385
+ }
3386
+ }
3387
+ run.ptyDisposables = [];
3225
3388
  run.child = null;
3226
3389
  run.stdinClosed = true;
3227
3390
  run.stopping = false;
@@ -3243,19 +3406,26 @@ function normalizeAppRunnerInputText(value) {
3243
3406
  function sendAppRunnerInput(tab, value, { appendNewline = true, closeStdin = false } = {}) {
3244
3407
  const run = tab?.appRunner;
3245
3408
  if (!run || run.status !== "running") throw makeHttpError(409, "No app runner is running in this tab");
3246
- const stdin = run.child?.stdin;
3247
- if (!stdin || stdin.destroyed || stdin.writableEnded || run.stdinClosed === true) throw makeHttpError(409, "App runner stdin is closed");
3409
+ if (!appRunnerStdinWritable(run)) throw makeHttpError(409, "App runner stdin is closed");
3248
3410
  const text = normalizeAppRunnerInputText(value);
3249
- const chunk = `${text}${appendNewline === false ? "" : "\n"}`;
3411
+ const newline = run.executionMode === "conpty" && process.platform === "win32" ? "\r" : "\n";
3412
+ const chunk = `${text}${appendNewline === false ? "" : newline}`;
3250
3413
  if (!chunk && !closeStdin) throw makeHttpError(400, "App runner input is empty");
3251
3414
  let buffered = false;
3252
3415
  try {
3253
- if (closeStdin) {
3254
- if (chunk) stdin.end(chunk, "utf8");
3255
- else stdin.end();
3256
- run.stdinClosed = true;
3416
+ if (run.executionMode === "conpty") {
3417
+ if (chunk) run.child.write(chunk);
3418
+ else if (closeStdin) run.child.write("\x04");
3419
+ if (closeStdin) run.stdinClosed = true;
3257
3420
  } else {
3258
- buffered = stdin.write(chunk, "utf8") === false;
3421
+ const stdin = run.child.stdin;
3422
+ if (closeStdin) {
3423
+ if (chunk) stdin.end(chunk, "utf8");
3424
+ else stdin.end();
3425
+ run.stdinClosed = true;
3426
+ } else {
3427
+ buffered = stdin.write(chunk, "utf8") === false;
3428
+ }
3259
3429
  }
3260
3430
  } catch (error) {
3261
3431
  run.stdinClosed = true;
@@ -3301,22 +3471,29 @@ async function startAppRunner(tab, runnerId) {
3301
3471
  run.pid = child.pid;
3302
3472
  tab.appRunner = run;
3303
3473
 
3304
- child.stdin?.on("error", (error) => {
3305
- run.stdinClosed = true;
3306
- run.stdinError = sanitizeError(error);
3307
- if (run.status === "running") {
3308
- appendAppRunnerLine(run, `# stdin error: ${run.stdinError}`);
3309
- scheduleAppRunnerBroadcast(tab);
3310
- }
3311
- });
3312
- child.stdin?.on("close", () => {
3313
- run.stdinClosed = true;
3314
- if (run.status === "running") scheduleAppRunnerBroadcast(tab);
3315
- });
3316
- child.stdout.on("data", (chunk) => appendAppRunnerChunk(tab, run, chunk, "stdout"));
3317
- child.stderr.on("data", (chunk) => appendAppRunnerChunk(tab, run, chunk, "stderr"));
3318
- child.on("error", (error) => finishAppRunner(tab, run, { error: sanitizeError(error) }));
3319
- child.on("exit", (exitCode, signal) => finishAppRunner(tab, run, { exitCode, signal }));
3474
+ if (run.executionMode === "conpty") {
3475
+ run.ptyDisposables = [
3476
+ child.onData((chunk) => appendAppRunnerChunk(tab, run, chunk, "stdout")),
3477
+ child.onExit(({ exitCode, signal }) => finishAppRunner(tab, run, { exitCode, signal })),
3478
+ ];
3479
+ } else {
3480
+ child.stdin?.on("error", (error) => {
3481
+ run.stdinClosed = true;
3482
+ run.stdinError = sanitizeError(error);
3483
+ if (run.status === "running") {
3484
+ appendAppRunnerLine(run, `# stdin error: ${run.stdinError}`);
3485
+ scheduleAppRunnerBroadcast(tab);
3486
+ }
3487
+ });
3488
+ child.stdin?.on("close", () => {
3489
+ run.stdinClosed = true;
3490
+ if (run.status === "running") scheduleAppRunnerBroadcast(tab);
3491
+ });
3492
+ child.stdout.on("data", (chunk) => appendAppRunnerChunk(tab, run, chunk, "stdout"));
3493
+ child.stderr.on("data", (chunk) => appendAppRunnerChunk(tab, run, chunk, "stderr"));
3494
+ child.on("error", (error) => finishAppRunner(tab, run, { error: sanitizeError(error) }));
3495
+ child.on("exit", (exitCode, signal) => finishAppRunner(tab, run, { exitCode, signal }));
3496
+ }
3320
3497
 
3321
3498
  recordEvent({ type: "webui_app_runner_start", tabId: tab.id, tabTitle: tab.title, command: run.displayCommand, cwd: run.cwd, pid: run.pid });
3322
3499
  broadcastAppRunnerState(tab);
@@ -3327,7 +3504,9 @@ function stopAppRunnerForTab(tab, reason = "stop requested", { force = false } =
3327
3504
  const run = tab?.appRunner;
3328
3505
  if (!run || run.status !== "running") return false;
3329
3506
  run.stopping = true;
3330
- const action = process.platform === "win32" ? "terminating Windows process tree" : `sending ${force ? "SIGKILL" : "Ctrl+C"}`;
3507
+ const action = run.executionMode === "conpty" && !force
3508
+ ? "sending Ctrl+C"
3509
+ : process.platform === "win32" ? "terminating Windows process tree" : `sending ${force ? "SIGKILL" : "Ctrl+C"}`;
3331
3510
  appendAppRunnerLine(run, `# ${reason}; ${action}`);
3332
3511
  if (force) terminateAppRunnerChild(run, "SIGKILL");
3333
3512
  else interruptAppRunnerChild(run);
@@ -4505,7 +4684,14 @@ async function getGitRoot(cwd) {
4505
4684
  }
4506
4685
 
4507
4686
  async function runGitReadCommandDetailed(root, args, { timeoutMs = GIT_CHANGES_COMMAND_TIMEOUT_MS, maxOutputLength = GIT_CHANGES_DIFF_MAX_OUTPUT } = {}) {
4508
- const result = await runCommand("git", args, { cwd: root, timeoutMs, maxOutputLength });
4687
+ const result = await runCommand("git", args, {
4688
+ cwd: root,
4689
+ timeoutMs,
4690
+ maxOutputLength,
4691
+ // Prevent read-only status/diff commands from refreshing the index and
4692
+ // feeding their own metadata writes back into the live Git watcher.
4693
+ env: { GIT_OPTIONAL_LOCKS: "0" },
4694
+ });
4509
4695
  if (result.exitCode === 0 && !result.timedOut && !result.error) {
4510
4696
  return { output: result.stdout, truncated: result.stdoutTruncated === true, capBytes: maxOutputLength };
4511
4697
  }
@@ -5839,35 +6025,73 @@ async function readGitWorkflowBranchName(cwd) {
5839
6025
  }
5840
6026
  }
5841
6027
 
5842
- async function readGitWorkflowMessages(cwd) {
6028
+ const GIT_WORKFLOW_MESSAGE_PAIR_SETTLE_MS = 80;
6029
+
6030
+ function gitWorkflowMessagePendingPayload(root, messageCwd, paths, generationId, reason, details = {}) {
6031
+ const shortFile = gitWorkflowMessageFileMeta(root, messageCwd, paths.shortPath);
6032
+ const longFile = gitWorkflowMessageFileMeta(root, messageCwd, paths.longPath);
6033
+ return {
6034
+ ready: false,
6035
+ generationId,
6036
+ reason,
6037
+ root,
6038
+ cwd: messageCwd,
6039
+ shortPath: paths.shortPath,
6040
+ longPath: paths.longPath,
6041
+ shortRelativePath: shortFile.relativePath,
6042
+ longRelativePath: longFile.relativePath,
6043
+ shortRepoRelativePath: shortFile.repoRelativePath,
6044
+ longRepoRelativePath: longFile.repoRelativePath,
6045
+ ...details,
6046
+ };
6047
+ }
6048
+
6049
+ async function readGitWorkflowMessages(cwd, { generationId = "", generation = null } = {}) {
5843
6050
  const root = await getGitRoot(cwd);
5844
6051
  const messageCwd = gitWorkflowMessageCwd(root, cwd);
5845
- const { shortPath, longPath } = commitMessagePaths(messageCwd);
6052
+ const paths = commitMessagePaths(messageCwd);
6053
+ if (generationId && (!generation || generation.id !== generationId || generation.kind !== "commit" || generation.cwd !== messageCwd)) {
6054
+ return gitWorkflowMessagePendingPayload(root, messageCwd, paths, generationId, "This commit-message generation is no longer active. Regenerate the message files.", { expired: true });
6055
+ }
5846
6056
  try {
5847
- const [shortText, longText, shortStat, longStat] = await Promise.all([
5848
- readFile(shortPath, "utf8"),
5849
- readFile(longPath, "utf8"),
5850
- stat(shortPath),
5851
- stat(longPath),
5852
- ]);
5853
- const shortFile = gitWorkflowMessageFileMeta(root, messageCwd, shortPath);
5854
- const longFile = gitWorkflowMessageFileMeta(root, messageCwd, longPath);
6057
+ let pair = await readStableGitMessageArtifactPair(paths);
6058
+ if (generationId) {
6059
+ const readiness = gitMessageArtifactPairReadiness(generation.baseline, pair);
6060
+ if (!readiness.ready) return gitWorkflowMessagePendingPayload(root, messageCwd, paths, generationId, readiness.reason, readiness);
6061
+ await new Promise((resolve) => setTimeout(resolve, GIT_WORKFLOW_MESSAGE_PAIR_SETTLE_MS));
6062
+ const settledPair = await readStableGitMessageArtifactPair(paths);
6063
+ if (!sameGitMessageArtifactPair(pair, settledPair)) {
6064
+ return gitWorkflowMessagePendingPayload(root, messageCwd, paths, generationId, "Generated commit message files are still settling.");
6065
+ }
6066
+ const settledReadiness = gitMessageArtifactPairReadiness(generation.baseline, settledPair);
6067
+ if (!settledReadiness.ready) return gitWorkflowMessagePendingPayload(root, messageCwd, paths, generationId, settledReadiness.reason, settledReadiness);
6068
+ pair = settledPair;
6069
+ }
6070
+ if (!pair.short.exists || !pair.long.exists) {
6071
+ throw new Error(`Missing ${!pair.short.exists ? paths.shortPath : paths.longPath}`);
6072
+ }
6073
+ const shortFile = gitWorkflowMessageFileMeta(root, messageCwd, paths.shortPath);
6074
+ const longFile = gitWorkflowMessageFileMeta(root, messageCwd, paths.longPath);
5855
6075
  return {
6076
+ ready: true,
6077
+ generationId,
5856
6078
  root,
5857
6079
  cwd: messageCwd,
5858
- shortPath,
5859
- longPath,
6080
+ shortPath: paths.shortPath,
6081
+ longPath: paths.longPath,
5860
6082
  shortRelativePath: shortFile.relativePath,
5861
6083
  longRelativePath: longFile.relativePath,
5862
6084
  shortRepoRelativePath: shortFile.repoRelativePath,
5863
6085
  longRepoRelativePath: longFile.repoRelativePath,
5864
- short: shortText.trimEnd(),
5865
- long: longText.trimEnd(),
5866
- shortMtimeMs: shortStat.mtimeMs,
5867
- longMtimeMs: longStat.mtimeMs,
6086
+ short: pair.short.text.trimEnd(),
6087
+ long: pair.long.text.trimEnd(),
6088
+ shortMtimeMs: Number(BigInt(pair.short.mtimeNs) / 1_000_000n),
6089
+ longMtimeMs: Number(BigInt(pair.long.mtimeNs) / 1_000_000n),
6090
+ shortSha256: pair.short.sha256,
6091
+ longSha256: pair.long.sha256,
5868
6092
  };
5869
6093
  } catch (error) {
5870
- throw new Error(`Missing generated commit message files in ${path.join(messageCwd, "dev", "COMMIT")}. Run /git-staged-msg first. ${sanitizeError(error)}`);
6094
+ throw new Error(`Missing or unstable generated commit message files in ${path.join(messageCwd, "dev", "COMMIT")}. Run /git-staged-msg first. ${sanitizeError(error)}`);
5871
6095
  }
5872
6096
  }
5873
6097
 
@@ -6611,8 +6835,11 @@ async function handleGitWorkflowRequest(pathname, body = {}, tabOrCwd = options.
6611
6835
  case "/api/git-workflow/staged-content":
6612
6836
  if (!tab) throw new Error("Staged-content lookup requires a Web UI tab");
6613
6837
  return { ok: true, data: await stagedContentHashForTab(tab) };
6614
- case "/api/git-workflow/message":
6615
- return { ok: true, data: await readGitWorkflowMessages(cwd) };
6838
+ case "/api/git-workflow/message": {
6839
+ const generationId = String(body.generationId || "").trim();
6840
+ if (generationId && !tab) throw new Error("Fresh commit-message lookup requires a Web UI tab");
6841
+ return { ok: true, data: await readGitWorkflowMessages(cwd, { generationId, generation: tab?.gitWorkflowMessageGeneration || null }) };
6842
+ }
6616
6843
  case "/api/git-workflow/default-commit-message":
6617
6844
  return { ok: true, data: await readGitWorkflowDefaultCommitMessage(cwd) };
6618
6845
  case "/api/git-workflow/branch-name":
@@ -6817,7 +7044,7 @@ async function readBundledThemes() {
6817
7044
  function normalizeStaticPath(urlPath) {
6818
7045
  if (urlPath === "/") return "index.html";
6819
7046
  const name = urlPath.startsWith("/") ? urlPath.slice(1) : urlPath;
6820
- if (!["index.html", "app.js", "voice-conversation.mjs", "aur-review-payload.mjs", "guided-git-command-state.mjs", "guided-git-review-state.mjs", "styles.css", "favicon.svg", "apple-touch-icon.png", "icon-192.png", "icon-512.png", "catppuccin-mocha-background.png", "matrix-background.webp", "manifest.webmanifest", "service-worker.js"].includes(name)) return undefined;
7047
+ if (!["index.html", "app.js", "fast-output-live.mjs", "voice-conversation.mjs", "aur-review-payload.mjs", "guided-git-command-state.mjs", "guided-git-review-state.mjs", "styles.css", "favicon.svg", "apple-touch-icon.png", "icon-192.png", "icon-512.png", "catppuccin-mocha-background.png", "matrix-background.webp", "manifest.webmanifest", "service-worker.js"].includes(name)) return undefined;
6821
7048
  return name;
6822
7049
  }
6823
7050
 
@@ -6937,11 +7164,21 @@ function stripDataUrlPrefix(data) {
6937
7164
  return comma === -1 ? text : text.slice(comma + 1);
6938
7165
  }
6939
7166
 
6940
- function decodeAttachmentData(data) {
7167
+ function decodeCanonicalBase64(data, label) {
6941
7168
  const base64 = stripDataUrlPrefix(data).replace(/\s+/g, "");
6942
- if (!base64) throw new Error("attachment data is required");
6943
- if (!/^[A-Za-z0-9+/]*={0,2}$/.test(base64)) throw new Error("attachment data must be base64 encoded");
6944
- return Buffer.from(base64, "base64");
7169
+ if (!base64) throw makeHttpError(400, `${label} data is required`);
7170
+ if (base64.length % 4 !== 0 || !/^[A-Za-z0-9+/]+={0,2}$/.test(base64)) {
7171
+ throw makeHttpError(400, `${label} data must be canonical base64`);
7172
+ }
7173
+ const buffer = Buffer.from(base64, "base64");
7174
+ if (buffer.length === 0 || buffer.toString("base64") !== base64) {
7175
+ throw makeHttpError(400, `${label} data must be canonical base64`);
7176
+ }
7177
+ return { base64, buffer };
7178
+ }
7179
+
7180
+ function decodeAttachmentData(data) {
7181
+ return decodeCanonicalBase64(data, "attachment").buffer;
6945
7182
  }
6946
7183
 
6947
7184
  async function saveUploadedAttachments(body) {
@@ -6985,13 +7222,10 @@ function normalizeRpcImages(value) {
6985
7222
  let totalBytes = 0;
6986
7223
  for (const [index, image] of value.entries()) {
6987
7224
  const mimeType = normalizeMimeType(image?.mimeType);
6988
- if (!RPC_IMAGE_MIME_TYPES.has(mimeType)) throw new Error(`image ${index + 1} has unsupported MIME type ${mimeType}`);
6989
- const data = stripDataUrlPrefix(image?.data).replace(/\s+/g, "");
6990
- if (!data) throw new Error(`image ${index + 1} data is required`);
6991
- if (!/^[A-Za-z0-9+/]*={0,2}$/.test(data)) throw new Error(`image ${index + 1} data must be base64 encoded`);
6992
- const approxBytes = Math.floor((data.length * 3) / 4);
6993
- if (approxBytes > INLINE_IMAGE_MAX_BYTES) throw new Error(`image ${index + 1} exceeds ${formatBytes(INLINE_IMAGE_MAX_BYTES)} inline limit`);
6994
- totalBytes += approxBytes;
7225
+ if (!RPC_IMAGE_MIME_TYPES.has(mimeType)) throw makeHttpError(400, `image ${index + 1} has unsupported MIME type ${mimeType}`);
7226
+ const { base64: data, buffer } = decodeCanonicalBase64(image?.data, `image ${index + 1}`);
7227
+ if (buffer.length > INLINE_IMAGE_MAX_BYTES) throw new Error(`image ${index + 1} exceeds ${formatBytes(INLINE_IMAGE_MAX_BYTES)} inline limit`);
7228
+ totalBytes += buffer.length;
6995
7229
  if (totalBytes > INLINE_IMAGE_TOTAL_MAX_BYTES) throw new Error(`inline images exceed ${formatBytes(INLINE_IMAGE_TOTAL_MAX_BYTES)} total`);
6996
7230
  images.push({ type: "image", data, mimeType });
6997
7231
  }
@@ -7734,9 +7968,9 @@ function enforceNaturalConversationCommandAllowed(tab, command) {
7734
7968
  }
7735
7969
  }
7736
7970
 
7737
- function replayExtensionStatuses(tab, res) {
7971
+ function replayExtensionStatuses(tab, client) {
7738
7972
  for (const [statusKey, statusText] of extensionStatusMap(tab)) {
7739
- sendSse(res, {
7973
+ sendSseToClient(client, {
7740
7974
  type: "extension_ui_request",
7741
7975
  id: randomUUID(),
7742
7976
  method: "setStatus",
@@ -7751,10 +7985,10 @@ function replayExtensionStatuses(tab, res) {
7751
7985
  }
7752
7986
  }
7753
7987
 
7754
- function replayExtensionWidgets(tab, res) {
7988
+ function replayExtensionWidgets(tab, client) {
7755
7989
  const pendingExtensionUiRequestCount = pendingExtensionUiRequests(tab).length;
7756
7990
  for (const [widgetKey, request] of extensionWidgetMap(tab)) {
7757
- sendSse(res, {
7991
+ sendSseToClient(client, {
7758
7992
  ...request,
7759
7993
  type: "extension_ui_request",
7760
7994
  id: randomUUID(),
@@ -8041,10 +8275,10 @@ function clearPendingExtensionUiRequests(tab) {
8041
8275
  tab?.pendingExtensionUiRequests?.clear();
8042
8276
  }
8043
8277
 
8044
- function replayPendingExtensionUiRequests(tab, res) {
8278
+ function replayPendingExtensionUiRequests(tab, client) {
8045
8279
  const pending = pendingExtensionUiRequests(tab);
8046
8280
  for (const request of pending) {
8047
- sendSse(res, {
8281
+ sendSseToClient(client, {
8048
8282
  ...request,
8049
8283
  type: "extension_ui_request",
8050
8284
  replayed: true,
@@ -8229,6 +8463,7 @@ function attachRpcToTab(tab, rpc) {
8229
8463
  let scopedEvent = eventForTabClients(tab, event);
8230
8464
  if (event?.type === "pi_process_exit" || event?.type === "pi_process_error") {
8231
8465
  tab.gitWorkflowGenerationRestore = null;
8466
+ tab.gitWorkflowMessageGeneration = null;
8232
8467
  clearPendingExtensionUiRequests(tab);
8233
8468
  clearExtensionStatuses(tab);
8234
8469
  clearExtensionWidgets(tab);
@@ -8242,7 +8477,7 @@ function attachRpcToTab(tab, rpc) {
8242
8477
  }
8243
8478
  scopedEvent = { ...scopedEvent, tabActivity: tabActivitySnapshot(tab), pendingExtensionUiRequestCount: pendingExtensionUiRequests(tab).length };
8244
8479
  recordEvent(scopedEvent);
8245
- for (const client of tab.sseClients) sendSse(client, scopedEvent);
8480
+ for (const client of tab.sseClients) sendSseToClient(client, scopedEvent);
8246
8481
  if (event?.type === "compaction_end") void flushCompactionQueue(tab, event);
8247
8482
  if (event?.type === "agent_settled") void restoreGitWorkflowGenerationProfile(tab);
8248
8483
  });
@@ -8275,6 +8510,7 @@ async function createTab({ id: requestedId, index, title, titleSource, conversat
8275
8510
  lastState: null,
8276
8511
  pendingThinkingLevel: undefined,
8277
8512
  gitWorkflowGenerationRestore: null,
8513
+ gitWorkflowMessageGeneration: null,
8278
8514
  activity: createTabActivity(createdAt),
8279
8515
  pendingExtensionUiRequests: new Map(),
8280
8516
  extensionStatuses: new Map(),
@@ -8300,6 +8536,7 @@ async function createTab({ id: requestedId, index, title, titleSource, conversat
8300
8536
  } catch (error) {
8301
8537
  if (!tab.rpc.isRunning()) {
8302
8538
  tab.rpcUnsubscribe?.();
8539
+ gitLiveWatcher.unsubscribe(id);
8303
8540
  tabs.delete(id);
8304
8541
  throw new Error(`Pi RPC process failed while starting ${tabTitle}: ${sanitizeError(error)}`);
8305
8542
  }
@@ -9047,7 +9284,7 @@ function rememberClosedRestorableTab(tab, state = null) {
9047
9284
 
9048
9285
  function broadcastTabEvent(tab, event) {
9049
9286
  recordEvent(event);
9050
- for (const client of tab.sseClients) sendSse(client, event);
9287
+ for (const client of tab.sseClients) sendSseToClient(client, event);
9051
9288
  }
9052
9289
 
9053
9290
  function broadcastServerEvent(event) {
@@ -9056,7 +9293,23 @@ function broadcastServerEvent(event) {
9056
9293
  for (const tab of tabs.values()) {
9057
9294
  for (const client of tab.sseClients) clients.add(client);
9058
9295
  }
9059
- for (const client of clients) sendSse(client, event);
9296
+ for (const client of clients) sendSseToClient(client, event);
9297
+ }
9298
+
9299
+ const gitLiveWatcher = createGitLiveWatcher({
9300
+ onChange: ({ root, changedAt }) => {
9301
+ broadcastServerEvent({ type: "webui_git_changed", root, changedAt });
9302
+ },
9303
+ onError: ({ root, error }) => {
9304
+ const message = sanitizeError(error);
9305
+ recordEvent({ type: "webui_git_watch_error", root, error: message });
9306
+ console.warn(`Git live watcher disabled for ${root}: ${message}`);
9307
+ },
9308
+ });
9309
+
9310
+ function trackGitRepositoryForTab(tab, root) {
9311
+ if (tab?.id && root) gitLiveWatcher.subscribe(tab.id, root);
9312
+ return root;
9060
9313
  }
9061
9314
 
9062
9315
  function renameTab(tab, title, { source = "explicit", maxLength, unique = source === "auto" } = {}) {
@@ -9112,11 +9365,9 @@ async function updateTabCwd(id, cwd) {
9112
9365
  const piArgs = await buildPiArgsForTab(tab.index, tab.title, nextCwd);
9113
9366
  if (sessionFile && !options.noSession) piArgs.push("--session", sessionFile);
9114
9367
  const piCommand = await resolvePiCommand(piArgs);
9368
+ gitLiveWatcher.unsubscribe(tab.id);
9115
9369
  const restartingEvent = { type: "webui_tab_restarting", tabId: tab.id, tabTitle: tab.title, cwd: nextCwd, sessionFile };
9116
- recordEvent(restartingEvent);
9117
- for (const client of tab.sseClients) {
9118
- sendSse(client, restartingEvent);
9119
- }
9370
+ broadcastTabEvent(tab, restartingEvent);
9120
9371
 
9121
9372
  const oldRpc = tab.rpc;
9122
9373
  tab.rpcUnsubscribe?.();
@@ -9139,10 +9390,7 @@ async function updateTabCwd(id, cwd) {
9139
9390
  await primeTabRpc(tab).catch(() => {});
9140
9391
 
9141
9392
  const changedEvent = { type: "webui_cwd_changed", tabId: tab.id, tabTitle: tab.title, cwd: tab.cwd, pid: tab.rpc.child?.pid, sessionFile, tabActivity: tabActivitySnapshot(tab) };
9142
- recordEvent(changedEvent);
9143
- for (const client of tab.sseClients) {
9144
- sendSse(client, changedEvent);
9145
- }
9393
+ broadcastTabEvent(tab, changedEvent);
9146
9394
  return { tab, changed: true };
9147
9395
  }
9148
9396
 
@@ -9157,8 +9405,7 @@ async function restartTabRpc(tab, reason = "reload") {
9157
9405
  if (state.data?.sessionFile && !options.noSession) piArgs.push("--session", state.data.sessionFile);
9158
9406
  const piCommand = await resolvePiCommand(piArgs);
9159
9407
  const reloadingEvent = { type: "webui_tab_reloading", tabId: tab.id, tabTitle: tab.title, cwd: tab.cwd, reason, sessionFile: state.data?.sessionFile };
9160
- recordEvent(reloadingEvent);
9161
- for (const client of tab.sseClients) sendSse(client, reloadingEvent);
9408
+ broadcastTabEvent(tab, reloadingEvent);
9162
9409
 
9163
9410
  const oldRpc = tab.rpc;
9164
9411
  tab.rpcUnsubscribe?.();
@@ -9177,8 +9424,7 @@ async function restartTabRpc(tab, reason = "reload") {
9177
9424
  rpc.start();
9178
9425
 
9179
9426
  const reloadedEvent = { type: "webui_tab_reloaded", tabId: tab.id, tabTitle: tab.title, cwd: tab.cwd, pid: tab.rpc.child?.pid, reason, sessionFile: state.data?.sessionFile, tabActivity: tabActivitySnapshot(tab) };
9180
- recordEvent(reloadedEvent);
9181
- for (const client of tab.sseClients) sendSse(client, reloadedEvent);
9427
+ broadcastTabEvent(tab, reloadedEvent);
9182
9428
  return tab;
9183
9429
  }
9184
9430
 
@@ -11283,12 +11529,13 @@ async function closeTab(id) {
11283
11529
  if (stateResult.ok) restorableState = stateResult.data;
11284
11530
  }
11285
11531
  rememberClosedRestorableTab(tab, restorableState);
11532
+ gitLiveWatcher.unsubscribe(tab.id);
11286
11533
 
11287
11534
  const closingEvent = { type: "webui_tab_closing", tabId: tab.id, tabTitle: tab.title };
11288
11535
  recordEvent(closingEvent);
11289
11536
  for (const client of tab.sseClients) {
11290
- sendSse(client, closingEvent);
11291
- client.end();
11537
+ sendSseToClient(client, closingEvent);
11538
+ client.res.end();
11292
11539
  }
11293
11540
  tab.sseClients.clear();
11294
11541
  tab.rpcUnsubscribe?.();
@@ -11301,6 +11548,7 @@ async function closeTab(id) {
11301
11548
 
11302
11549
  async function discardTab(tab) {
11303
11550
  if (!tab || !tabs.has(tab.id)) return;
11551
+ gitLiveWatcher.unsubscribe(tab.id);
11304
11552
  tab.rpcUnsubscribe?.();
11305
11553
  rejectTabBashQueue(tab, new Error("Pi recovery tab initialization failed"));
11306
11554
  stopAppRunnerForTab(tab, "recovery initialization failed", { force: true });
@@ -11418,12 +11666,89 @@ async function createInitialTabs() {
11418
11666
  }
11419
11667
 
11420
11668
  const serverStartedAt = new Date().toISOString();
11421
- let persistedRemoteAuthEnabled = await readPersistedRemoteAuthEnabled();
11669
+ const persistedStartupSettings = await readWebuiSettings(undefined, { reportInvalidOutputMode: true });
11670
+ let persistedRemoteAuthEnabled = persistedStartupSettings.remoteAuthEnabled === true;
11671
+ let persistedOutputModeDefault = persistedStartupSettings.outputModeDefault;
11422
11672
  const initialTabs = await createInitialTabs();
11423
11673
  const initialTab = initialTabs[0];
11424
11674
  let currentHost = options.host;
11425
11675
  let networkRebindInProgress = false;
11426
11676
  let networkRebindTargetHost = null;
11677
+
11678
+ function resolvedOutputModeDefault() {
11679
+ return resolveOutputModeDefault({
11680
+ cliMode: options.outputMode,
11681
+ envMode: options.envOutputMode,
11682
+ persistedMode: persistedOutputModeDefault,
11683
+ });
11684
+ }
11685
+
11686
+ function outputModeMetadata() {
11687
+ const resolved = resolvedOutputModeDefault();
11688
+ return {
11689
+ persistedDefault: normalizeOutputMode(persistedOutputModeDefault),
11690
+ effectiveDefault: resolved.mode,
11691
+ source: resolved.source,
11692
+ overridden: resolved.source === "cli" || resolved.source === "env",
11693
+ };
11694
+ }
11695
+
11696
+ function tabHasActiveOutput(tab) {
11697
+ return tab?.activity?.isWorking === true || tab?.lastState?.isStreaming === true || tab?.lastState?.isCompacting === true;
11698
+ }
11699
+
11700
+ function activateOutputMode(client, activeMode, reason = "server-default-change") {
11701
+ const nextMode = normalizeOutputMode(activeMode);
11702
+ if (client.activeMode === nextMode) {
11703
+ client.pendingMode = undefined;
11704
+ return;
11705
+ }
11706
+ sendSse(client, {
11707
+ type: "webui_output_mode",
11708
+ protocolVersion: OUTPUT_MODE_PROTOCOL_VERSION,
11709
+ previousMode: client.activeMode,
11710
+ activeMode: nextMode,
11711
+ reason,
11712
+ });
11713
+ client.activeMode = nextMode;
11714
+ client.pendingMode = undefined;
11715
+ }
11716
+
11717
+ function sendSseToClient(client, event) {
11718
+ sendSse(client, event);
11719
+ if (client?.pendingMode && isOutputModeSemanticBarrier(event)) activateOutputMode(client, client.pendingMode);
11720
+ }
11721
+
11722
+ function refreshAutoOutputModes() {
11723
+ const resolved = resolvedOutputModeDefault();
11724
+ for (const tab of tabs.values()) {
11725
+ for (const client of tab.sseClients) {
11726
+ if (client.requestedMode !== "auto") continue;
11727
+ client.defaultSource = resolved.source;
11728
+ if (client.activeMode === resolved.mode) {
11729
+ client.pendingMode = undefined;
11730
+ } else if (tabHasActiveOutput(tab)) {
11731
+ client.pendingMode = resolved.mode;
11732
+ } else {
11733
+ activateOutputMode(client, resolved.mode);
11734
+ }
11735
+ }
11736
+ }
11737
+ }
11738
+
11739
+ async function saveOutputModeDefault(value) {
11740
+ let mode;
11741
+ try {
11742
+ mode = requiredOutputMode(value, "outputModeDefault");
11743
+ } catch (error) {
11744
+ throw makeHttpError(400, formatCliError(error));
11745
+ }
11746
+ const settings = await writeWebuiSettings({ outputModeDefault: mode });
11747
+ persistedOutputModeDefault = settings.outputModeDefault;
11748
+ refreshAutoOutputModes();
11749
+ return outputModeMetadata();
11750
+ }
11751
+
11427
11752
  const remoteAuth = {
11428
11753
  pin: undefined,
11429
11754
  token: undefined,
@@ -11556,8 +11881,8 @@ function closeSseClientsForRebind(nextHost) {
11556
11881
  };
11557
11882
  recordEvent(rebindEvent);
11558
11883
  for (const client of tab.sseClients) {
11559
- sendSse(client, rebindEvent);
11560
- client.end();
11884
+ sendSseToClient(client, rebindEvent);
11885
+ client.res.end();
11561
11886
  }
11562
11887
  tab.sseClients.clear();
11563
11888
  }
@@ -11573,8 +11898,8 @@ function closeSseClientsForRemoteAuthChange() {
11573
11898
  };
11574
11899
  recordEvent(authEvent);
11575
11900
  for (const client of tab.sseClients) {
11576
- sendSse(client, authEvent);
11577
- client.end();
11901
+ sendSseToClient(client, authEvent);
11902
+ client.res.end();
11578
11903
  }
11579
11904
  tab.sseClients.clear();
11580
11905
  }
@@ -11785,6 +12110,7 @@ async function webuiStatus({ detailed = false, eventLimit = 40, includeAuthPin =
11785
12110
  network,
11786
12111
  piPid: tab?.rpc.child?.pid,
11787
12112
  piRunning: !!tab?.rpc.child && tab.rpc.child.exitCode === null,
12113
+ outputMode: outputModeMetadata(),
11788
12114
  tabs: statusTabs,
11789
12115
  restorableTabs: mergeRestorableTabDescriptors(statusTabs),
11790
12116
  };
@@ -11851,6 +12177,17 @@ const server = createServer(async (req, res) => {
11851
12177
  return;
11852
12178
  }
11853
12179
 
12180
+ if (url.pathname === "/api/webui-output-mode" && req.method === "GET") {
12181
+ sendJson(res, 200, { ok: true, data: outputModeMetadata() });
12182
+ return;
12183
+ }
12184
+
12185
+ if (url.pathname === "/api/webui-output-mode" && req.method === "PUT") {
12186
+ const body = await readJsonBody(req);
12187
+ sendJson(res, 200, { ok: true, data: await saveOutputModeDefault(body.outputModeDefault) });
12188
+ return;
12189
+ }
12190
+
11854
12191
  if (url.pathname === "/api/tabs" && req.method === "GET") {
11855
12192
  sendJson(res, 200, { ok: true, data: { tabs: await listTabsWithReconciledActivity() } });
11856
12193
  return;
@@ -11901,6 +12238,20 @@ const server = createServer(async (req, res) => {
11901
12238
 
11902
12239
  if (url.pathname === "/api/events" && req.method === "GET") {
11903
12240
  const tab = getRequestedTab(req, url);
12241
+ const resolvedDefault = resolvedOutputModeDefault();
12242
+ const negotiated = negotiateOutputMode({
12243
+ requestedMode: url.searchParams.get("outputMode"),
12244
+ protocolVersion: url.searchParams.get("outputModeProtocol"),
12245
+ serverDefault: resolvedDefault.mode,
12246
+ });
12247
+ const client = {
12248
+ res,
12249
+ requestedMode: negotiated.requestedMode,
12250
+ protocolVersion: negotiated.protocolVersion,
12251
+ activeMode: negotiated.activeMode,
12252
+ pendingMode: undefined,
12253
+ defaultSource: resolvedDefault.source,
12254
+ };
11904
12255
  res.writeHead(200, {
11905
12256
  "content-type": "text/event-stream; charset=utf-8",
11906
12257
  "cache-control": "no-cache, no-transform",
@@ -11908,13 +12259,20 @@ const server = createServer(async (req, res) => {
11908
12259
  "x-content-type-options": "nosniff",
11909
12260
  });
11910
12261
  res.write(": connected\n\n");
11911
- tab.sseClients.add(res);
11912
- sendSse(res, {
12262
+ tab.sseClients.add(client);
12263
+ sendSseToClient(client, {
11913
12264
  type: "webui_connected",
11914
12265
  version: packageJson.version,
11915
12266
  piVersion: String(piPackageJson.version || ""),
11916
12267
  webuiDev: webuiDevServer,
11917
12268
  webuiMode: webuiDevServer ? "dev" : "production",
12269
+ outputMode: {
12270
+ protocolVersion: negotiated.protocolVersion,
12271
+ requestedMode: negotiated.requestedMode,
12272
+ activeMode: negotiated.activeMode,
12273
+ serverDefault: resolvedDefault.mode,
12274
+ serverDefaultSource: resolvedDefault.source,
12275
+ },
11918
12276
  tabId: tab.id,
11919
12277
  tabTitle: tab.title,
11920
12278
  pid: tab.rpc.child?.pid,
@@ -11924,13 +12282,13 @@ const server = createServer(async (req, res) => {
11924
12282
  pendingExtensionUiRequestCount: pendingExtensionUiRequests(tab).length,
11925
12283
  activeRun: publicAppRunnerState(tab.appRunner),
11926
12284
  });
11927
- replayExtensionStatuses(tab, res);
11928
- replayExtensionWidgets(tab, res);
11929
- replayPendingExtensionUiRequests(tab, res);
12285
+ replayExtensionStatuses(tab, client);
12286
+ replayExtensionWidgets(tab, client);
12287
+ replayPendingExtensionUiRequests(tab, client);
11930
12288
  const keepAlive = setInterval(() => res.write(": keepalive\n\n"), 15000);
11931
12289
  req.on("close", () => {
11932
12290
  clearInterval(keepAlive);
11933
- tab.sseClients.delete(res);
12291
+ tab.sseClients.delete(client);
11934
12292
  });
11935
12293
  return;
11936
12294
  }
@@ -11947,6 +12305,7 @@ const server = createServer(async (req, res) => {
11947
12305
  piPid: status.piPid,
11948
12306
  piRunning: status.piRunning,
11949
12307
  cwd: status.cwd,
12308
+ outputMode: status.outputMode,
11950
12309
  network: status.network,
11951
12310
  tabs: status.tabs,
11952
12311
  restorableTabs: status.restorableTabs,
@@ -12635,7 +12994,8 @@ const server = createServer(async (req, res) => {
12635
12994
  if (url.pathname === "/api/git-root" && req.method === "GET") {
12636
12995
  const tab = getRequestedTab(req, url);
12637
12996
  try {
12638
- sendJson(res, 200, { ok: true, data: { cwd: tab.cwd, root: await getGitRoot(tab.cwd) } });
12997
+ const root = trackGitRepositoryForTab(tab, await getGitRoot(tab.cwd));
12998
+ sendJson(res, 200, { ok: true, data: { cwd: tab.cwd, root } });
12639
12999
  } catch (error) {
12640
13000
  sendJson(res, 200, { ok: false, error: sanitizeError(error) });
12641
13001
  }
@@ -12645,7 +13005,9 @@ const server = createServer(async (req, res) => {
12645
13005
  if (url.pathname === "/api/git-panel" && req.method === "GET") {
12646
13006
  const tab = getRequestedTab(req, url);
12647
13007
  try {
12648
- sendJson(res, 200, { ok: true, data: await readGitPanel(tab.cwd) });
13008
+ const data = await readGitPanel(tab.cwd);
13009
+ trackGitRepositoryForTab(tab, data.root);
13010
+ sendJson(res, 200, { ok: true, data });
12649
13011
  } catch (error) {
12650
13012
  sendJson(res, 200, { ok: false, error: sanitizeError(error) });
12651
13013
  }
@@ -12831,7 +13193,7 @@ const server = createServer(async (req, res) => {
12831
13193
  sendJson(res, 405, { ok: false, error: `${url.pathname} requires ${requiredMethod}` });
12832
13194
  return;
12833
13195
  }
12834
- const body = mutatingWorkflow ? await readJsonBody(req) : {};
13196
+ const body = mutatingWorkflow ? await readJsonBody(req) : { generationId: url.searchParams.get("generationId") || "" };
12835
13197
  const tab = getRequestedTab(req, url, body);
12836
13198
  if (mutatingWorkflow) ensureNaturalConversationRouteAllowed(tab, "git workflow actions are blocked");
12837
13199
  const response = await handleGitWorkflowRequest(url.pathname, body, tab);
@@ -12963,6 +13325,7 @@ server.listen(options.port, currentHost, () => {
12963
13325
 
12964
13326
  function shutdown(signal) {
12965
13327
  console.log(`\n${signal}: shutting down Pi Web UI...`);
13328
+ gitLiveWatcher.closeAll();
12966
13329
  const forceCloseTimer = setTimeout(() => {
12967
13330
  server.closeAllConnections?.();
12968
13331
  }, NETWORK_REBIND_FORCE_CLOSE_MS);