@firstpick/pi-package-webui 0.7.2 → 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/README.md CHANGED
@@ -155,10 +155,10 @@ Optional Natural Conversation server-side voice fallback variables:
155
155
  - Runtime `/tools` and `/skills` selectors backed by the hidden Web UI RPC helper, with explicit **Session only** and **Global default** scopes. Session choices persist on the current branch and take precedence; global defaults are inherited by future sessions without rewriting existing branches. Disabled skills are removed from the system prompt, and tracked `SKILL.md` files can be opened/edited from skill tags.
156
156
  - Session resume/switch, metadata rename, and localhost-only safe delete with active/open-tab/session-directory guards.
157
157
  - Model, thinking, session, workspace, theme, optional-feature, Codex usage, optional Remote WebUI, update/restart/stop, event, notification, thinking-visibility, terminal-tab-layout, and custom-background controls in collapsible side-panel sections.
158
- - A side-panel **Git** section mirrors the repositories represented by every open terminal tab/group. Repository cards are shown directly—without session-name parent disclosures—and always use the Git-root or cwd basename as their title. One repository can be expanded at a time, and first/stale expansion refreshes local status after a five-minute cache window without background polling or an automatic network `git fetch`. Its compact Changes tree groups conflicted, staged, modified, and untracked paths with additions/deletions; right-click a repository, folder, or file (or press Shift+F10/the Context Menu key) for View Diff, refresh, stage/unstage, and confirmed discard/delete actions. History lists the latest 30 commits and opens bounded read-only commit diffs.
158
+ - A side-panel **Git** section mirrors the repositories represented by every open terminal tab/group. Repository cards are shown directly—without session-name parent disclosures—and always use the Git-root or cwd basename as their title. One repository can be expanded at a time. First/stale expansion refreshes local status after a five-minute cache window, while live filesystem updates use a debounced server watcher and SSE invalidation to refresh visible repositories without periodic Git polling or an automatic network `git fetch`. Its compact Changes tree groups conflicted, staged, modified, and untracked paths with additions/deletions; right-click a repository, folder, or file (or press Shift+F10/the Context Menu key) for View Diff, refresh, stage/unstage, and confirmed discard/delete actions. History lists the latest 30 commits and opens bounded read-only commit diffs.
159
159
  - Persistent context-window meter with manual compact and auto-compaction controls near the composer; side-panel thinking changes made while a tab is busy are queued for the next prompt.
160
160
  - Side-panel theme picker backed by optional `@firstpick/pi-themes-bundle` themes when loaded.
161
- - Per-tab cwd changes, a clickable footer cwd picker, directory creation/search in the picker, saved path fast picks, server-persisted fast picks, and restart-safe restoration of open tabs.
161
+ - Per-tab cwd changes, a clickable footer cwd picker, directory creation/search in the picker, saved path fast picks, server-persisted fast picks, and restart-safe restoration of open tabs. When the optional stats and git-footer companions are loaded, clicking the footer **PI** token metric dispatches `/calibrate` in the background and refreshes the metric after the isolated calibration sample is recorded.
162
162
  - Detected app runner dropdown for the active tab cwd, including Cargo, Bun, npm/npx/pnpm, Python/uv, Go/Golang, Zig, C/C++, Docker Compose, root/dev/scripts shell scripts, and other common project runners with live output pinned at the top of the terminal. Running app runners expose line-oriented stdin in the widget for interactive scripts. Projects can add browseable custom runners in `.pi-webui-runners.json` with a command (default `./`) plus a relative path to the file to run.
163
163
  - Guided Git workflow for existing repos and new repos with persistent model/reasoning preferences, review-first staging, an optional manual staged repository-review gate from `aur-review`, generated or typed commit messages, explicit push/PR confirmation, and optional PR worktrees. When the review extension is loaded/enabled, both `git add .` and accepting the current staged set send `/aur-review start --scope staged --origin guided-git` to the same tab. Only its matching approval advances to message generation. The browser and server recheck the approved domain-separated staged-content hash before message generation, commit, and PR-worktree transfer; drift, missing hashes, or hash-check errors return to Stage and require a new review. A decline returns to staging and rejects an unchanged declined staged hash until corrected content is restaged. Guided Git never stages, commits, or pushes remediation automatically. The extension remains the decision authority; direct API callers are not granted an approval by this browser workflow.
