@firstpick/pi-package-webui 0.5.7 → 0.5.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/pi-webui.mjs CHANGED
@@ -192,6 +192,8 @@ const APP_RUNNER_INPUT_MAX_CHARS = 16_000;
192
192
  const APP_RUNNER_CONTEXT_DEFAULT_LINES = 80;
193
193
  const APP_RUNNER_CONTEXT_MAX_LINES = APP_RUNNER_OUTPUT_LINE_LIMIT;
194
194
  const APP_RUNNER_STOP_GRACE_MS = 2_500;
195
+ const APP_RUNNER_PTY_DISABLED_VALUES = new Set(["0", "false", "no", "off"]);
196
+ const APP_RUNNER_PTY_SCRIPT_CACHE_TTL_MS = 5 * 60 * 1000;
195
197
  const APP_RUNNER_PYTHON_ENTRIES = ["Main.py", "main.py", "src/main.py", "src/Main.py", "app.py", "src/app.py"];
196
198
  const APP_RUNNER_JS_ENTRIES = ["main.js", "src/main.js", "index.js", "src/index.js", "server.js", "src/server.js", "app.js", "src/app.js"];
197
199
  const APP_RUNNER_ZIG_ENTRIES = ["src/main.zig", "main.zig"];
@@ -236,6 +238,7 @@ const unavailableNative = (command, details = {}) => nativeCommandUnavailable(co
236
238
  function parseSlashCommand(message) {
237
239
  return parseNativeSlashCommand(message, NATIVE_SLASH_COMMAND_NAMES);
238
240
  }
241
+ const NATURAL_CONVERSATION_FEATURE_ID = "naturalConversation";
239
242
  const OPTIONAL_FEATURE_PACKAGES = new Map([
240
243
  ["btwCommand", "@firstpick/pi-extension-btw"],
241
244
  ["gitWorkflow", "@firstpick/pi-prompts-git-pr"],
@@ -247,11 +250,19 @@ const OPTIONAL_FEATURE_PACKAGES = new Map([
247
250
  ["todoProgressWidget", "@firstpick/pi-extension-todo-progress"],
248
251
  ["tuiToolsCommand", "@firstpick/pi-extension-tools"],
249
252
  ["remoteWebui", "@firstpick/pi-package-remote-webui"],
253
+ ["naturalConversation", "@firstpick/pi-package-natural-conversation"],
250
254
  ["gitFooterStatus", "@firstpick/pi-extension-git-footer-status"],
251
255
  ["statsCommand", "@firstpick/pi-extension-stats"],
252
256
  ["themeBundle", "@firstpick/pi-themes-bundle"],
253
257
  ]);
254
- const WEBUI_CONTROLLED_PACKAGES = new Set([WEBUI_PACKAGE, ...OPTIONAL_FEATURE_PACKAGES.values()]);
258
+ const WEBUI_CONTROLLED_PACKAGES = new Set([
259
+ WEBUI_PACKAGE,
260
+ ...[...OPTIONAL_FEATURE_PACKAGES.entries()]
261
+ .filter(([featureId]) => featureId !== NATURAL_CONVERSATION_FEATURE_ID)
262
+ .map(([, packageName]) => packageName),
263
+ ]);
264
+ const NATURAL_CONVERSATION_STATUS_KEY = "natural-conversation";
265
+ const NATURAL_CONVERSATION_COMMAND_NAMES = ["talk", "voice", "conversation"];
255
266
  const PACKAGE_NAME_CACHE = new Map();
256
267
 
257
268
  function usage() {
@@ -1117,6 +1128,31 @@ function nodeModulesParentForPackageRoot(root = packageRoot) {
1117
1128
  return root;
1118
1129
  }
1119
1130
 
1131
+ function prependNodePathEntries(entries) {
1132
+ const existing = String(process.env.NODE_PATH || "").split(path.delimiter).filter(Boolean);
1133
+ const seen = new Set();
1134
+ const next = [];
1135
+ for (const entry of [...entries, ...existing]) {
1136
+ if (!entry) continue;
1137
+ const normalized = path.resolve(entry);
1138
+ const key = process.platform === "win32" ? normalized.toLowerCase() : normalized;
1139
+ if (seen.has(key)) continue;
1140
+ seen.add(key);
1141
+ next.push(normalized);
1142
+ }
1143
+ if (next.length) process.env.NODE_PATH = next.join(path.delimiter);
1144
+ }
1145
+
1146
+ async function configureDevDependencyResolution() {
1147
+ if (!webuiDevServer) return;
1148
+ const workspaceRoot = await devWorkspaceRoot();
1149
+ prependNodePathEntries([
1150
+ workspaceRoot ? path.join(workspaceRoot, "node_modules") : "",
1151
+ path.join(packageRoot, "node_modules"),
1152
+ path.join(configuredAgentNpmRoot(), "node_modules"),
1153
+ ]);
1154
+ }
1155
+
1120
1156
  function declaredDependencySpec(pkg, packageName) {
1121
1157
  return firstDefined(
1122
1158
  pkg?.dependencies?.[packageName],
@@ -1449,6 +1485,7 @@ async function readJsonFileIfExists(filePath) {
1449
1485
  }
1450
1486
 
1451
1487
  const appRunnerCommandAvailability = new Map();
1488
+ let appRunnerPtyScriptAvailability = { available: false, expiresAt: 0 };
1452
1489
 
1453
1490
  async function fileStatsIfExists(filePath) {
1454
1491
  try {
@@ -1504,6 +1541,25 @@ async function appRunnerCommandAvailable(command, cwd) {
1504
1541
  return available;
1505
1542
  }
1506
1543
 
1544
+ function appRunnerPtyDisabled() {
1545
+ return APP_RUNNER_PTY_DISABLED_VALUES.has(String(process.env.PI_WEBUI_APP_RUNNER_PTY || "").trim().toLowerCase());
1546
+ }
1547
+
1548
+ async function appRunnerScriptPtyAvailable(cwd) {
1549
+ if (process.platform === "win32" || appRunnerPtyDisabled()) return false;
1550
+ const now = Date.now();
1551
+ if (appRunnerPtyScriptAvailability.expiresAt > now) return appRunnerPtyScriptAvailability.available;
1552
+ const result = await runCommand("script", ["--version"], {
1553
+ cwd,
1554
+ timeoutMs: APP_RUNNER_DETECTION_TIMEOUT_MS,
1555
+ maxOutputLength: 4_000,
1556
+ });
1557
+ const output = `${result.stdout || ""}\n${result.stderr || ""}`;
1558
+ const available = !result.error && !result.timedOut && /util-linux/i.test(output);
1559
+ appRunnerPtyScriptAvailability = { available, expiresAt: now + APP_RUNNER_PTY_SCRIPT_CACHE_TTL_MS };
1560
+ return available;
1561
+ }
1562
+
1507
1563
  function appRunnerPackageScripts(pkg) {
1508
1564
  return pkg && typeof pkg.scripts === "object" && pkg.scripts ? pkg.scripts : {};
1509
1565
  }
@@ -1538,6 +1594,41 @@ function shellQuote(value) {
1538
1594
  return `'${String(value ?? "").replace(/'/g, `'\\''`)}'`;
1539
1595
  }
1540
1596
 
1597
+ function appRunnerShellCommandLine(command, args = []) {
1598
+ return [command, ...args].map(shellQuote).join(" ");
1599
+ }
1600
+
1601
+ async function spawnAppRunnerChild(run) {
1602
+ const baseOptions = {
1603
+ cwd: run.cwd,
1604
+ env: process.env,
1605
+ stdio: ["pipe", "pipe", "pipe"],
1606
+ windowsHide: true,
1607
+ detached: process.platform !== "win32",
1608
+ };
1609
+ if (await appRunnerScriptPtyAvailable(run.cwd)) {
1610
+ run.executionMode = "pty";
1611
+ return spawn("script", [
1612
+ "-q",
1613
+ "-e",
1614
+ "-f",
1615
+ "-c",
1616
+ `stty -echo 2>/dev/null || true; exec ${appRunnerShellCommandLine(run.command, run.args || [])}`,
1617
+ "/dev/null",
1618
+ ], {
1619
+ ...baseOptions,
1620
+ env: {
1621
+ ...process.env,
1622
+ TERM: process.env.TERM || "xterm-256color",
1623
+ COLUMNS: process.env.COLUMNS || "120",
1624
+ LINES: process.env.LINES || "40",
1625
+ },
1626
+ });
1627
+ }
1628
+ run.executionMode = "pipe";
1629
+ return spawn(run.command, run.args || [], baseOptions);
1630
+ }
1631
+
1541
1632
  function appRunnerCandidate({ id, label, kind, command, args = [], projectFile = "", description = "", shortDisplayCommand = "", priority = 100, cwd = "", custom = false, configFile = "" }) {
1542
1633
  return {
1543
1634
  id,
@@ -2322,6 +2413,7 @@ function publicAppRunnerState(run) {
2322
2413
  cwd: run.cwd,
2323
2414
  pid: run.pid,
2324
2415
  status: run.status,
2416
+ executionMode: run.executionMode || "pipe",
2325
2417
  startedAt: run.startedAt,
2326
2418
  endedAt: run.endedAt,
2327
2419
  exitCode: run.exitCode,
@@ -2412,7 +2504,7 @@ function scheduleAppRunnerBroadcast(tab) {
2412
2504
  }
2413
2505
 
2414
2506
  function terminateAppRunnerChild(run, signal = "SIGTERM") {
2415
- if (!run?.child || run.child.killed) return false;
2507
+ if (!run?.child || run.child.exitCode !== null || run.child.signalCode !== null) return false;
2416
2508
  try {
2417
2509
  if (process.platform !== "win32" && run.pid) process.kill(-run.pid, signal);
2418
2510
  else run.child.kill(signal);
@@ -2427,6 +2519,24 @@ function terminateAppRunnerChild(run, signal = "SIGTERM") {
2427
2519
  }
2428
2520
  }
2429
2521
 
2522
+ function appRunnerStdinWritable(run) {
2523
+ const stdin = run?.child?.stdin;
2524
+ return !!stdin && !stdin.destroyed && !stdin.writableEnded && run.stdinClosed !== true;
2525
+ }
2526
+
2527
+ function interruptAppRunnerChild(run) {
2528
+ if (!run?.child || run.child.exitCode !== null || run.child.signalCode !== null) return false;
2529
+ if (appRunnerStdinWritable(run) && (run.executionMode === "pty" || process.platform === "win32")) {
2530
+ try {
2531
+ run.child.stdin.write("\x03", "utf8");
2532
+ return true;
2533
+ } catch {
2534
+ // Fall back to process signals below.
2535
+ }
2536
+ }
2537
+ return terminateAppRunnerChild(run, "SIGINT");
2538
+ }
2539
+
2430
2540
  function finishAppRunner(tab, run, patch = {}) {
2431
2541
  if (!run || run.settled) return;
2432
2542
  run.settled = true;
@@ -2511,13 +2621,7 @@ async function startAppRunner(tab, runnerId) {
2511
2621
  stdinWrites: 0,
2512
2622
  };
2513
2623
  appendAppRunnerLine(run, `$ ${run.displayCommand}`);
2514
- const child = spawn(run.command, run.args, {
2515
- cwd: run.cwd,
2516
- env: process.env,
2517
- stdio: ["pipe", "pipe", "pipe"],
2518
- windowsHide: true,
2519
- detached: process.platform !== "win32",
2520
- });
2624
+ const child = await spawnAppRunnerChild(run);
2521
2625
  run.child = child;
2522
2626
  run.pid = child.pid;
2523
2627
  tab.appRunner = run;
@@ -2548,13 +2652,14 @@ function stopAppRunnerForTab(tab, reason = "stop requested", { force = false } =
2548
2652
  const run = tab?.appRunner;
2549
2653
  if (!run || run.status !== "running") return false;
2550
2654
  run.stopping = true;
2551
- appendAppRunnerLine(run, `# ${reason}; sending ${force ? "SIGKILL" : "SIGTERM"}`);
2552
- terminateAppRunnerChild(run, force ? "SIGKILL" : "SIGTERM");
2655
+ appendAppRunnerLine(run, `# ${reason}; sending ${force ? "SIGKILL" : "Ctrl+C"}`);
2656
+ if (force) terminateAppRunnerChild(run, "SIGKILL");
2657
+ else interruptAppRunnerChild(run);
2553
2658
  if (!force) {
2554
2659
  clearTimeout(run.stopTimer);
2555
2660
  run.stopTimer = setTimeout(() => {
2556
2661
  if (run.status === "running") {
2557
- appendAppRunnerLine(run, "# app runner did not stop; sending SIGKILL");
2662
+ appendAppRunnerLine(run, "# app runner did not stop after Ctrl+C; sending SIGKILL");
2558
2663
  terminateAppRunnerChild(run, "SIGKILL");
2559
2664
  scheduleAppRunnerBroadcast(tab);
2560
2665
  }
@@ -3471,22 +3576,38 @@ async function readGitChanges(cwd) {
3471
3576
  };
3472
3577
  }
3473
3578
 
3474
- function commitMessagePaths(root) {
3579
+ function gitWorkflowMessageCwd(root, cwd) {
3580
+ const messageCwd = path.resolve(String(cwd || root));
3581
+ if (!pathInside(root, messageCwd)) throw new Error(`Git workflow cwd must stay inside repository root: ${messageCwd}`);
3582
+ return messageCwd;
3583
+ }
3584
+
3585
+ function gitWorkflowMessageFileMeta(root, messageCwd, filePath) {
3586
+ return {
3587
+ path: filePath,
3588
+ relativePath: path.relative(messageCwd, filePath).split(path.sep).join("/"),
3589
+ repoRelativePath: path.relative(root, filePath).split(path.sep).join("/"),
3590
+ };
3591
+ }
3592
+
3593
+ function commitMessagePaths(baseDir) {
3475
3594
  return {
3476
- shortPath: path.join(root, "dev", "COMMIT", "staged-commit-short.txt"),
3477
- longPath: path.join(root, "dev", "COMMIT", "staged-commit-long.txt"),
3478
- branchPath: path.join(root, "dev", "COMMIT", "staged-branch-name.txt"),
3595
+ shortPath: path.join(baseDir, "dev", "COMMIT", "staged-commit-short.txt"),
3596
+ longPath: path.join(baseDir, "dev", "COMMIT", "staged-commit-long.txt"),
3597
+ branchPath: path.join(baseDir, "dev", "COMMIT", "staged-branch-name.txt"),
3479
3598
  };
3480
3599
  }
3481
3600
 
3482
3601
  async function readGitWorkflowBranchName(cwd) {
3483
3602
  const root = await getGitRoot(cwd);
3484
- const { branchPath } = commitMessagePaths(root);
3603
+ const messageCwd = gitWorkflowMessageCwd(root, cwd);
3604
+ const { branchPath } = commitMessagePaths(messageCwd);
3485
3605
  try {
3486
3606
  const [branchText, branchStat] = await Promise.all([readFile(branchPath, "utf8"), stat(branchPath)]);
3487
3607
  const branch = branchText.split(/\r?\n/).find((line) => line.trim())?.trim() || "";
3488
3608
  if (!branch) throw new Error(`${branchPath} is empty`);
3489
- return { root, branchPath, branch, mtimeMs: branchStat.mtimeMs };
3609
+ const branchFile = gitWorkflowMessageFileMeta(root, messageCwd, branchPath);
3610
+ return { root, cwd: messageCwd, branchPath, branchRelativePath: branchFile.relativePath, branchRepoRelativePath: branchFile.repoRelativePath, branch, mtimeMs: branchStat.mtimeMs };
3490
3611
  } catch (error) {
3491
3612
  throw new Error(`Missing generated branch name file ${branchPath}. Run /git-branch-name first. ${sanitizeError(error)}`);
3492
3613
  }
@@ -3494,7 +3615,8 @@ async function readGitWorkflowBranchName(cwd) {
3494
3615
 
3495
3616
  async function readGitWorkflowMessages(cwd) {
3496
3617
  const root = await getGitRoot(cwd);
3497
- const { shortPath, longPath } = commitMessagePaths(root);
3618
+ const messageCwd = gitWorkflowMessageCwd(root, cwd);
3619
+ const { shortPath, longPath } = commitMessagePaths(messageCwd);
3498
3620
  try {
3499
3621
  const [shortText, longText, shortStat, longStat] = await Promise.all([
3500
3622
  readFile(shortPath, "utf8"),
@@ -3502,17 +3624,24 @@ async function readGitWorkflowMessages(cwd) {
3502
3624
  stat(shortPath),
3503
3625
  stat(longPath),
3504
3626
  ]);
3627
+ const shortFile = gitWorkflowMessageFileMeta(root, messageCwd, shortPath);
3628
+ const longFile = gitWorkflowMessageFileMeta(root, messageCwd, longPath);
3505
3629
  return {
3506
3630
  root,
3631
+ cwd: messageCwd,
3507
3632
  shortPath,
3508
3633
  longPath,
3634
+ shortRelativePath: shortFile.relativePath,
3635
+ longRelativePath: longFile.relativePath,
3636
+ shortRepoRelativePath: shortFile.repoRelativePath,
3637
+ longRepoRelativePath: longFile.repoRelativePath,
3509
3638
  short: shortText.trimEnd(),
3510
3639
  long: longText.trimEnd(),
3511
3640
  shortMtimeMs: shortStat.mtimeMs,
3512
3641
  longMtimeMs: longStat.mtimeMs,
3513
3642
  };
3514
3643
  } catch (error) {
3515
- throw new Error(`Missing generated commit message files in ${path.join(root, "dev", "COMMIT")}. Run /git-staged-msg first. ${sanitizeError(error)}`);
3644
+ throw new Error(`Missing generated commit message files in ${path.join(messageCwd, "dev", "COMMIT")}. Run /git-staged-msg first. ${sanitizeError(error)}`);
3516
3645
  }
3517
3646
  }
3518
3647
 
@@ -3938,8 +4067,8 @@ async function cleanupCreatedWorktreeAfterFailure(sourceCwd, worktreePath) {
3938
4067
  }
3939
4068
  }
3940
4069
 
3941
- async function readGitWorkflowMessageFilesForTransfer(root) {
3942
- const { shortPath, longPath } = commitMessagePaths(root);
4070
+ async function readGitWorkflowMessageFilesForTransfer(root, messageCwd = root) {
4071
+ const { shortPath, longPath } = commitMessagePaths(messageCwd);
3943
4072
  const files = [];
3944
4073
  for (const sourcePath of [shortPath, longPath]) {
3945
4074
  try {
@@ -3952,7 +4081,8 @@ async function readGitWorkflowMessageFilesForTransfer(root) {
3952
4081
  return files;
3953
4082
  }
3954
4083
 
3955
- async function snapshotGitWorkflowBranchState(root) {
4084
+ async function snapshotGitWorkflowBranchState(root, cwd = root) {
4085
+ const messageCwd = gitWorkflowMessageCwd(root, cwd);
3956
4086
  const diffResult = await runGitWorkflowCommand(["diff", "--cached", "--binary", "--full-index"], {
3957
4087
  cwd: root,
3958
4088
  label: "git diff --cached --binary --full-index",
@@ -3963,7 +4093,7 @@ async function snapshotGitWorkflowBranchState(root) {
3963
4093
  }
3964
4094
  return {
3965
4095
  stagedPatch: diffResult.stdout || "",
3966
- messageFiles: await readGitWorkflowMessageFilesForTransfer(root),
4096
+ messageFiles: await readGitWorkflowMessageFilesForTransfer(root, messageCwd),
3967
4097
  };
3968
4098
  }
3969
4099
 
@@ -4019,7 +4149,7 @@ async function createGitWorkflowBranchWorktree(tab, body = {}) {
4019
4149
  const root = await getGitRoot(tab.cwd);
4020
4150
  const branch = cleanGitBranchName(body.branch || body.branchName);
4021
4151
  await validateGitBranchName(root, branch);
4022
- const snapshot = await snapshotGitWorkflowBranchState(root);
4152
+ const snapshot = await snapshotGitWorkflowBranchState(root, tab.cwd);
4023
4153
  let createdResult = null;
4024
4154
  try {
4025
4155
  createdResult = await createGitWorktree(tab.cwd, { ...body, branchName: branch });
@@ -4724,6 +4854,7 @@ try {
4724
4854
 
4725
4855
  process.env.PI_WEBUI_HOST = options.host;
4726
4856
  process.env.PI_WEBUI_PORT = String(options.port);
4857
+ await configureDevDependencyResolution();
4727
4858
 
4728
4859
  const startupDelayMs = Number.parseInt(process.env.PI_WEBUI_START_DELAY_MS || "", 10);
4729
4860
  delete process.env.PI_WEBUI_START_DELAY_MS;
@@ -4994,9 +5125,19 @@ function rememberTabState(tab, state) {
4994
5125
  if (!options.noSession && Object.prototype.hasOwnProperty.call(state, "sessionFile")) tab.sessionFile = sessionFileFromState(state);
4995
5126
  }
4996
5127
 
5128
+ function patchTabState(tab, patch) {
5129
+ if (!tab || !patch || typeof patch !== "object") return;
5130
+ tab.lastState = { ...(tab.lastState || {}), ...patch };
5131
+ }
5132
+
4997
5133
  function stateWithPendingThinking(tab, state) {
4998
- if (!state || typeof state !== "object" || !tab?.pendingThinkingLevel) return state;
4999
- return { ...state, pendingThinkingLevel: tab.pendingThinkingLevel };
5134
+ if (!state || typeof state !== "object") return state;
5135
+ const queueLength = tab ? compactionQueueForTab(tab).length : 0;
5136
+ if (!tab?.pendingThinkingLevel && queueLength === 0) return state;
5137
+ const patch = {};
5138
+ if (tab?.pendingThinkingLevel) patch.pendingThinkingLevel = tab.pendingThinkingLevel;
5139
+ if (queueLength > 0) patch.pendingMessageCount = Number(state.pendingMessageCount || 0) + queueLength;
5140
+ return { ...state, ...patch };
5000
5141
  }
5001
5142
 
5002
5143
  function responseWithPendingThinking(tab, response) {
@@ -5090,6 +5231,96 @@ function clearExtensionWidgets(tab) {
5090
5231
  tab?.extensionWidgets?.clear();
5091
5232
  }
5092
5233
 
5234
+ function naturalConversationStatusState(statusText) {
5235
+ const text = stripAnsi(statusText).replace(/\s+/g, " ").trim();
5236
+ if (!text) return { enabled: false, uiState: "off", statusText: "" };
5237
+ const match = text.match(/voice\s*:\s*([a-z0-9_-]+)/i);
5238
+ return { enabled: true, uiState: (match?.[1] || "listening").toLowerCase(), statusText: text };
5239
+ }
5240
+
5241
+ function naturalConversationModeSnapshot(tab, patch = {}) {
5242
+ const previous = tab?.conversationMode && typeof tab.conversationMode === "object" ? tab.conversationMode : {};
5243
+ const status = naturalConversationStatusState(extensionStatusMap(tab).get(NATURAL_CONVERSATION_STATUS_KEY) || previous.statusText || "");
5244
+ const enabled = patch.enabled ?? status.enabled ?? previous.enabled ?? false;
5245
+ const uiState = patch.uiState || (enabled ? status.uiState || previous.uiState || "listening" : "off");
5246
+ return {
5247
+ featureId: NATURAL_CONVERSATION_FEATURE_ID,
5248
+ available: patch.available ?? previous.available ?? false,
5249
+ enabled,
5250
+ uiState,
5251
+ statusText: patch.statusText ?? status.statusText ?? previous.statusText ?? "",
5252
+ allowedTools: Array.isArray(patch.allowedTools) ? patch.allowedTools : Array.isArray(previous.allowedTools) ? previous.allowedTools : ["read", "grep", "find", "ls"],
5253
+ provider: patch.provider || previous.provider || "browser-shell",
5254
+ startedAt: patch.startedAt ?? previous.startedAt ?? null,
5255
+ packageInstalled: patch.packageInstalled ?? previous.packageInstalled ?? false,
5256
+ loadedCommands: Array.isArray(patch.loadedCommands) ? patch.loadedCommands : Array.isArray(previous.loadedCommands) ? previous.loadedCommands : [],
5257
+ updatedAt: patch.updatedAt || previous.updatedAt || new Date().toISOString(),
5258
+ };
5259
+ }
5260
+
5261
+ function resetNaturalConversationMode(tab) {
5262
+ if (!tab) return;
5263
+ tab.conversationMode = naturalConversationModeSnapshot(tab, { available: false, enabled: false, uiState: "off", statusText: "", loadedCommands: [] });
5264
+ }
5265
+
5266
+ function rememberNaturalConversationStatusEvent(tab, event) {
5267
+ if (event?.type !== "extension_ui_request" || event.method !== "setStatus" || event.statusKey !== NATURAL_CONVERSATION_STATUS_KEY) return;
5268
+ const status = naturalConversationStatusState(event.statusText || "");
5269
+ tab.conversationMode = naturalConversationModeSnapshot(tab, {
5270
+ ...status,
5271
+ available: true,
5272
+ loadedCommands: tab?.conversationMode?.loadedCommands?.length ? tab.conversationMode.loadedCommands : ["talk"],
5273
+ });
5274
+ }
5275
+
5276
+ function isNaturalConversationActive(tab) {
5277
+ return naturalConversationModeSnapshot(tab).enabled === true;
5278
+ }
5279
+
5280
+ function naturalConversationCommandBaseName(name) {
5281
+ return String(name || "").trim().toLowerCase().replace(/:\d+$/, "");
5282
+ }
5283
+
5284
+ function naturalConversationSlashCommandName(message) {
5285
+ const match = String(message || "").trim().match(/^\/([^\s]+)/);
5286
+ return match ? naturalConversationCommandBaseName(match[1]) : "";
5287
+ }
5288
+
5289
+ function isNaturalConversationSlashCommand(message) {
5290
+ return NATURAL_CONVERSATION_COMMAND_NAMES.includes(naturalConversationSlashCommandName(message));
5291
+ }
5292
+
5293
+ function blockNaturalConversationAction(action) {
5294
+ throw makeHttpError(409, `Natural Conversation Mode is active; ${action}. Leave the mode first with /talk off.`);
5295
+ }
5296
+
5297
+ function ensureNaturalConversationRouteAllowed(tab, action) {
5298
+ if (isNaturalConversationActive(tab)) blockNaturalConversationAction(action);
5299
+ }
5300
+
5301
+ async function ensureNaturalConversationPromptSafety(tab, command) {
5302
+ if (!isNaturalConversationActive(tab) || !["prompt", "steer", "follow_up"].includes(command?.type)) return null;
5303
+ tab.pendingThinkingLevel = undefined;
5304
+ const stateResult = await safeRpcData(tab, { type: "get_state" }, STATUS_RPC_TIMEOUT_MS);
5305
+ if (stateResult.ok && stateIsBusyForSettings(stateResult.data)) return null;
5306
+ const response = await setThinkingLevelForTab(tab, "off", { allowPending: false });
5307
+ return response?.success === false ? response : null;
5308
+ }
5309
+
5310
+ function enforceNaturalConversationCommandAllowed(tab, command) {
5311
+ if (!isNaturalConversationActive(tab)) return;
5312
+ if (command?.type === "set_thinking_level") {
5313
+ if (command.level !== "off") blockNaturalConversationAction("thinking is forced off");
5314
+ return;
5315
+ }
5316
+ if (!["prompt", "steer", "follow_up", "abort", "abort_bash"].includes(command?.type)) {
5317
+ blockNaturalConversationAction(`${command?.type || "this action"} is blocked`);
5318
+ }
5319
+ if (command?.type === "prompt" && naturalConversationSlashCommandName(command.message) && !isNaturalConversationSlashCommand(command.message)) {
5320
+ blockNaturalConversationAction("slash commands are blocked from the Web UI shell");
5321
+ }
5322
+ }
5323
+
5093
5324
  function replayExtensionStatuses(tab, res) {
5094
5325
  for (const [statusKey, statusText] of extensionStatusMap(tab)) {
5095
5326
  sendSse(res, {
@@ -5130,6 +5361,160 @@ function bashQueueForTab(tab) {
5130
5361
  return tab.bashQueue;
5131
5362
  }
5132
5363
 
5364
+ function compactionQueueForTab(tab) {
5365
+ if (!tab.compactionQueue) tab.compactionQueue = [];
5366
+ return tab.compactionQueue;
5367
+ }
5368
+
5369
+ function queueableCompactionCommand(command) {
5370
+ return ["prompt", "steer", "follow_up"].includes(command?.type) && !!String(command.message || "").trim();
5371
+ }
5372
+
5373
+ function compactionQueueMode(command) {
5374
+ if (command?.type === "follow_up" || command?.streamingBehavior === "followUp") return "followUp";
5375
+ return "steer";
5376
+ }
5377
+
5378
+ function compactQueuedCommand(command) {
5379
+ const queued = {
5380
+ type: command.type,
5381
+ message: String(command.message || ""),
5382
+ mode: compactionQueueMode(command),
5383
+ };
5384
+ if (Array.isArray(command.images) && command.images.length) queued.images = command.images;
5385
+ return queued;
5386
+ }
5387
+
5388
+ function compactionQueueEvent(tab, extra = {}) {
5389
+ const queue = compactionQueueForTab(tab);
5390
+ const steering = [];
5391
+ const followUp = [];
5392
+ for (const item of queue) {
5393
+ const message = String(item?.command?.message || "").trim();
5394
+ if (!message) continue;
5395
+ if (item.command.mode === "followUp") followUp.push(message);
5396
+ else steering.push(message);
5397
+ }
5398
+ return {
5399
+ type: "webui_compaction_queue_update",
5400
+ tabId: tab.id,
5401
+ tabTitle: tab.title,
5402
+ queueLength: queue.length,
5403
+ pendingMessageCount: queue.length,
5404
+ steering,
5405
+ followUp,
5406
+ draining: tab.compactionQueueDraining === true,
5407
+ tabActivity: tabActivitySnapshot(tab),
5408
+ ...extra,
5409
+ };
5410
+ }
5411
+
5412
+ function enqueueCommandUntilCompactionEnds(tab, command) {
5413
+ const queue = compactionQueueForTab(tab);
5414
+ const item = {
5415
+ id: randomUUID(),
5416
+ command: compactQueuedCommand(command),
5417
+ enqueuedAt: new Date().toISOString(),
5418
+ };
5419
+ queue.push(item);
5420
+ broadcastTabEvent(tab, compactionQueueEvent(tab, { queuedId: item.id }));
5421
+ return rpcSuccess(command.type, {
5422
+ queued: true,
5423
+ queuedFor: "compaction",
5424
+ queueLength: queue.length,
5425
+ message: "Prompt queued; Pi will resume automatically after compaction finishes.",
5426
+ });
5427
+ }
5428
+
5429
+ function maybeQueueCommandDuringCompaction(tab, command) {
5430
+ if (!queueableCompactionCommand(command)) return null;
5431
+ if (!tab?.lastState?.isCompacting) return null;
5432
+ return enqueueCommandUntilCompactionEnds(tab, command);
5433
+ }
5434
+
5435
+ function queuedPromptCommand(item) {
5436
+ const command = { type: "prompt", message: item.command.message };
5437
+ if (Array.isArray(item.command.images) && item.command.images.length) command.images = item.command.images;
5438
+ return command;
5439
+ }
5440
+
5441
+ function queuedStreamingCommand(item) {
5442
+ const command = {
5443
+ type: item.command.mode === "followUp" ? "follow_up" : "steer",
5444
+ message: item.command.message,
5445
+ };
5446
+ if (Array.isArray(item.command.images) && item.command.images.length) command.images = item.command.images;
5447
+ return command;
5448
+ }
5449
+
5450
+ function queuedRetryCommand(item) {
5451
+ const message = String(item.command.message || "").trim();
5452
+ if (item.command.type === "prompt" && message.startsWith("/")) {
5453
+ const command = queuedPromptCommand(item);
5454
+ command.streamingBehavior = item.command.mode === "followUp" ? "followUp" : "steer";
5455
+ return command;
5456
+ }
5457
+ return queuedStreamingCommand(item);
5458
+ }
5459
+
5460
+ function requeueCompactionItems(tab, items) {
5461
+ if (!items?.length) return;
5462
+ const queue = compactionQueueForTab(tab);
5463
+ queue.unshift(...items);
5464
+ broadcastTabEvent(tab, compactionQueueEvent(tab));
5465
+ }
5466
+
5467
+ async function compactionFlushShouldJoinActiveRun(tab, event = {}) {
5468
+ if (event.willRetry === true) return true;
5469
+ await delay(80);
5470
+ const state = await safeRpcData(tab, { type: "get_state" }, STATUS_RPC_TIMEOUT_MS).catch(() => ({ ok: false }));
5471
+ if (state.ok) return !!state.data?.isStreaming;
5472
+ return !!tab.lastState?.isStreaming;
5473
+ }
5474
+
5475
+ async function flushCompactionQueue(tab, event = {}) {
5476
+ const queue = compactionQueueForTab(tab);
5477
+ if (!queue.length || tab.compactionQueueDraining) return;
5478
+ const items = queue.splice(0);
5479
+ tab.compactionQueueDraining = true;
5480
+ broadcastTabEvent(tab, compactionQueueEvent(tab));
5481
+ const remaining = [...items];
5482
+ try {
5483
+ const joinActiveRun = await compactionFlushShouldJoinActiveRun(tab, event);
5484
+ if (joinActiveRun) {
5485
+ while (remaining.length) {
5486
+ const item = remaining[0];
5487
+ const response = await tab.rpc.send(queuedRetryCommand(item));
5488
+ if (response.success === false) throw new Error(response.error || "failed to queue prompt after compaction");
5489
+ remaining.shift();
5490
+ }
5491
+ } else {
5492
+ let startedPrompt = false;
5493
+ while (remaining.length) {
5494
+ const item = remaining[0];
5495
+ const command = startedPrompt ? queuedStreamingCommand(item) : queuedPromptCommand(item);
5496
+ if (!startedPrompt) {
5497
+ const pendingThinkingResponse = await applyPendingThinkingBeforePrompt(tab);
5498
+ if (pendingThinkingResponse?.success === false) throw new Error(pendingThinkingResponse.error || "failed to apply queued thinking level");
5499
+ maybeNameTabForConversation(tab, command);
5500
+ markTabWorking(tab);
5501
+ }
5502
+ const response = await tab.rpc.send(command, command.type === "prompt" ? PROMPT_REQUEST_TIMEOUT_MS : REQUEST_TIMEOUT_MS);
5503
+ if (response.success === false) throw new Error(response.error || "failed to resume after compaction");
5504
+ remaining.shift();
5505
+ if (command.type === "prompt") startedPrompt = true;
5506
+ }
5507
+ }
5508
+ broadcastTabEvent(tab, compactionQueueEvent(tab, { drained: true }));
5509
+ } catch (error) {
5510
+ requeueCompactionItems(tab, remaining);
5511
+ broadcastTabEvent(tab, compactionQueueEvent(tab, { error: sanitizeError(error) }));
5512
+ } finally {
5513
+ tab.compactionQueueDraining = false;
5514
+ broadcastTabEvent(tab, compactionQueueEvent(tab));
5515
+ }
5516
+ }
5517
+
5133
5518
  function settleBashQueueItem(item, kind, value) {
5134
5519
  if (!item || item.settled) return;
5135
5520
  item.settled = true;
@@ -5369,13 +5754,24 @@ function updateTabActivityFromEvent(tab, event) {
5369
5754
  const timestamp = new Date().toISOString();
5370
5755
  switch (event?.type) {
5371
5756
  case "agent_start":
5757
+ patchTabState(tab, { isStreaming: true });
5758
+ markTabWorking(tab, timestamp);
5759
+ break;
5372
5760
  case "compaction_start":
5761
+ patchTabState(tab, { isCompacting: true });
5373
5762
  markTabWorking(tab, timestamp);
5374
5763
  break;
5375
5764
  case "agent_end":
5765
+ patchTabState(tab, { isStreaming: false });
5766
+ markTabDone(tab, timestamp);
5767
+ break;
5376
5768
  case "compaction_end":
5769
+ patchTabState(tab, { isCompacting: false });
5377
5770
  markTabDone(tab, timestamp);
5378
5771
  break;
5772
+ case "queue_update":
5773
+ patchTabState(tab, { pendingMessageCount: (event.steering?.length || 0) + (event.followUp?.length || 0) });
5774
+ break;
5379
5775
  case "pi_process_exit":
5380
5776
  case "pi_process_error":
5381
5777
  if (tab.activity?.isWorking) markTabDone(tab, timestamp);
@@ -5422,14 +5818,17 @@ function attachRpcToTab(tab, rpc) {
5422
5818
  clearPendingExtensionUiRequests(tab);
5423
5819
  clearExtensionStatuses(tab);
5424
5820
  clearExtensionWidgets(tab);
5821
+ resetNaturalConversationMode(tab);
5425
5822
  } else {
5426
5823
  rememberExtensionStatusEvent(tab, scopedEvent);
5824
+ rememberNaturalConversationStatusEvent(tab, scopedEvent);
5427
5825
  rememberExtensionWidgetEvent(tab, scopedEvent);
5428
5826
  trackPendingExtensionUiRequest(tab, scopedEvent);
5429
5827
  }
5430
5828
  scopedEvent = { ...scopedEvent, tabActivity: tabActivitySnapshot(tab), pendingExtensionUiRequestCount: pendingExtensionUiRequests(tab).length };
5431
5829
  recordEvent(scopedEvent);
5432
5830
  for (const client of tab.sseClients) sendSse(client, scopedEvent);
5831
+ if (event?.type === "compaction_end" && event.aborted !== true) void flushCompactionQueue(tab, event);
5433
5832
  });
5434
5833
  }
5435
5834
 
@@ -5467,10 +5866,13 @@ async function createTab({ id: requestedId, index, title, titleSource, conversat
5467
5866
  webuiHelperResponseIds: new Set(),
5468
5867
  bashQueue: [],
5469
5868
  bashQueueDraining: false,
5869
+ compactionQueue: [],
5870
+ compactionQueueDraining: false,
5470
5871
  rpc: undefined,
5471
5872
  rpcUnsubscribe: undefined,
5472
5873
  sseClients: new Set(),
5473
5874
  };
5875
+ resetNaturalConversationMode(tab);
5474
5876
 
5475
5877
  attachRpcToTab(tab, rpc);
5476
5878
  tabs.set(id, tab);
@@ -5514,6 +5916,7 @@ function tabMeta(tab) {
5514
5916
  pendingExtensionUiRequestCount: pendingExtensionUiRequests(tab).length,
5515
5917
  activity: tabActivitySnapshot(tab),
5516
5918
  appRunner: publicAppRunnerState(tab.appRunner),
5919
+ conversationMode: naturalConversationModeSnapshot(tab),
5517
5920
  };
5518
5921
  }
5519
5922
 
@@ -6055,6 +6458,7 @@ async function updateTabCwd(id, cwd) {
6055
6458
  clearPendingExtensionUiRequests(tab);
6056
6459
  clearExtensionStatuses(tab);
6057
6460
  clearExtensionWidgets(tab);
6461
+ resetNaturalConversationMode(tab);
6058
6462
  const rpc = new PiRpcProcess({ ...piCommand, cwd: tab.cwd });
6059
6463
  attachRpcToTab(tab, rpc);
6060
6464
  rpc.start();
@@ -6093,6 +6497,7 @@ async function restartTabRpc(tab, reason = "reload") {
6093
6497
  clearPendingExtensionUiRequests(tab);
6094
6498
  clearExtensionStatuses(tab);
6095
6499
  clearExtensionWidgets(tab);
6500
+ resetNaturalConversationMode(tab);
6096
6501
  const rpc = new PiRpcProcess({ ...piCommand, cwd: tab.cwd });
6097
6502
  attachRpcToTab(tab, rpc);
6098
6503
  rpc.start();
@@ -6677,19 +7082,119 @@ async function annotateSkillCommandState(tab, commands) {
6677
7082
  });
6678
7083
  }
6679
7084
 
7085
+ function naturalConversationLoadedCommandNames(commands = []) {
7086
+ const names = [];
7087
+ const seen = new Set();
7088
+ for (const command of commands || []) {
7089
+ const baseName = naturalConversationCommandBaseName(command?.name || command?.invokeName || "");
7090
+ if (!NATURAL_CONVERSATION_COMMAND_NAMES.includes(baseName) || seen.has(baseName)) continue;
7091
+ seen.add(baseName);
7092
+ names.push(baseName);
7093
+ }
7094
+ return names;
7095
+ }
7096
+
7097
+ function rememberNaturalConversationCommands(tab, commands = []) {
7098
+ const loadedCommands = naturalConversationLoadedCommandNames(commands);
7099
+ const available = loadedCommands.length > 0;
7100
+ tab.conversationMode = naturalConversationModeSnapshot(tab, {
7101
+ available,
7102
+ enabled: available ? undefined : false,
7103
+ uiState: available ? undefined : "off",
7104
+ statusText: available ? undefined : "",
7105
+ loadedCommands,
7106
+ });
7107
+ return tab.conversationMode;
7108
+ }
7109
+
6680
7110
  async function getCommandData(tab) {
6681
7111
  try {
6682
7112
  const response = await tab.rpc.send({ type: "get_commands" });
6683
7113
  if (response.success === false) throw makeHttpError(400, response.error || "failed to load commands");
6684
7114
  const rpcCommands = await annotateSkillCommandState(tab, response.data?.commands || []);
7115
+ rememberNaturalConversationCommands(tab, rpcCommands);
6685
7116
  return { commands: [...NATIVE_SLASH_COMMANDS, ...rpcCommands], rpcRunning: true };
6686
7117
  } catch (error) {
6687
7118
  const message = sanitizeError(error);
6688
7119
  if (!/Pi RPC process is not running/i.test(message)) throw error;
7120
+ rememberNaturalConversationCommands(tab, []);
6689
7121
  return { commands: [...NATIVE_SLASH_COMMANDS], rpcRunning: false, error: message };
6690
7122
  }
6691
7123
  }
6692
7124
 
7125
+ async function naturalConversationPackageStatus() {
7126
+ try {
7127
+ return await optionalFeaturePackageStatus(NATURAL_CONVERSATION_FEATURE_ID);
7128
+ } catch (error) {
7129
+ return { featureId: NATURAL_CONVERSATION_FEATURE_ID, packageName: OPTIONAL_FEATURE_PACKAGES.get(NATURAL_CONVERSATION_FEATURE_ID), installed: false, error: sanitizeError(error) };
7130
+ }
7131
+ }
7132
+
7133
+ async function naturalConversationFeatureData(tab, { refreshCommands = true } = {}) {
7134
+ let commandData = null;
7135
+ let commandError = "";
7136
+ if (refreshCommands) {
7137
+ try {
7138
+ commandData = await getCommandData(tab);
7139
+ } catch (error) {
7140
+ commandError = sanitizeError(error);
7141
+ rememberNaturalConversationCommands(tab, []);
7142
+ }
7143
+ }
7144
+ const packageStatus = await naturalConversationPackageStatus();
7145
+ tab.conversationMode = naturalConversationModeSnapshot(tab, { packageInstalled: packageStatus.installed === true });
7146
+ const mode = naturalConversationModeSnapshot(tab);
7147
+ const available = mode.available === true;
7148
+ return {
7149
+ featureId: NATURAL_CONVERSATION_FEATURE_ID,
7150
+ packageName: OPTIONAL_FEATURE_PACKAGES.get(NATURAL_CONVERSATION_FEATURE_ID),
7151
+ available,
7152
+ packageInstalled: packageStatus.installed === true,
7153
+ packageStatus,
7154
+ commands: mode.loadedCommands,
7155
+ mode,
7156
+ rpcRunning: commandData?.rpcRunning !== false && !commandError,
7157
+ unavailableReason: available
7158
+ ? ""
7159
+ : packageStatus.installed
7160
+ ? "Natural Conversation package is installed, but /talk is not loaded in the active Pi tab. Reload the tab or enable the package extension."
7161
+ : "Natural Conversation package is not installed or not visible from the Web UI package root.",
7162
+ error: commandError || undefined,
7163
+ };
7164
+ }
7165
+
7166
+ async function setNaturalConversationMode(tab, body = {}) {
7167
+ const desired = body.enabled === true;
7168
+ const feature = await naturalConversationFeatureData(tab);
7169
+ if (!feature.available) throw makeHttpError(404, feature.unavailableReason);
7170
+ const commandName = feature.commands.find((name) => name === "talk") || feature.commands[0] || "talk";
7171
+ const response = await tab.rpc.send({ type: "prompt", message: `/${commandName} ${desired ? "on" : "off"}` }, REQUEST_TIMEOUT_MS);
7172
+ if (response.success === false) throw makeHttpError(400, response.error || `Failed to ${desired ? "enable" : "disable"} Natural Conversation Mode`);
7173
+ tab.conversationMode = naturalConversationModeSnapshot(tab, {
7174
+ available: true,
7175
+ enabled: desired,
7176
+ uiState: desired ? "listening" : "off",
7177
+ statusText: desired ? `Voice: listening` : "",
7178
+ loadedCommands: feature.commands,
7179
+ packageInstalled: feature.packageInstalled,
7180
+ startedAt: desired ? naturalConversationModeSnapshot(tab).startedAt || new Date().toISOString() : null,
7181
+ });
7182
+ if (desired) {
7183
+ tab.pendingThinkingLevel = undefined;
7184
+ await setThinkingLevelForTab(tab, "off", { allowPending: false }).catch(() => null);
7185
+ }
7186
+ return { ...(await naturalConversationFeatureData(tab, { refreshCommands: false })), response };
7187
+ }
7188
+
7189
+ function naturalConversationUnavailableResponse(tab) {
7190
+ return {
7191
+ featureId: NATURAL_CONVERSATION_FEATURE_ID,
7192
+ available: false,
7193
+ mode: naturalConversationModeSnapshot(tab, { available: false, enabled: false, uiState: "off" }),
7194
+ message: "Natural Conversation STT/TTS fallback endpoints are reserved for a later phase. Install and load @firstpick/pi-package-natural-conversation, then use browser-native audio from the Web UI shell.",
7195
+ };
7196
+ }
7197
+
6693
7198
  function resolveCliPath(value) {
6694
7199
  const text = String(value || "").trim();
6695
7200
  if (!text) return "";
@@ -7138,6 +7643,12 @@ async function handleNativeSlashCommand(tab, body, req) {
7138
7643
  const response = await tab.rpc.send({ type: "new_session" });
7139
7644
  if (response.success === false) return response;
7140
7645
  tab.conversationStarted = false;
7646
+ forgetTabState(tab);
7647
+ rememberTabState(tab, response.data);
7648
+ clearPendingExtensionUiRequests(tab);
7649
+ clearExtensionStatuses(tab);
7650
+ clearExtensionWidgets(tab);
7651
+ resetNaturalConversationMode(tab);
7141
7652
  return respondNative("new", {
7142
7653
  status: "succeeded",
7143
7654
  message: "Started a new session.",
@@ -7601,6 +8112,10 @@ async function setThinkingLevelForTab(tab, level, { allowPending = true } = {})
7601
8112
  }
7602
8113
 
7603
8114
  async function applyPendingThinkingBeforePrompt(tab) {
8115
+ if (isNaturalConversationActive(tab)) {
8116
+ tab.pendingThinkingLevel = undefined;
8117
+ return null;
8118
+ }
7604
8119
  const level = tab?.pendingThinkingLevel;
7605
8120
  if (!level) return null;
7606
8121
  const stateResult = await safeRpcData(tab, { type: "get_state" }, STATUS_RPC_TIMEOUT_MS);
@@ -7929,6 +8444,7 @@ const server = createServer(async (req, res) => {
7929
8444
  if (url.pathname === "/api/app-runner" && req.method === "POST") {
7930
8445
  const body = await readJsonBody(req);
7931
8446
  const tab = getRequestedTab(req, url, body);
8447
+ ensureNaturalConversationRouteAllowed(tab, "app runner actions are blocked");
7932
8448
  sendJson(res, 200, { ok: true, data: await startAppRunner(tab, String(body.runnerId || body.id || "")) });
7933
8449
  return;
7934
8450
  }
@@ -7936,6 +8452,7 @@ const server = createServer(async (req, res) => {
7936
8452
  if (url.pathname === "/api/app-runner/input" && req.method === "POST") {
7937
8453
  const body = await readJsonBody(req);
7938
8454
  const tab = getRequestedTab(req, url, body);
8455
+ ensureNaturalConversationRouteAllowed(tab, "app runner actions are blocked");
7939
8456
  const text = Object.prototype.hasOwnProperty.call(body, "text") ? body.text : body.input;
7940
8457
  sendJson(res, 200, { ok: true, data: sendAppRunnerInput(tab, text, { appendNewline: body.newline !== false, closeStdin: body.closeStdin === true || body.close === true }) });
7941
8458
  return;
@@ -7944,6 +8461,7 @@ const server = createServer(async (req, res) => {
7944
8461
  if (url.pathname === "/api/app-runner/context" && req.method === "POST") {
7945
8462
  const body = await readJsonBody(req);
7946
8463
  const tab = getRequestedTab(req, url, body);
8464
+ ensureNaturalConversationRouteAllowed(tab, "app runner actions are blocked");
7947
8465
  sendJson(res, 200, { ok: true, data: await transferAppRunnerContext(tab, body) });
7948
8466
  return;
7949
8467
  }
@@ -7951,6 +8469,7 @@ const server = createServer(async (req, res) => {
7951
8469
  if (url.pathname === "/api/app-runner/stop" && req.method === "POST") {
7952
8470
  const body = await readJsonBody(req);
7953
8471
  const tab = getRequestedTab(req, url, body);
8472
+ ensureNaturalConversationRouteAllowed(tab, "app runner actions are blocked");
7954
8473
  stopAppRunnerForTab(tab, "stop requested from Web UI");
7955
8474
  sendJson(res, 200, { ok: true, data: await getAppRunnerData(tab) });
7956
8475
  return;
@@ -7959,6 +8478,7 @@ const server = createServer(async (req, res) => {
7959
8478
  if (url.pathname === "/api/app-runner/clear" && req.method === "POST") {
7960
8479
  const body = await readJsonBody(req);
7961
8480
  const tab = getRequestedTab(req, url, body);
8481
+ ensureNaturalConversationRouteAllowed(tab, "app runner actions are blocked");
7962
8482
  clearAppRunnerForTab(tab);
7963
8483
  sendJson(res, 200, { ok: true, data: await getAppRunnerData(tab) });
7964
8484
  return;
@@ -7973,6 +8493,7 @@ const server = createServer(async (req, res) => {
7973
8493
  if (url.pathname === "/api/app-runner-config" && req.method === "POST") {
7974
8494
  const body = await readJsonBody(req);
7975
8495
  const tab = getRequestedTab(req, url, body);
8496
+ ensureNaturalConversationRouteAllowed(tab, "app runner configuration changes are blocked");
7976
8497
  sendJson(res, 200, { ok: true, data: await saveCustomAppRunner(tab, body.runner || body) });
7977
8498
  return;
7978
8499
  }
@@ -7980,6 +8501,7 @@ const server = createServer(async (req, res) => {
7980
8501
  if (url.pathname === "/api/app-runner-config" && req.method === "DELETE") {
7981
8502
  const body = await readJsonBody(req);
7982
8503
  const tab = getRequestedTab(req, url, body);
8504
+ ensureNaturalConversationRouteAllowed(tab, "app runner configuration changes are blocked");
7983
8505
  sendJson(res, 200, { ok: true, data: await deleteCustomAppRunner(tab, body.id || body.runnerId) });
7984
8506
  return;
7985
8507
  }
@@ -8001,6 +8523,8 @@ const server = createServer(async (req, res) => {
8001
8523
 
8002
8524
  if (url.pathname === "/api/directories" && req.method === "POST") {
8003
8525
  const body = await readJsonBody(req);
8526
+ const tab = getRequestedTab(req, url, body);
8527
+ ensureNaturalConversationRouteAllowed(tab, "directory creation is blocked");
8004
8528
  const activeCwd = directoryPickerActiveCwd(req, url, body);
8005
8529
  sendJson(res, 201, {
8006
8530
  ok: true,
@@ -8022,6 +8546,8 @@ const server = createServer(async (req, res) => {
8022
8546
 
8023
8547
  if (url.pathname === "/api/path-fast-picks" && req.method === "POST") {
8024
8548
  const body = await readJsonBody(req);
8549
+ const tab = getRequestedTab(req, url, body);
8550
+ ensureNaturalConversationRouteAllowed(tab, "path fast-pick changes are blocked");
8025
8551
  const picks = await writePathFastPicks(body.picks ?? body);
8026
8552
  sendJson(res, 200, { ok: true, data: { picks } });
8027
8553
  return;
@@ -8029,6 +8555,8 @@ const server = createServer(async (req, res) => {
8029
8555
 
8030
8556
  if (url.pathname === "/api/attachments" && req.method === "POST") {
8031
8557
  const body = await readJsonBody(req, { limitBytes: requestBodyLimitForPath(url.pathname) });
8558
+ const tab = getRequestedTab(req, url, body);
8559
+ ensureNaturalConversationRouteAllowed(tab, "attachment uploads are blocked");
8032
8560
  sendJson(res, 201, { ok: true, data: await saveUploadedAttachments(body) });
8033
8561
  return;
8034
8562
  }
@@ -8042,6 +8570,7 @@ const server = createServer(async (req, res) => {
8042
8570
  if (url.pathname === "/api/model-cycle" && req.method === "POST") {
8043
8571
  const body = await readJsonBody(req);
8044
8572
  const tab = getRequestedTab(req, url, body);
8573
+ ensureNaturalConversationRouteAllowed(tab, "model changes are blocked");
8045
8574
  const response = await cycleTabModel(tab, body.direction || body.mode);
8046
8575
  sendJson(res, response.success === false ? 400 : 200, responseWithTab(response, tab));
8047
8576
  return;
@@ -8068,6 +8597,7 @@ const server = createServer(async (req, res) => {
8068
8597
  if (url.pathname === "/api/fork" && req.method === "POST") {
8069
8598
  const body = await readJsonBody(req);
8070
8599
  const tab = getRequestedTab(req, url, body);
8600
+ ensureNaturalConversationRouteAllowed(tab, "session fork actions are blocked");
8071
8601
  const response = await runForkCommand(tab, body.entryId);
8072
8602
  sendJson(res, response.success === false ? 400 : 200, responseWithTab(response, tab));
8073
8603
  return;
@@ -8076,6 +8606,7 @@ const server = createServer(async (req, res) => {
8076
8606
  if (url.pathname === "/api/clone" && req.method === "POST") {
8077
8607
  const body = await readJsonBody(req);
8078
8608
  const tab = getRequestedTab(req, url, body);
8609
+ ensureNaturalConversationRouteAllowed(tab, "session clone actions are blocked");
8079
8610
  const response = await runCloneCommand(tab);
8080
8611
  sendJson(res, response.success === false ? 400 : 200, responseWithTab(response, tab));
8081
8612
  return;
@@ -8084,6 +8615,7 @@ const server = createServer(async (req, res) => {
8084
8615
  if (url.pathname === "/api/switch-session" && req.method === "POST") {
8085
8616
  const body = await readJsonBody(req);
8086
8617
  const tab = getRequestedTab(req, url, body);
8618
+ ensureNaturalConversationRouteAllowed(tab, "session switching is blocked");
8087
8619
  const response = await switchTabSession(tab, body.sessionPath || body.path);
8088
8620
  sendJson(res, response.success === false ? 400 : 200, responseWithTab(response, tab));
8089
8621
  return;
@@ -8092,6 +8624,7 @@ const server = createServer(async (req, res) => {
8092
8624
  if (url.pathname === "/api/session-rename" && req.method === "POST") {
8093
8625
  const body = await readJsonBody(req);
8094
8626
  const tab = getRequestedTab(req, url, body);
8627
+ ensureNaturalConversationRouteAllowed(tab, "session renaming is blocked");
8095
8628
  sendJson(res, 200, { ok: true, data: await renameSessionData(tab, body), tab: tabMeta(tab) });
8096
8629
  return;
8097
8630
  }
@@ -8100,6 +8633,7 @@ const server = createServer(async (req, res) => {
8100
8633
  requireLocalhostRoute(req, url.pathname);
8101
8634
  const body = await readJsonBody(req);
8102
8635
  const tab = getRequestedTab(req, url, body);
8636
+ ensureNaturalConversationRouteAllowed(tab, "session deletion is blocked");
8103
8637
  sendJson(res, 200, { ok: true, data: await deleteSessionData(tab, body), tab: tabMeta(tab) });
8104
8638
  return;
8105
8639
  }
@@ -8119,11 +8653,37 @@ const server = createServer(async (req, res) => {
8119
8653
  if (url.pathname === "/api/tree-navigate" && req.method === "POST") {
8120
8654
  const body = await readJsonBody(req);
8121
8655
  const tab = getRequestedTab(req, url, body);
8656
+ ensureNaturalConversationRouteAllowed(tab, "session tree navigation is blocked");
8122
8657
  const response = await navigateSessionTree(tab, body);
8123
8658
  sendJson(res, response.success === false ? 400 : 200, responseWithTab(response, tab));
8124
8659
  return;
8125
8660
  }
8126
8661
 
8662
+ if (url.pathname === "/api/features/natural-conversation" && req.method === "GET") {
8663
+ const tab = getRequestedTab(req, url);
8664
+ sendJson(res, 200, { ok: true, data: await naturalConversationFeatureData(tab) });
8665
+ return;
8666
+ }
8667
+
8668
+ if (url.pathname === "/api/conversation-mode" && req.method === "GET") {
8669
+ const tab = getRequestedTab(req, url);
8670
+ sendJson(res, 200, { ok: true, data: await naturalConversationFeatureData(tab) });
8671
+ return;
8672
+ }
8673
+
8674
+ if (url.pathname === "/api/conversation-mode" && req.method === "POST") {
8675
+ const body = await readJsonBody(req);
8676
+ const tab = getRequestedTab(req, url, body);
8677
+ sendJson(res, 200, { ok: true, data: await setNaturalConversationMode(tab, body), tab: tabMeta(tab) });
8678
+ return;
8679
+ }
8680
+
8681
+ if ((url.pathname === "/api/stt/transcribe" || url.pathname === "/api/tts/speech") && req.method === "POST") {
8682
+ const tab = getRequestedTab(req, url);
8683
+ sendJson(res, 501, { ok: false, feature_unavailable: true, data: naturalConversationUnavailableResponse(tab), error: "Natural Conversation hosted/local STT/TTS fallbacks are not implemented in this Web UI shell yet." });
8684
+ return;
8685
+ }
8686
+
8127
8687
  if (url.pathname === "/api/optional-features" && req.method === "GET") {
8128
8688
  sendJson(res, 200, { ok: true, data: await optionalFeaturePackageStatuses() });
8129
8689
  return;
@@ -8132,6 +8692,8 @@ const server = createServer(async (req, res) => {
8132
8692
  if (url.pathname === "/api/optional-feature-install" && req.method === "POST") {
8133
8693
  requireLocalhostRoute(req, url.pathname);
8134
8694
  const body = await readJsonBody(req);
8695
+ const tab = getRequestedTab(req, url, body);
8696
+ ensureNaturalConversationRouteAllowed(tab, "optional feature installs are blocked");
8135
8697
  const data = await installOptionalFeaturePackage(String(body.featureId || ""));
8136
8698
  sendJson(res, 200, { ok: true, data });
8137
8699
  return;
@@ -8146,6 +8708,7 @@ const server = createServer(async (req, res) => {
8146
8708
  if (url.pathname === "/api/tools" && req.method === "POST") {
8147
8709
  const body = await readJsonBody(req);
8148
8710
  const tab = getRequestedTab(req, url, body);
8711
+ if (isNaturalConversationActive(tab)) blockNaturalConversationAction("tool configuration changes are blocked");
8149
8712
  sendJson(res, 200, { ok: true, data: await setToolConfigData(tab, body) });
8150
8713
  return;
8151
8714
  }
@@ -8159,6 +8722,7 @@ const server = createServer(async (req, res) => {
8159
8722
  if (url.pathname === "/api/skills" && req.method === "POST") {
8160
8723
  const body = await readJsonBody(req);
8161
8724
  const tab = getRequestedTab(req, url, body);
8725
+ ensureNaturalConversationRouteAllowed(tab, "skill configuration changes are blocked");
8162
8726
  sendJson(res, 200, { ok: true, data: await setSkillConfigData(tab, body) });
8163
8727
  return;
8164
8728
  }
@@ -8173,6 +8737,7 @@ const server = createServer(async (req, res) => {
8173
8737
  requireLocalhostRoute(req, url.pathname);
8174
8738
  const body = await readJsonBody(req, { limitBytes: SKILL_FILE_BODY_LIMIT_BYTES });
8175
8739
  const tab = getRequestedTab(req, url, body);
8740
+ ensureNaturalConversationRouteAllowed(tab, "skill file edits are blocked");
8176
8741
  sendJson(res, 200, { ok: true, data: await saveSkillFileData(tab, body) });
8177
8742
  return;
8178
8743
  }
@@ -8186,6 +8751,7 @@ const server = createServer(async (req, res) => {
8186
8751
  if (url.pathname === "/api/settings" && req.method === "POST") {
8187
8752
  const body = await readJsonBody(req);
8188
8753
  const tab = getRequestedTab(req, url, body);
8754
+ ensureNaturalConversationRouteAllowed(tab, "settings changes are blocked");
8189
8755
  sendJson(res, 200, { ok: true, data: await setNativeSettingsData(tab, body) });
8190
8756
  return;
8191
8757
  }
@@ -8199,6 +8765,7 @@ const server = createServer(async (req, res) => {
8199
8765
  if (url.pathname === "/api/action-feedback" && req.method === "POST") {
8200
8766
  const body = await readJsonBody(req);
8201
8767
  const tab = getRequestedTab(req, url, body);
8768
+ ensureNaturalConversationRouteAllowed(tab, "feedback-learning prompts are blocked");
8202
8769
  const response = await handleActionFeedback(tab, body);
8203
8770
  sendJson(res, response.success === false ? 400 : 200, response);
8204
8771
  return;
@@ -8219,12 +8786,26 @@ const server = createServer(async (req, res) => {
8219
8786
  if (url.pathname === "/api/prompt" && req.method === "POST") {
8220
8787
  const body = await readJsonBody(req, { limitBytes: requestBodyLimitForPath(url.pathname) });
8221
8788
  const tab = getRequestedTab(req, url, body);
8789
+ if (isNaturalConversationActive(tab) && naturalConversationSlashCommandName(body.message) && !isNaturalConversationSlashCommand(body.message)) {
8790
+ blockNaturalConversationAction("slash commands are blocked from the Web UI shell");
8791
+ }
8222
8792
  const nativeResponse = await handleNativeSlashCommand(tab, body, req);
8223
8793
  if (nativeResponse) {
8224
8794
  sendJson(res, nativeResponse.success === false ? 400 : 200, responseWithTab(nativeResponse, tab));
8225
8795
  return;
8226
8796
  }
8227
8797
  const command = commandFromPost(url.pathname, body);
8798
+ enforceNaturalConversationCommandAllowed(tab, command);
8799
+ const queuedForCompaction = maybeQueueCommandDuringCompaction(tab, command);
8800
+ if (queuedForCompaction) {
8801
+ sendJson(res, 202, responseWithTab(queuedForCompaction, tab));
8802
+ return;
8803
+ }
8804
+ const naturalConversationSafetyResponse = await ensureNaturalConversationPromptSafety(tab, command);
8805
+ if (naturalConversationSafetyResponse?.success === false) {
8806
+ sendJson(res, 400, responseWithTab(naturalConversationSafetyResponse, tab));
8807
+ return;
8808
+ }
8228
8809
  const pendingThinkingResponse = await applyPendingThinkingBeforePrompt(tab);
8229
8810
  if (pendingThinkingResponse?.success === false) {
8230
8811
  sendJson(res, 400, responseWithTab(pendingThinkingResponse, tab));
@@ -8264,6 +8845,7 @@ const server = createServer(async (req, res) => {
8264
8845
  if (url.pathname === "/api/git-changes/pull" && req.method === "POST") {
8265
8846
  const body = await readJsonBody(req);
8266
8847
  const tab = getRequestedTab(req, url, body);
8848
+ ensureNaturalConversationRouteAllowed(tab, "git pull is blocked");
8267
8849
  try {
8268
8850
  sendJson(res, 200, await pullGitChanges(tab.cwd));
8269
8851
  } catch (error) {
@@ -8285,6 +8867,7 @@ const server = createServer(async (req, res) => {
8285
8867
  if (url.pathname === "/api/git-worktrees" && req.method === "POST") {
8286
8868
  const body = await readJsonBody(req);
8287
8869
  const tab = getRequestedTab(req, url, body);
8870
+ ensureNaturalConversationRouteAllowed(tab, "git worktree changes are blocked");
8288
8871
  try {
8289
8872
  sendJson(res, 200, { ok: true, data: await createGitWorktreeTab(tab, body) });
8290
8873
  } catch (error) {
@@ -8296,6 +8879,7 @@ const server = createServer(async (req, res) => {
8296
8879
  if (url.pathname === "/api/git-worktrees/open" && req.method === "POST") {
8297
8880
  const body = await readJsonBody(req);
8298
8881
  const tab = getRequestedTab(req, url, body);
8882
+ ensureNaturalConversationRouteAllowed(tab, "git worktree changes are blocked");
8299
8883
  try {
8300
8884
  sendJson(res, 200, { ok: true, data: await openExistingGitWorktreeTab(tab, body) });
8301
8885
  } catch (error) {
@@ -8308,6 +8892,7 @@ const server = createServer(async (req, res) => {
8308
8892
  requireLocalhost(req, "Removing Git worktrees is only allowed from localhost");
8309
8893
  const body = await readJsonBody(req);
8310
8894
  const tab = getRequestedTab(req, url, body);
8895
+ ensureNaturalConversationRouteAllowed(tab, "git worktree removal is blocked");
8311
8896
  try {
8312
8897
  sendJson(res, 200, { ok: true, data: await removeGitWorktreeForTab(tab, body) });
8313
8898
  } catch (error) {
@@ -8329,6 +8914,7 @@ const server = createServer(async (req, res) => {
8329
8914
  if (url.pathname === "/api/git-branch" && req.method === "POST") {
8330
8915
  const body = await readJsonBody(req);
8331
8916
  const tab = getRequestedTab(req, url, body);
8917
+ ensureNaturalConversationRouteAllowed(tab, "git branch changes are blocked");
8332
8918
  try {
8333
8919
  sendJson(res, 200, await switchGitBranch(tab.cwd, body.branch, { create: body.create === true }));
8334
8920
  } catch (error) {
@@ -8340,6 +8926,7 @@ const server = createServer(async (req, res) => {
8340
8926
  if (url.pathname.startsWith("/api/git-workflow/")) {
8341
8927
  const body = req.method === "POST" ? await readJsonBody(req) : {};
8342
8928
  const tab = getRequestedTab(req, url, body);
8929
+ if (req.method !== "GET") ensureNaturalConversationRouteAllowed(tab, "git workflow actions are blocked");
8343
8930
  const response = await handleGitWorkflowRequest(url.pathname, body, tab);
8344
8931
  if (response) {
8345
8932
  sendJson(res, 200, response);
@@ -8383,7 +8970,18 @@ const server = createServer(async (req, res) => {
8383
8970
  const command = commandFromPost(url.pathname, body);
8384
8971
  if (command) {
8385
8972
  const tab = getRequestedTab(req, url, body);
8973
+ enforceNaturalConversationCommandAllowed(tab, command);
8386
8974
  if (command.type === "abort") await cancelPendingExtensionUiRequests(tab);
8975
+ const queuedForCompaction = maybeQueueCommandDuringCompaction(tab, command);
8976
+ if (queuedForCompaction) {
8977
+ sendJson(res, 202, responseWithTab(queuedForCompaction, tab));
8978
+ return;
8979
+ }
8980
+ const naturalConversationSafetyResponse = await ensureNaturalConversationPromptSafety(tab, command);
8981
+ if (naturalConversationSafetyResponse?.success === false) {
8982
+ sendJson(res, 400, responseWithTab(naturalConversationSafetyResponse, tab));
8983
+ return;
8984
+ }
8387
8985
  const startsVisibleWork = commandStartsVisibleWork(command);
8388
8986
  if (startsVisibleWork) {
8389
8987
  maybeNameTabForConversation(tab, command);
@@ -8406,6 +9004,7 @@ const server = createServer(async (req, res) => {
8406
9004
  clearPendingExtensionUiRequests(tab);
8407
9005
  clearExtensionStatuses(tab);
8408
9006
  clearExtensionWidgets(tab);
9007
+ resetNaturalConversationMode(tab);
8409
9008
  }
8410
9009
  sendJson(res, response.success === false ? 400 : 200, responseWithTab(response, tab));
8411
9010
  return;