164
164
  - Browser support for Pi extension UI prompts, widgets, status updates, `/btw` side-question output widgets with optional context transfer/live steering, browser notifications when a tab needs an extension UI response, and an optional side-panel toggle for agent-done notifications.
@@ -231,7 +231,7 @@ These screenshots show the v0.4.8 Web UI surfaces. Current implementations inclu
231
231
  ![Pi Web UI app runner selector showing detected project runners and custom runner creation](https://raw.githubusercontent.com/Firstp1ck/npm-packages/main/pi-package-webui/images/Webui_AppRunner_v0.4.8.png)
232
232
 
233
233
  - **What it is:** A project runner detector for common stacks plus browseable custom runners from `.pi-webui-runners.json`.
234
- - **What you can do:** Launch dev servers, tests, builds, scripts, and custom commands from the active cwd, pass arguments, watch pinned live output, and send line-oriented stdin to interactive runners.
234
+ - **What you can do:** Launch dev servers, tests, builds, scripts, and custom commands from the active cwd, pass arguments, watch pinned live output, and send line-oriented stdin to interactive runners. Windows runners use ConPTY through the optional `node-pty` dependency so Bash/Node scripts receive a real TTY; set `PI_WEBUI_APP_RUNNER_PTY=off` to force the pipe fallback.
235
235
 
236
236
  ### Queue manager
237
237
 
@@ -404,7 +404,7 @@ For an existing repository, the workflow can:
404
404
  1. Show staged, unstaged, untracked, and fetched incoming changes.
405
405
  2. Fast-forward pull fetched incoming commits when the repository is safely behind.
406
406
  3. Review/select files, preserve a non-empty staged set, or explicitly opt into `git add .`.
407
- 4. Generate `/git-staged-msg` with the configured model, supported reasoning effort, language, and scope policy, then restore the tab's prior model/effort.
407
+ 4. Generate `/git-staged-msg` with the configured model, supported reasoning effort, language, and scope policy, then restore the tab's prior model/effort. Each request is correlated to its originating tab and a before-generation snapshot of both message files; the browser advances only when both non-empty files are fresh and stable for that exact generation.
408
408
  5. Use the preferred generated short/long message, a generated single-file default such as `updated file.txt`, or a manual **Commit input** message.
409
409
  6. Show an optional pre-commit verification reminder, then require explicit confirmation before push and PR delivery actions.
410
410
 
@@ -420,7 +420,7 @@ If the configured model or effort is unavailable, generation stops and asks you
420
420
 
421
421
  After the message is generated, **Create PR** asks Pi to generate `dev/COMMIT/staged-branch-name.txt`, lets you confirm or edit the `type/feature-name` branch, then switches with `git switch -c` before committing. In PR mode, choose **Commit short**, **Commit long**, or type a message and use **Commit input**, then **Push and Create PR** pushes the branch, sends `/pr`, shows the generated `dev/PR/<branch>.md` description for editing/confirmation, and creates the pull request with `gh pr create`. Use **Manual branch** to skip agent branch-name generation and type the branch directly.
422
422
 
423
- Use the workflow process buttons to jump directly to **Initialize**, **Stage**, **Message**, **Commit**, **Push**, or PR steps when earlier work was already completed manually. Selecting **Message** lets you either run `/git-staged-msg` or type a commit message and use **Commit input** directly. Selecting **Commit** loads the current generated files from `dev/COMMIT/` before enabling the commit choices. A yellow dot means that process was selected or is available but its action has not completed in this workflow; green means the process action completed.
423
+ Use the workflow process buttons to jump directly to **Initialize**, **Stage**, **Message**, **Commit**, **Push**, or PR steps when earlier work was already completed manually. Selecting **Message** lets you either run `/git-staged-msg` or type a commit message and use **Commit input** directly. Selecting **Commit** loads the current generated files from `dev/COMMIT/` before enabling the commit choices. Manual preview remains available for existing files, while an active generation uses bounded single-flight polling so duplicate timer, reconnect, and `agent_end` signals cannot race or surface a stale pair. A yellow dot means that process was selected or is available but its action has not completed in this workflow; green means the process action completed.
424
424
 
425
425
  This requires `/git-staged-msg` and `/pr` from `@firstpick/pi-prompts-git-pr`; branch-name generation uses `/git-branch-name`. Creating the PR also requires an authenticated GitHub CLI (`gh`). Review the generated commit message, branch name, remote URL, and PR description before committing, pushing, or creating a PR.
426
426
 
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);
@@ -1484,13 +1490,13 @@ function latestEvents(limit = 40) {
1484
1490
  return eventHistory.slice(-Math.max(0, Math.min(EVENT_HISTORY_LIMIT, limit)));
1485
1491
  }
1486
1492
 
1487
- function runCommand(command, args, { cwd, timeoutMs = 2000, maxOutputLength = 20000 } = {}) {
1493
+ function runCommand(command, args, { cwd, timeoutMs = 2000, maxOutputLength = 20000, env = {} } = {}) {
1488
1494
  return new Promise((resolve) => {
1489
1495
  const child = spawn(command, args, {
1490
1496
  cwd,
1491
1497
  // LC_ALL=C keeps tool output in English so error classification works
1492
1498
  // regardless of locale.
1493
- env: { ...process.env, LC_ALL: "C" },
1499
+ env: { ...process.env, ...env, LC_ALL: "C" },
1494
1500
  stdio: ["ignore", "pipe", "pipe"],
1495
1501
  windowsHide: true,
1496
1502
  });
@@ -2098,6 +2104,23 @@ async function restoreGitWorkflowGenerationProfile(tab) {
2098
2104
  }
2099
2105
  }
2100
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
+
2101
2124
  async function startGitWorkflowGeneration(tab, body = {}) {
2102
2125
  if (tab.gitWorkflowGenerationRestore) throw makeHttpError(409, "A guided Git generation request is already active in this tab");
2103
2126
  // Browser state is untrusted. When it claims an approved content token,
@@ -2105,6 +2128,8 @@ async function startGitWorkflowGeneration(tab, body = {}) {
2105
2128
  await assertExpectedStagedContentHash(tab, body);
2106
2129
  const preferences = await readGitWorkflowPreferences();
2107
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);
2108
2133
 
2109
2134
  const state = await currentSessionState(tab);
2110
2135
  if (stateIsBusyForSettings(state)) throw makeHttpError(409, "Wait for the current agent run to finish before generating Git text");
@@ -2117,7 +2142,10 @@ async function startGitWorkflowGeneration(tab, body = {}) {
2117
2142
  }
2118
2143
 
2119
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;
2120
2147
  tab.gitWorkflowGenerationRestore = restore;
2148
+ if (messageGeneration) tab.gitWorkflowMessageGeneration = messageGeneration;
2121
2149
  try {
2122
2150
  if (gitWorkflowModelKey(state.model) !== gitWorkflowModelKey(selectedModel)) {
2123
2151
  const modelResponse = await tab.rpc.send({ type: "set_model", provider: selectedModel.provider, modelId: selectedModel.id });
@@ -2126,8 +2154,6 @@ async function startGitWorkflowGeneration(tab, body = {}) {
2126
2154
  const thinkingResponse = await setThinkingLevelForTab(tab, preferences.generation.thinkingLevel, { allowPending: false });
2127
2155
  if (thinkingResponse.success === false) throw new Error(thinkingResponse.error || `Failed to select thinking level ${preferences.generation.thinkingLevel}`);
2128
2156
 
2129
- const kind = String(body.kind || "").trim();
2130
- const message = gitWorkflowGenerationPrompt(kind, preferences);
2131
2157
  markTabWorking(tab);
2132
2158
  const response = await tab.rpc.send({ type: "prompt", message });
2133
2159
  if (response.success === false) throw new Error(response.error || "Guided Git generation prompt was rejected");
@@ -2135,6 +2161,7 @@ async function startGitWorkflowGeneration(tab, body = {}) {
2135
2161
  accepted: true,
2136
2162
  kind,
2137
2163
  message,
2164
+ generationId: messageGeneration?.id || "",
2138
2165
  generation: {
2139
2166
  provider: selectedModel.provider,
2140
2167
  modelId: selectedModel.id,
@@ -2142,6 +2169,9 @@ async function startGitWorkflowGeneration(tab, body = {}) {
2142
2169
  },
2143
2170
  };
2144
2171
  } catch (error) {
2172
+ if (messageGeneration && tab.gitWorkflowMessageGeneration?.id === messageGeneration.id) {
2173
+ tab.gitWorkflowMessageGeneration = previousMessageGeneration;
2174
+ }
2145
2175
  markTabIdle(tab);
2146
2176
  await restoreGitWorkflowGenerationProfile(tab);
2147
2177
  throw error;
@@ -2169,6 +2199,7 @@ async function readJsonFileIfExists(filePath) {
2169
2199
 
2170
2200
  const appRunnerCommandAvailability = new Map();
2171
2201
  let appRunnerPtyScriptAvailability = { available: false, expiresAt: 0 };
2202
+ let appRunnerNodePtyPromise = null;
2172
2203
 
2173
2204
  async function fileStatsIfExists(filePath) {
2174
2205
  try {
@@ -2228,6 +2259,40 @@ function appRunnerPtyDisabled() {
2228
2259
  return APP_RUNNER_PTY_DISABLED_VALUES.has(String(process.env.PI_WEBUI_APP_RUNNER_PTY || "").trim().toLowerCase());
2229
2260
  }
2230
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
+
2231
2296
  async function appRunnerScriptPtyAvailable(cwd) {
2232
2297
  if (process.platform === "win32" || appRunnerPtyDisabled()) return false;
2233
2298
  const now = Date.now();
@@ -2289,6 +2354,19 @@ async function spawnAppRunnerChild(run) {
2289
2354
  windowsHide: true,
2290
2355
  detached: process.platform !== "win32",
2291
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
+ }
2292
2370
  if (await appRunnerScriptPtyAvailable(run.cwd)) {
2293
2371
  run.executionMode = "pty";
2294
2372
  return spawn("script", [
@@ -3186,18 +3264,34 @@ function scheduleAppRunnerBroadcast(tab) {
3186
3264
  }, 120);
3187
3265
  }
3188
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
+
3189
3273
  function terminateAppRunnerChild(run, signal = "SIGTERM") {
3190
- if (!run?.child || run.child.exitCode !== null || run.child.signalCode !== null) return false;
3274
+ if (!appRunnerChildActive(run)) return false;
3191
3275
  return terminateProcessTree(run.child, signal);
3192
3276
  }
3193
3277
 
3194
3278
  function appRunnerStdinWritable(run) {
3195
- const stdin = run?.child?.stdin;
3196
- 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;
3197
3283
  }
3198
3284
 
3199
3285
  function interruptAppRunnerChild(run) {
3200
- 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
+ }
3201
3295
  // Writing ETX to a Windows pipe is data, not a console Ctrl+C event. Kill the
3202
3296
  // complete tree there so npm/bash wrappers cannot leave orphaned servers.
3203
3297
  if (process.platform === "win32") return terminateAppRunnerChild(run, "SIGKILL");
@@ -3222,6 +3316,14 @@ function finishAppRunner(tab, run, patch = {}) {
3222
3316
  run.signal = patch.signal;
3223
3317
  run.error = patch.error;
3224
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 = [];
3225
3327
  run.child = null;
3226
3328
  run.stdinClosed = true;
3227
3329
  run.stopping = false;
@@ -3243,19 +3345,26 @@ function normalizeAppRunnerInputText(value) {
3243
3345
  function sendAppRunnerInput(tab, value, { appendNewline = true, closeStdin = false } = {}) {
3244
3346
  const run = tab?.appRunner;
3245
3347
  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");
3348
+ if (!appRunnerStdinWritable(run)) throw makeHttpError(409, "App runner stdin is closed");
3248
3349
  const text = normalizeAppRunnerInputText(value);
3249
- const chunk = `${text}${appendNewline === false ? "" : "\n"}`;
3350
+ const newline = run.executionMode === "conpty" && process.platform === "win32" ? "\r" : "\n";
3351
+ const chunk = `${text}${appendNewline === false ? "" : newline}`;
3250
3352
  if (!chunk && !closeStdin) throw makeHttpError(400, "App runner input is empty");
3251
3353
  let buffered = false;
3252
3354
  try {
3253
- if (closeStdin) {
3254
- if (chunk) stdin.end(chunk, "utf8");
3255
- else stdin.end();
3256
- 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;
3257
3359
  } else {
3258
- 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
+ }
3259
3368
  }
3260
3369
  } catch (error) {
3261
3370
  run.stdinClosed = true;
@@ -3301,22 +3410,29 @@ async function startAppRunner(tab, runnerId) {
3301
3410
  run.pid = child.pid;
3302
3411
  tab.appRunner = run;
3303
3412
 
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 }));
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
+ }
3320
3436
 
3321
3437
  recordEvent({ type: "webui_app_runner_start", tabId: tab.id, tabTitle: tab.title, command: run.displayCommand, cwd: run.cwd, pid: run.pid });
3322
3438
  broadcastAppRunnerState(tab);
@@ -3327,7 +3443,9 @@ function stopAppRunnerForTab(tab, reason = "stop requested", { force = false } =
3327
3443
  const run = tab?.appRunner;
3328
3444
  if (!run || run.status !== "running") return false;
3329
3445
  run.stopping = true;
3330
- 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"}`;
3331
3449
  appendAppRunnerLine(run, `# ${reason}; ${action}`);
3332
3450
  if (force) terminateAppRunnerChild(run, "SIGKILL");
3333
3451
  else interruptAppRunnerChild(run);
@@ -4505,7 +4623,14 @@ async function getGitRoot(cwd) {
4505
4623
  }
4506
4624
 
4507
4625
  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 });
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
+ });
4509
4634
  if (result.exitCode === 0 && !result.timedOut && !result.error) {
4510
4635
  return { output: result.stdout, truncated: result.stdoutTruncated === true, capBytes: maxOutputLength };
4511
4636
  }
@@ -5839,35 +5964,73 @@ async function readGitWorkflowBranchName(cwd) {
5839
5964
  }
5840
5965
  }
5841
5966
 
5842
- 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 } = {}) {
5843
5989
  const root = await getGitRoot(cwd);
5844
5990
  const messageCwd = gitWorkflowMessageCwd(root, cwd);
5845
- 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
+ }
5846
5995
  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);
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);
5855
6014
  return {
6015
+ ready: true,
6016
+ generationId,
5856
6017
  root,
5857
6018
  cwd: messageCwd,
5858
- shortPath,
5859
- longPath,
6019
+ shortPath: paths.shortPath,
6020
+ longPath: paths.longPath,
5860
6021
  shortRelativePath: shortFile.relativePath,
5861
6022
  longRelativePath: longFile.relativePath,
5862
6023
  shortRepoRelativePath: shortFile.repoRelativePath,
5863
6024
  longRepoRelativePath: longFile.repoRelativePath,
5864
- short: shortText.trimEnd(),
5865
- long: longText.trimEnd(),
5866
- shortMtimeMs: shortStat.mtimeMs,
5867
- 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,
5868
6031
  };
5869
6032
  } catch (error) {
5870
- 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)}`);
5871
6034
  }
5872
6035
  }
5873
6036
 
@@ -6611,8 +6774,11 @@ async function handleGitWorkflowRequest(pathname, body = {}, tabOrCwd = options.
6611
6774
  case "/api/git-workflow/staged-content":
6612
6775
  if (!tab) throw new Error("Staged-content lookup requires a Web UI tab");
6613
6776
  return { ok: true, data: await stagedContentHashForTab(tab) };
6614
- case "/api/git-workflow/message":
6615
- 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
+ }
6616
6782
  case "/api/git-workflow/default-commit-message":
6617
6783
  return { ok: true, data: await readGitWorkflowDefaultCommitMessage(cwd) };
6618
6784
  case "/api/git-workflow/branch-name":
@@ -6937,11 +7103,21 @@ function stripDataUrlPrefix(data) {
6937
7103
  return comma === -1 ? text : text.slice(comma + 1);
6938
7104
  }
6939
7105
 
6940
- function decodeAttachmentData(data) {
7106
+ function decodeCanonicalBase64(data, label) {
6941
7107
  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");
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;
6945
7121
  }
6946
7122
 
6947
7123
  async function saveUploadedAttachments(body) {
@@ -6985,13 +7161,10 @@ function normalizeRpcImages(value) {
6985
7161
  let totalBytes = 0;
6986
7162
  for (const [index, image] of value.entries()) {
6987
7163
  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;
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;
6995
7168
  if (totalBytes > INLINE_IMAGE_TOTAL_MAX_BYTES) throw new Error(`inline images exceed ${formatBytes(INLINE_IMAGE_TOTAL_MAX_BYTES)} total`);
6996
7169
  images.push({ type: "image", data, mimeType });
6997
7170
  }
@@ -8229,6 +8402,7 @@ function attachRpcToTab(tab, rpc) {
8229
8402
  let scopedEvent = eventForTabClients(tab, event);
8230
8403
  if (event?.type === "pi_process_exit" || event?.type === "pi_process_error") {
8231
8404
  tab.gitWorkflowGenerationRestore = null;
8405
+ tab.gitWorkflowMessageGeneration = null;
8232
8406
  clearPendingExtensionUiRequests(tab);
8233
8407
  clearExtensionStatuses(tab);
8234
8408
  clearExtensionWidgets(tab);
@@ -8275,6 +8449,7 @@ async function createTab({ id: requestedId, index, title, titleSource, conversat
8275
8449
  lastState: null,
8276
8450
  pendingThinkingLevel: undefined,
8277
8451
  gitWorkflowGenerationRestore: null,
8452
+ gitWorkflowMessageGeneration: null,
8278
8453
  activity: createTabActivity(createdAt),
8279
8454
  pendingExtensionUiRequests: new Map(),
8280
8455
  extensionStatuses: new Map(),
@@ -8300,6 +8475,7 @@ async function createTab({ id: requestedId, index, title, titleSource, conversat
8300
8475
  } catch (error) {
8301
8476
  if (!tab.rpc.isRunning()) {
8302
8477
  tab.rpcUnsubscribe?.();
8478
+ gitLiveWatcher.unsubscribe(id);
8303
8479
  tabs.delete(id);
8304
8480
  throw new Error(`Pi RPC process failed while starting ${tabTitle}: ${sanitizeError(error)}`);
8305
8481
  }
@@ -9059,6 +9235,22 @@ function broadcastServerEvent(event) {
9059
9235
  for (const client of clients) sendSse(client, event);
9060
9236
  }
9061
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
+
9062
9254
  function renameTab(tab, title, { source = "explicit", maxLength, unique = source === "auto" } = {}) {
9063
9255
  if (!tab) return false;
9064
9256
  const rawTitle = maxLength ? truncateTabTitle(title, maxLength) : String(title || "").replace(/\s+/g, " ").trim();
@@ -9112,6 +9304,7 @@ async function updateTabCwd(id, cwd) {
9112
9304
  const piArgs = await buildPiArgsForTab(tab.index, tab.title, nextCwd);
9113
9305
  if (sessionFile && !options.noSession) piArgs.push("--session", sessionFile);
9114
9306
  const piCommand = await resolvePiCommand(piArgs);
9307
+ gitLiveWatcher.unsubscribe(tab.id);
9115
9308
  const restartingEvent = { type: "webui_tab_restarting", tabId: tab.id, tabTitle: tab.title, cwd: nextCwd, sessionFile };
9116
9309
  recordEvent(restartingEvent);
9117
9310
  for (const client of tab.sseClients) {
@@ -11283,6 +11476,7 @@ async function closeTab(id) {
11283
11476
  if (stateResult.ok) restorableState = stateResult.data;
11284
11477
  }
11285
11478
  rememberClosedRestorableTab(tab, restorableState);
11479
+ gitLiveWatcher.unsubscribe(tab.id);
11286
11480
 
11287
11481
  const closingEvent = { type: "webui_tab_closing", tabId: tab.id, tabTitle: tab.title };
11288
11482
  recordEvent(closingEvent);
@@ -11301,6 +11495,7 @@ async function closeTab(id) {
11301
11495
 
11302
11496
  async function discardTab(tab) {
11303
11497
  if (!tab || !tabs.has(tab.id)) return;
11498
+ gitLiveWatcher.unsubscribe(tab.id);
11304
11499
  tab.rpcUnsubscribe?.();
11305
11500
  rejectTabBashQueue(tab, new Error("Pi recovery tab initialization failed"));
11306
11501
  stopAppRunnerForTab(tab, "recovery initialization failed", { force: true });
@@ -12635,7 +12830,8 @@ const server = createServer(async (req, res) => {
12635
12830
  if (url.pathname === "/api/git-root" && req.method === "GET") {
12636
12831
  const tab = getRequestedTab(req, url);
12637
12832
  try {
12638
- sendJson(res, 200, { ok: true, data: { cwd: tab.cwd, root: await getGitRoot(tab.cwd) } });
12833
+ const root = trackGitRepositoryForTab(tab, await getGitRoot(tab.cwd));
12834
+ sendJson(res, 200, { ok: true, data: { cwd: tab.cwd, root } });
12639
12835
  } catch (error) {
12640
12836
  sendJson(res, 200, { ok: false, error: sanitizeError(error) });
12641
12837
  }
@@ -12645,7 +12841,9 @@ const server = createServer(async (req, res) => {
12645
12841
  if (url.pathname === "/api/git-panel" && req.method === "GET") {
12646
12842
  const tab = getRequestedTab(req, url);
12647
12843
  try {
12648
- sendJson(res, 200, { ok: true, data: await readGitPanel(tab.cwd) });
12844
+ const data = await readGitPanel(tab.cwd);
12845
+ trackGitRepositoryForTab(tab, data.root);
12846
+ sendJson(res, 200, { ok: true, data });
12649
12847
  } catch (error) {
12650
12848
  sendJson(res, 200, { ok: false, error: sanitizeError(error) });
12651
12849
  }
@@ -12831,7 +13029,7 @@ const server = createServer(async (req, res) => {
12831
13029
  sendJson(res, 405, { ok: false, error: `${url.pathname} requires ${requiredMethod}` });
12832
13030
  return;
12833
13031
  }
12834
- const body = mutatingWorkflow ? await readJsonBody(req) : {};
13032
+ const body = mutatingWorkflow ? await readJsonBody(req) : { generationId: url.searchParams.get("generationId") || "" };
12835
13033
  const tab = getRequestedTab(req, url, body);
12836
13034
  if (mutatingWorkflow) ensureNaturalConversationRouteAllowed(tab, "git workflow actions are blocked");
12837
13035
  const response = await handleGitWorkflowRequest(url.pathname, body, tab);
@@ -12963,6 +13161,7 @@ server.listen(options.port, currentHost, () => {
12963
13161
 
12964
13162
  function shutdown(signal) {
12965
13163
  console.log(`\n${signal}: shutting down Pi Web UI...`);
13164
+ gitLiveWatcher.closeAll();
12966
13165
  const forceCloseTimer = setTimeout(() => {
12967
13166
  server.closeAllConnections?.();
12968
13167
  }, NETWORK_REBIND_FORCE_CLOSE_MS);