@firstpick/pi-package-webui 0.7.6 → 0.7.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +60 -4
  2. package/bin/pi-webui-rpc-supervisor.mjs +612 -0
  3. package/bin/pi-webui.mjs +1051 -95
  4. package/lib/WEBUI_TUI_NATIVE_PARITY.json +13 -0
  5. package/lib/rpc-supervisor-client.mjs +317 -0
  6. package/lib/rpc-supervisor-protocol.mjs +245 -0
  7. package/lib/rpc-supervisor-state.mjs +165 -0
  8. package/lib/trust-boundaries.mjs +1 -0
  9. package/package.json +4 -4
  10. package/public/app.js +1986 -170
  11. package/public/index.html +388 -25
  12. package/public/issue-bot-client.mjs +344 -0
  13. package/public/issue-wizard-state.mjs +443 -0
  14. package/public/service-worker.js +8 -1
  15. package/public/styles.css +578 -52
  16. package/public/subagent-gate-visibility.mjs +36 -0
  17. package/public/workflow-status-stack.mjs +69 -0
  18. package/tests/app-runner-process-tree-harness.test.mjs +37 -3
  19. package/tests/boot-failure-diagnostics.test.mjs +180 -0
  20. package/tests/completion-signal-contract.test.mjs +156 -0
  21. package/tests/cwd-footer-reliability-static.test.mjs +107 -0
  22. package/tests/durable-rpc-supervisor-harness.test.mjs +275 -0
  23. package/tests/fast-mode-client-static.test.mjs +2 -2
  24. package/tests/fixtures/fake-pi.mjs +90 -6
  25. package/tests/footer-context-contrast-static.test.mjs +10 -0
  26. package/tests/git-panel-file-preview-static.test.mjs +221 -0
  27. package/tests/git-panel-render-stability-static.test.mjs +11 -1
  28. package/tests/http-endpoints-harness.test.mjs +458 -33
  29. package/tests/issue-bot-client.test.mjs +135 -0
  30. package/tests/issue-wizard-state.test.mjs +126 -0
  31. package/tests/mobile-static.test.mjs +79 -16
  32. package/tests/native-parity-harness.test.mjs +2 -1
  33. package/tests/native-parity.test.mjs +13 -2
  34. package/tests/numpad-decimal-input-static.test.mjs +128 -0
  35. package/tests/open-issue-wizard-static.test.mjs +75 -0
  36. package/tests/prompt-routing-input-clear-static.test.mjs +34 -0
  37. package/tests/prompt-routing-tab-status.test.mjs +108 -0
  38. package/tests/rpc-supervisor-host.test.mjs +408 -0
  39. package/tests/rpc-supervisor-protocol.test.mjs +93 -0
  40. package/tests/rpc-supervisor-state.test.mjs +62 -0
  41. package/tests/run-all.mjs +4 -1
  42. package/tests/streaming-ui-coupling.test.mjs +18 -2
  43. package/tests/subagent-gate-visibility.test.mjs +66 -0
  44. package/tests/subagent-launch-slots-static.test.mjs +1 -1
  45. package/tests/subagents-helper.test.mjs +136 -0
  46. package/tests/terminal-tab-workspace-static.test.mjs +99 -0
  47. package/tests/workflow-status-stack.test.mjs +87 -0
  48. package/webui-rpc-helper.mjs +160 -2
package/bin/pi-webui.mjs CHANGED
@@ -15,6 +15,8 @@ import { SessionManager, SettingsManager, DefaultPackageManager } from "@earendi
15
15
  import { authProvidersPayload, createAuthContext, logoutStoredProvider } from "../lib/auth-actions.mjs";
16
16
  import { resolveCodexUsageAuth } from "../lib/codex-usage-auth.mjs";
17
17
  import { nativeExportDownloadPayload } from "../lib/native-export-payload.mjs";
18
+ import { discoverStartAttachRpcSupervisor } from "../lib/rpc-supervisor-client.mjs";
19
+ import { readSupervisorState, supervisorPaths } from "../lib/rpc-supervisor-state.mjs";
18
20
  import {
19
21
  collectOpenSessionFiles,
20
22
  deleteSessionFile,
@@ -128,6 +130,9 @@ let remoteQrCorePromise = null;
128
130
  const DEFAULT_HOST = "127.0.0.1";
129
131
  const DEFAULT_PORT = 31415;
130
132
  const REQUEST_TIMEOUT_MS = 5 * 60 * 1000;
133
+ // Keep supervisor waits bounded while preserving the existing two-hour prompt
134
+ // contract. A detached owner may legitimately outlive the HTTP server request.
135
+ const RPC_SUPERVISOR_COMMAND_TIMEOUT_MAX_MS = 24 * 60 * 60 * 1000;
131
136
  const PROMPT_REQUEST_TIMEOUT_MS = Math.max(REQUEST_TIMEOUT_MS, Number.parseInt(process.env.PI_WEBUI_PROMPT_TIMEOUT_MS || "7200000", 10) || 7200000);
132
137
  const WEBUI_HELPER_TIMEOUT_MS = 8 * 1000;
133
138
  const WEBUI_HELPER_COMMAND = "webui-helper";
@@ -277,6 +282,8 @@ const AUTO_TAB_TITLE_STOP_WORDS = new Set([
277
282
  const APP_RUNNER_CONFIG_FILE = ".pi-webui-runners.json";
278
283
  const APP_RUNNER_CUSTOM_LIMIT = 48;
279
284
  const APP_RUNNER_CUSTOM_ARG_LIMIT = 32;
285
+ const APP_RUNNER_SEARCH_PATH_LIMIT = 24;
286
+ const APP_RUNNER_SEARCH_PATH_MAX_CHARS = 4_096;
280
287
  const APP_RUNNER_FILE_PICKER_LIMIT = 500;
281
288
  const APP_RUNNER_DETECTION_TIMEOUT_MS = 1_200;
282
289
  const APP_RUNNER_COMMAND_CACHE_TTL_MS = 30_000;
@@ -296,6 +303,8 @@ const APP_RUNNER_CPP_ENTRIES = ["main.cpp", "src/main.cpp", "main.cc", "src/main
296
303
  const APP_RUNNER_DOCKER_COMPOSE_FILES = ["compose.yaml", "compose.yml", "docker-compose.yaml", "docker-compose.yml"];
297
304
  const APP_RUNNER_SHELL_SCRIPT_DIRS = ["", "dev", "scripts", "dev/scripts"];
298
305
  const APP_RUNNER_SHELL_SCRIPT_LIMIT = 24;
306
+ const APP_RUNNER_PYTHON_SCRIPT_LIMIT = 24;
307
+ const APP_RUNNER_CONFIGURED_SCRIPT_SCAN_LIMIT = (APP_RUNNER_SHELL_SCRIPT_LIMIT + APP_RUNNER_PYTHON_SCRIPT_LIMIT) * 2;
299
308
  const APP_RUNNER_SHELL_EXTENSIONS = new Map([
300
309
  [".sh", "bash"],
301
310
  [".bash", "bash"],
@@ -733,6 +742,105 @@ function mirrorPiStderr(text, onFailure) {
733
742
  }
734
743
  }
735
744
 
745
+ class SupervisorPiRpcProcess {
746
+ constructor({ supervisor, tabId, displayCommand = "supervised Pi RPC", cwd, snapshot = {} }) {
747
+ this.supervisor = supervisor;
748
+ this.tabId = tabId;
749
+ this.displayCommand = displayCommand;
750
+ this.cwd = cwd;
751
+ this.startedAt = snapshot.startedAt || new Date().toISOString();
752
+ this.listeners = new Set();
753
+ this.metadataUpdate = Promise.resolve();
754
+ this.applySnapshot(snapshot);
755
+ }
756
+
757
+ applySnapshot(snapshot = {}) {
758
+ this.startedAt = snapshot.startedAt || this.startedAt;
759
+ this.cwd = snapshot.metadata?.cwd || this.cwd;
760
+ const running = snapshot.running !== false;
761
+ this.child = {
762
+ pid: Number.isInteger(snapshot.pid) ? snapshot.pid : undefined,
763
+ exitCode: running ? null : 1,
764
+ signalCode: null,
765
+ killed: !running,
766
+ };
767
+ }
768
+
769
+ isRunning() {
770
+ return !!this.child && this.child.exitCode === null && this.child.signalCode === null;
771
+ }
772
+
773
+ onEvent(listener) {
774
+ this.listeners.add(listener);
775
+ return () => this.listeners.delete(listener);
776
+ }
777
+
778
+ emit(event) {
779
+ for (const listener of this.listeners) {
780
+ try {
781
+ listener(event);
782
+ } catch (error) {
783
+ console.error("webui listener failed:", error);
784
+ }
785
+ }
786
+ }
787
+
788
+ receiveSupervisorEvent(event) {
789
+ const payload = event?.payload;
790
+ if (!payload || typeof payload !== "object") return;
791
+ if (payload.type === "pi_process_start") {
792
+ this.child = { pid: payload.pid, exitCode: null, signalCode: null, killed: false };
793
+ this.startedAt = event.at || new Date().toISOString();
794
+ } else if (payload.type === "pi_process_exit") {
795
+ this.child = { ...(this.child || {}), exitCode: payload.code ?? 1, signalCode: payload.signal ?? null, killed: true };
796
+ } else if (payload.type === "pi_process_error" && !this.isRunning()) {
797
+ this.child = { ...(this.child || {}), exitCode: 1, signalCode: null, killed: true };
798
+ }
799
+ this.emit({
800
+ ...payload,
801
+ supervisorScopeId: event.scopeId,
802
+ supervisorEpoch: event.epoch,
803
+ supervisorSeq: event.seq,
804
+ });
805
+ if (payload.type === "pi_stderr" && payload.text) {
806
+ mirrorPiStderr(payload.text, (error) => this.emit({
807
+ type: "pi_stderr_sink_error",
808
+ error: `Pi RPC stderr could not be mirrored to the Web UI server log: ${sanitizeError(error)}`,
809
+ }));
810
+ }
811
+ }
812
+
813
+ send(command, timeoutMs = REQUEST_TIMEOUT_MS) {
814
+ const requestId = command?.id || randomUUID();
815
+ const boundedTimeoutMs = Math.min(Math.max(1, Number(timeoutMs) || REQUEST_TIMEOUT_MS), RPC_SUPERVISOR_COMMAND_TIMEOUT_MAX_MS);
816
+ return this.supervisor.command(this.tabId, command, { requestId, timeoutMs: boundedTimeoutMs });
817
+ }
818
+
819
+ async writeRaw(command) {
820
+ await this.supervisor.write(this.tabId, command);
821
+ }
822
+
823
+ async replace({ child, metadata, displayCommand }) {
824
+ const snapshot = await this.supervisor.replaceTab({ tabId: this.tabId, metadata, child });
825
+ if (displayCommand) this.displayCommand = displayCommand;
826
+ this.applySnapshot(snapshot);
827
+ return snapshot;
828
+ }
829
+
830
+ updateMetadata(metadata) {
831
+ this.metadataUpdate = this.metadataUpdate.catch(() => {}).then(() => this.supervisor.updateTab(this.tabId, metadata));
832
+ return this.metadataUpdate;
833
+ }
834
+
835
+ async stop() {
836
+ return this.supervisor.closeTab(this.tabId);
837
+ }
838
+
839
+ dispose() {
840
+ this.listeners.clear();
841
+ }
842
+ }
843
+
736
844
  class PiRpcProcess {
737
845
  constructor({ command, args, displayCommand, cwd, env = process.env }) {
738
846
  this.command = command;
@@ -2014,6 +2122,82 @@ async function saveRemoteAuthPreference(enabled) {
2014
2122
  return persistedRemoteAuthEnabled;
2015
2123
  }
2016
2124
 
2125
+ const WORKFLOW_POLICY_MODULE_API = ["readWorkflowPolicyState", "writeWorkflowPolicyState"];
2126
+ // Advisory draft catalog owned by the workflow package; the browser never invents suggestions.
2127
+ const WORKFLOW_POLICY_MODULE_CATALOG_API = ["WORKFLOW_POLICY_SUGGESTIONS"];
2128
+ let workflowPolicyModulePromise;
2129
+
2130
+ async function workflowPolicyModule() {
2131
+ if (!workflowPolicyModulePromise) {
2132
+ workflowPolicyModulePromise = (async () => {
2133
+ const specifiers = [
2134
+ "@firstpick/pi-extension-workflows/src/workflow-policy.mjs",
2135
+ new URL("../../pi-extension-workflows/src/workflow-policy.mjs", import.meta.url).href,
2136
+ ];
2137
+ const failures = [];
2138
+ for (const specifier of specifiers) {
2139
+ try {
2140
+ const module = await import(specifier);
2141
+ const missing = [
2142
+ ...WORKFLOW_POLICY_MODULE_API.filter((name) => typeof module?.[name] !== "function"),
2143
+ ...WORKFLOW_POLICY_MODULE_CATALOG_API.filter((name) => !module?.[name] || typeof module[name] !== "object" || Array.isArray(module[name])),
2144
+ ];
2145
+ if (missing.length) throw new Error(`missing ${missing.join(", ")}`);
2146
+ return module;
2147
+ } catch (error) {
2148
+ failures.push(error instanceof Error ? error.message : String(error));
2149
+ }
2150
+ }
2151
+ throw makeHttpError(503, `Workflow policy setup support is unavailable. Install or update @firstpick/pi-extension-workflows and restart Web UI. ${failures.at(-1) || ""}`.trim());
2152
+ })().catch((error) => {
2153
+ workflowPolicyModulePromise = undefined;
2154
+ throw error;
2155
+ });
2156
+ }
2157
+ return workflowPolicyModulePromise;
2158
+ }
2159
+
2160
+ function requireWorkflowPolicyJsonRequest(req) {
2161
+ const contentType = String(req.headers["content-type"] || "").split(";", 1)[0].trim().toLowerCase();
2162
+ if (contentType !== "application/json") throw makeHttpError(415, "Workflow policy saves require Content-Type: application/json.");
2163
+ const fetchSite = String(req.headers["sec-fetch-site"] || "").trim().toLowerCase();
2164
+ if (fetchSite && fetchSite !== "same-origin" && fetchSite !== "none") {
2165
+ throw makeHttpError(403, "Cross-origin workflow policy saves are blocked.");
2166
+ }
2167
+ }
2168
+
2169
+ function workflowPolicySaveBody(body) {
2170
+ if (!body || typeof body !== "object" || Array.isArray(body)) {
2171
+ throw makeHttpError(400, "Workflow policy save body must be an object with only policy and expectedRevision.");
2172
+ }
2173
+ const allowedFields = new Set(["policy", "expectedRevision"]);
2174
+ const unknownFields = Object.keys(body).filter((key) => !allowedFields.has(key));
2175
+ if (unknownFields.length) {
2176
+ throw makeHttpError(400, `Workflow policy save body contains unsupported field${unknownFields.length === 1 ? "" : "s"}: ${unknownFields.join(", ")}.`);
2177
+ }
2178
+ if (!Object.prototype.hasOwnProperty.call(body, "policy") || !Object.prototype.hasOwnProperty.call(body, "expectedRevision")) {
2179
+ throw makeHttpError(400, "Workflow policy save body requires policy and expectedRevision.");
2180
+ }
2181
+ if (body.expectedRevision !== null && typeof body.expectedRevision !== "string") {
2182
+ throw makeHttpError(400, "expectedRevision must be a read revision string or null for a missing policy.");
2183
+ }
2184
+ return body;
2185
+ }
2186
+
2187
+ function workflowPolicyRequestError(error) {
2188
+ if (error?.statusCode) return error;
2189
+ if (error?.code === "WORKFLOW_POLICY_INVALID") return makeHttpError(400, formatCliError(error));
2190
+ if (error?.code === "WORKFLOW_POLICY_STALE_REVISION") return makeHttpError(409, formatCliError(error));
2191
+ if (error?.code === "WORKFLOW_POLICY_UNSAFE_TARGET") return makeHttpError(409, formatCliError(error));
2192
+ if (error instanceof TypeError) return makeHttpError(400, formatCliError(error));
2193
+ return error;
2194
+ }
2195
+
2196
+ function ensureWorkflowPolicyMutationAllowed() {
2197
+ // The policy is global, so any active Natural Conversation tab blocks a global mutation.
2198
+ for (const tab of tabs.values()) ensureNaturalConversationRouteAllowed(tab, "workflow policy changes are blocked");
2199
+ }
2200
+
2017
2201
  let safetyGuardConfigModulePromise;
2018
2202
 
2019
2203
  async function safetyGuardConfigModule() {
@@ -2406,6 +2590,20 @@ async function appRunnerTextIfExists(cwd, relativePath, maxLength = 120_000) {
2406
2590
  }
2407
2591
  }
2408
2592
 
2593
+ async function appRunnerFilePrefix(filePath, maxLength = 256) {
2594
+ let handle;
2595
+ try {
2596
+ handle = await open(filePath, "r");
2597
+ const buffer = Buffer.alloc(maxLength);
2598
+ const { bytesRead } = await handle.read(buffer, 0, maxLength, 0);
2599
+ return buffer.subarray(0, bytesRead).toString("utf8");
2600
+ } catch {
2601
+ return "";
2602
+ } finally {
2603
+ await handle?.close().catch(() => {});
2604
+ }
2605
+ }
2606
+
2409
2607
  async function firstExistingRunnerFile(cwd, candidates) {
2410
2608
  for (const candidate of candidates) {
2411
2609
  if (await appRunnerFileExists(cwd, candidate)) return candidate;
@@ -2595,6 +2793,64 @@ function appRunnerPathInside(root, target) {
2595
2793
  return !relative || (!relative.startsWith("..") && !path.isAbsolute(relative));
2596
2794
  }
2597
2795
 
2796
+ function normalizeAppRunnerSearchPath(value) {
2797
+ if (typeof value !== "string") throw makeHttpError(400, "Search path must be a string");
2798
+ const raw = normalizeSuggestionPath(value).trim();
2799
+ if (!raw) throw makeHttpError(400, "Search path is required");
2800
+ if (raw.includes("\0")) throw makeHttpError(400, "Search path cannot contain null bytes");
2801
+ if (raw.length > APP_RUNNER_SEARCH_PATH_MAX_CHARS) throw makeHttpError(400, `Search path is too long; limit is ${APP_RUNNER_SEARCH_PATH_MAX_CHARS} characters`);
2802
+ if (path.isAbsolute(raw) || /^[a-z]:\//i.test(raw)) throw makeHttpError(400, "Search path must be relative to the project root");
2803
+ if (raw === "." || /^\.\/+$/i.test(raw)) return ".";
2804
+ const normalized = raw.replace(/^\.\/+/, "").replace(/\/+$/g, "");
2805
+ if (!normalized) return ".";
2806
+ const parts = normalized.split("/").filter(Boolean);
2807
+ if (parts.some((part) => part === "." || part === "..")) throw makeHttpError(400, "Search path cannot contain . or .. segments");
2808
+ return parts.join("/");
2809
+ }
2810
+
2811
+ async function canonicalAppRunnerProjectRoot(projectRoot) {
2812
+ try {
2813
+ return await realpath(projectRoot);
2814
+ } catch (error) {
2815
+ throw makeHttpError(400, `Cannot resolve project root: ${formatCliError(error)}`);
2816
+ }
2817
+ }
2818
+
2819
+ async function appRunnerSearchPathStatus(projectRoot, relativePath, canonicalProjectRoot) {
2820
+ const absolutePath = resolveProjectRelativePath(projectRoot, relativePath === "." ? "" : relativePath);
2821
+ let canonicalPath;
2822
+ try {
2823
+ canonicalPath = await realpath(absolutePath);
2824
+ } catch (error) {
2825
+ if (error?.code === "ENOENT" || error?.code === "ENOTDIR") return { available: false, reason: `Search path does not exist: ${relativePath}` };
2826
+ return { available: false, reason: `Cannot access search path ${relativePath}: ${formatCliError(error)}` };
2827
+ }
2828
+ if (!appRunnerPathInside(canonicalProjectRoot, canonicalPath)) {
2829
+ return { available: false, reason: `Search path resolves outside the project root: ${relativePath}` };
2830
+ }
2831
+ const info = await fileStatsIfExists(canonicalPath).catch(() => null);
2832
+ if (!info?.isDirectory()) return { available: false, reason: `Search path is not a directory: ${relativePath}` };
2833
+ return { available: true, absolutePath, canonicalPath };
2834
+ }
2835
+
2836
+ async function appRunnerCanonicalFileInsideProject(projectRoot, relativePath, canonicalProjectRoot) {
2837
+ let absolutePath;
2838
+ try {
2839
+ absolutePath = resolveProjectRelativePath(projectRoot, relativePath);
2840
+ } catch {
2841
+ return null;
2842
+ }
2843
+ let canonicalPath;
2844
+ try {
2845
+ canonicalPath = await realpath(absolutePath);
2846
+ } catch {
2847
+ return null;
2848
+ }
2849
+ if (!appRunnerPathInside(canonicalProjectRoot, canonicalPath)) return null;
2850
+ const info = await fileStatsIfExists(canonicalPath).catch(() => null);
2851
+ return info?.isFile() ? { absolutePath, canonicalPath, info } : null;
2852
+ }
2853
+
2598
2854
  function normalizeProjectRelativePath(value, { allowEmpty = false } = {}) {
2599
2855
  const raw = normalizeSuggestionPath(value).replace(/\0/g, "").trim();
2600
2856
  const withoutDot = raw.replace(/^\.\/+/, "").replace(/\/+$/g, "");
@@ -2680,7 +2936,7 @@ function normalizeCustomRunnerDefinition(raw, projectRoot, { strict = false } =
2680
2936
  const args = parseCustomRunnerArgs(raw?.args);
2681
2937
  const label = String(raw?.label || path.basename(filePath)).trim().slice(0, 120) || path.basename(filePath);
2682
2938
  const rawId = String(raw?.id || "").trim();
2683
- const id = appRunnerId(rawId || label, command, filePath) || appRunnerId(command, filePath);
2939
+ const id = appRunnerId(rawId) || appRunnerId(label, command, filePath) || appRunnerId(command, filePath);
2684
2940
  if (!id) throw makeHttpError(400, "Custom runner id could not be generated");
2685
2941
  if (strict && !appRunnerPathInside(projectRoot, absolutePath)) throw makeHttpError(400, "Path must stay inside the project root");
2686
2942
  return { id, label, command, path: filePath, args };
@@ -2706,21 +2962,63 @@ function directCustomRunnerUnavailableReason(filePath, stats) {
2706
2962
 
2707
2963
  async function customAppRunnerUnavailableReason(projectRoot, runner) {
2708
2964
  const filePath = runner.path;
2709
- let stats;
2710
- try {
2711
- stats = await fileStatsIfExists(resolveProjectRelativePath(projectRoot, filePath));
2712
- } catch (error) {
2713
- return `Cannot access path ${filePath}: ${formatCliError(error)}`;
2965
+ const canonicalProjectRoot = await canonicalAppRunnerProjectRoot(projectRoot);
2966
+ const file = await appRunnerCanonicalFileInsideProject(projectRoot, filePath, canonicalProjectRoot);
2967
+ if (!file) {
2968
+ const absolutePath = resolveProjectRelativePath(projectRoot, filePath);
2969
+ const info = await fileStatsIfExists(absolutePath).catch(() => null);
2970
+ if (info?.isFile()) return `Path resolves outside the project root: ${filePath}`;
2971
+ return `Path to file does not exist: ${filePath}`;
2714
2972
  }
2715
- if (!stats?.isFile()) return `Path to file does not exist: ${filePath}`;
2716
2973
  const command = cleanCustomRunnerCommand(runner.command);
2717
- const directReason = command === "./" ? directCustomRunnerUnavailableReason(filePath, stats) : "";
2974
+ const directReason = command === "./" ? directCustomRunnerUnavailableReason(filePath, file.info) : "";
2718
2975
  if (directReason) return directReason;
2719
2976
  const commandParts = customRunnerCommandParts(command);
2720
2977
  if (command !== "./" && !await appRunnerCommandAvailable(commandParts[0], projectRoot)) return `Command is not available: ${commandParts[0]}`;
2721
2978
  return "";
2722
2979
  }
2723
2980
 
2981
+ function appRunnerSearchPathDiagnostic(severity, message, pathValue) {
2982
+ return customAppRunnerDiagnostic(severity, message, { path: pathValue });
2983
+ }
2984
+
2985
+ async function normalizeAppRunnerSearchPaths(rawSearchPaths, projectRoot, { requireDirectories = false, diagnostics = null } = {}) {
2986
+ if (!Array.isArray(rawSearchPaths)) throw makeHttpError(400, `${APP_RUNNER_CONFIG_FILE} searchPaths must be an array`);
2987
+ if (rawSearchPaths.length > APP_RUNNER_SEARCH_PATH_LIMIT) {
2988
+ throw makeHttpError(400, `Search path limit reached (${APP_RUNNER_SEARCH_PATH_LIMIT})`);
2989
+ }
2990
+ const canonicalProjectRoot = await canonicalAppRunnerProjectRoot(projectRoot);
2991
+ const searchPaths = [];
2992
+ const availableSearchPaths = [];
2993
+ const seen = new Set();
2994
+ for (const rawPath of rawSearchPaths) {
2995
+ let searchPath;
2996
+ try {
2997
+ searchPath = normalizeAppRunnerSearchPath(rawPath);
2998
+ } catch (error) {
2999
+ if (!diagnostics) throw error;
3000
+ diagnostics.push(appRunnerSearchPathDiagnostic("error", `Invalid search path ignored: ${formatCliError(error)}`, typeof rawPath === "string" ? rawPath : ""));
3001
+ continue;
3002
+ }
3003
+ if (seen.has(searchPath)) {
3004
+ const message = `Duplicate search path ignored: ${searchPath}`;
3005
+ if (!diagnostics) throw makeHttpError(400, message);
3006
+ diagnostics.push(appRunnerSearchPathDiagnostic("warning", message, searchPath));
3007
+ continue;
3008
+ }
3009
+ seen.add(searchPath);
3010
+ searchPaths.push(searchPath);
3011
+ const status = await appRunnerSearchPathStatus(projectRoot, searchPath, canonicalProjectRoot);
3012
+ if (!status.available) {
3013
+ if (requireDirectories) throw makeHttpError(400, status.reason);
3014
+ diagnostics?.push(appRunnerSearchPathDiagnostic("warning", status.reason, searchPath));
3015
+ continue;
3016
+ }
3017
+ availableSearchPaths.push({ path: searchPath, ...status });
3018
+ }
3019
+ return { searchPaths, availableSearchPaths, canonicalProjectRoot };
3020
+ }
3021
+
2724
3022
  async function readAppRunnerConfig(projectRoot, { strictRead = false } = {}) {
2725
3023
  const configPath = path.join(projectRoot, APP_RUNNER_CONFIG_FILE);
2726
3024
  let source = {};
@@ -2747,6 +3045,11 @@ async function readAppRunnerConfig(projectRoot, { strictRead = false } = {}) {
2747
3045
  if (strictRead) throw makeHttpError(400, message);
2748
3046
  diagnostics.push(customAppRunnerDiagnostic("error", message));
2749
3047
  }
3048
+ if (source.searchPaths !== undefined && !Array.isArray(source.searchPaths)) {
3049
+ const message = `${APP_RUNNER_CONFIG_FILE} searchPaths must be an array`;
3050
+ if (strictRead) throw makeHttpError(400, message);
3051
+ diagnostics.push(appRunnerSearchPathDiagnostic("error", message, ""));
3052
+ }
2750
3053
  const rawRunners = Array.isArray(source.runners) ? source.runners : [];
2751
3054
  const runners = [];
2752
3055
  for (const raw of rawRunners) {
@@ -2764,20 +3067,31 @@ async function readAppRunnerConfig(projectRoot, { strictRead = false } = {}) {
2764
3067
  }
2765
3068
  if (runners.length >= APP_RUNNER_CUSTOM_LIMIT) break;
2766
3069
  }
2767
- return { projectRoot, configPath, runners, diagnostics };
3070
+ let searchPathData = { searchPaths: [], availableSearchPaths: [], canonicalProjectRoot: await canonicalAppRunnerProjectRoot(projectRoot) };
3071
+ if (Array.isArray(source.searchPaths)) {
3072
+ try {
3073
+ searchPathData = await normalizeAppRunnerSearchPaths(source.searchPaths, projectRoot, { diagnostics });
3074
+ } catch (error) {
3075
+ const message = `Invalid search paths ignored: ${formatCliError(error)}`;
3076
+ if (strictRead) throw makeHttpError(400, message);
3077
+ diagnostics.push(appRunnerSearchPathDiagnostic("error", message, ""));
3078
+ }
3079
+ }
3080
+ return { projectRoot, configPath, runners, diagnostics, ...searchPathData };
2768
3081
  }
2769
3082
 
2770
- async function writeAppRunnerConfig(projectRoot, runners) {
3083
+ async function writeAppRunnerConfig(projectRoot, runners, searchPaths = []) {
2771
3084
  const configPath = path.join(projectRoot, APP_RUNNER_CONFIG_FILE);
2772
- const normalized = [];
3085
+ const normalizedRunners = [];
2773
3086
  for (const runner of runners) {
2774
- normalized.push(normalizeCustomRunnerDefinition(runner, projectRoot, { strict: true }));
2775
- if (normalized.length >= APP_RUNNER_CUSTOM_LIMIT) break;
3087
+ normalizedRunners.push(normalizeCustomRunnerDefinition(runner, projectRoot, { strict: true }));
3088
+ if (normalizedRunners.length >= APP_RUNNER_CUSTOM_LIMIT) break;
2776
3089
  }
3090
+ const { searchPaths: normalizedSearchPaths } = await normalizeAppRunnerSearchPaths(searchPaths, projectRoot);
2777
3091
  const tmpFile = `${configPath}.${process.pid}.${Date.now()}.tmp`;
2778
- await writeFile(tmpFile, `${JSON.stringify({ version: 1, runners: normalized }, null, 2)}\n`, { mode: 0o600 });
3092
+ await writeFile(tmpFile, `${JSON.stringify({ version: 2, searchPaths: normalizedSearchPaths, runners: normalizedRunners }, null, 2)}\n`, { mode: 0o600 });
2779
3093
  await rename(tmpFile, configPath);
2780
- return { projectRoot, configPath, runners: normalized };
3094
+ return { projectRoot, configPath, runners: normalizedRunners, searchPaths: normalizedSearchPaths };
2781
3095
  }
2782
3096
 
2783
3097
  async function customAppRunnerCandidate(projectRoot, configPath, runner) {
@@ -2825,11 +3139,13 @@ async function getCustomAppRunnerConfigData(tab) {
2825
3139
  });
2826
3140
  }
2827
3141
  return {
3142
+ version: 2,
2828
3143
  projectRoot,
2829
3144
  displayProjectRoot: displayPath(projectRoot),
2830
3145
  configFile: config.configPath,
2831
3146
  displayConfigFile: displayPath(config.configPath),
2832
3147
  relativeConfigFile: APP_RUNNER_CONFIG_FILE,
3148
+ searchPaths: config.searchPaths,
2833
3149
  runners,
2834
3150
  diagnostics: config.diagnostics,
2835
3151
  };
@@ -2844,7 +3160,15 @@ async function saveCustomAppRunner(tab, rawRunner) {
2844
3160
  const runners = config.runners.filter((runner) => runner.id !== normalized.id);
2845
3161
  if (runners.length >= APP_RUNNER_CUSTOM_LIMIT) throw makeHttpError(400, `Custom runner limit reached (${APP_RUNNER_CUSTOM_LIMIT})`);
2846
3162
  runners.push(normalized);
2847
- await writeAppRunnerConfig(projectRoot, runners);
3163
+ await writeAppRunnerConfig(projectRoot, runners, config.searchPaths);
3164
+ return getAppRunnerData(tab);
3165
+ }
3166
+
3167
+ async function saveAppRunnerSearchPaths(tab, rawSearchPaths) {
3168
+ const projectRoot = await findAppRunnerProjectRoot(tab?.cwd || options.cwd);
3169
+ const config = await readAppRunnerConfig(projectRoot, { strictRead: true });
3170
+ const { searchPaths } = await normalizeAppRunnerSearchPaths(rawSearchPaths, projectRoot, { requireDirectories: true });
3171
+ await writeAppRunnerConfig(projectRoot, config.runners, searchPaths);
2848
3172
  return getAppRunnerData(tab);
2849
3173
  }
2850
3174
 
@@ -2855,7 +3179,7 @@ async function deleteCustomAppRunner(tab, runnerId) {
2855
3179
  const config = await readAppRunnerConfig(projectRoot);
2856
3180
  const runners = config.runners.filter((runner) => runner.id !== id);
2857
3181
  if (runners.length === config.runners.length) throw makeHttpError(404, "Custom runner not found");
2858
- await writeAppRunnerConfig(projectRoot, runners);
3182
+ await writeAppRunnerConfig(projectRoot, runners, config.searchPaths);
2859
3183
  return getAppRunnerData(tab);
2860
3184
  }
2861
3185
 
@@ -3190,6 +3514,11 @@ function shellFromShebang(text) {
3190
3514
  return "";
3191
3515
  }
3192
3516
 
3517
+ function pythonFromShebang(text) {
3518
+ const firstLine = String(text || "").split(/\r?\n/, 1)[0] || "";
3519
+ return firstLine.startsWith("#!") && /\bpython(?:3(?:\.\d+)?)?\b/i.test(firstLine);
3520
+ }
3521
+
3193
3522
  function shellScriptPriority(relativePath, shell) {
3194
3523
  const base = path.basename(relativePath).replace(/\.(?:sh|bash|zsh|fish)$/i, "").toLowerCase();
3195
3524
  const directory = path.dirname(relativePath).replace(/\\/g, "/");
@@ -3199,10 +3528,20 @@ function shellScriptPriority(relativePath, shell) {
3199
3528
  return 70 + (nameRank === -1 ? 18 : nameRank) + (dirRank === -1 ? 8 : dirRank) + shellRank / 10;
3200
3529
  }
3201
3530
 
3202
- async function shellScriptRunnerForFile(cwd, relativePath) {
3531
+ async function shellScriptRunnerForFile(cwd, relativePath, { canonicalProjectRoot = "", runnerCwd = "" } = {}) {
3532
+ let file;
3533
+ if (canonicalProjectRoot) {
3534
+ file = await appRunnerCanonicalFileInsideProject(cwd, relativePath, canonicalProjectRoot);
3535
+ if (!file) return null;
3536
+ }
3203
3537
  const extensionShell = APP_RUNNER_SHELL_EXTENSIONS.get(path.extname(relativePath).toLowerCase()) || "";
3204
3538
  let shell = extensionShell;
3205
- if (!shell) shell = shellFromShebang(await appRunnerTextIfExists(cwd, relativePath, 256));
3539
+ if (!shell) {
3540
+ const text = file
3541
+ ? await appRunnerFilePrefix(file.canonicalPath)
3542
+ : await appRunnerTextIfExists(cwd, relativePath, 256);
3543
+ shell = shellFromShebang(text);
3544
+ }
3206
3545
  if (!shell || !await appRunnerCommandAvailable(shell, cwd)) return null;
3207
3546
  const fileName = path.basename(relativePath);
3208
3547
  const directory = path.dirname(relativePath);
@@ -3215,9 +3554,103 @@ async function shellScriptRunnerForFile(cwd, relativePath) {
3215
3554
  projectFile: relativePath,
3216
3555
  description: `Detected ${shell} shell script${directory && directory !== "." ? ` in ${directory}` : ""}`,
3217
3556
  priority: shellScriptPriority(relativePath, shell),
3557
+ cwd: runnerCwd,
3218
3558
  });
3219
3559
  }
3220
3560
 
3561
+ async function pythonScriptRunnersForFile(cwd, relativePath, { canonicalProjectRoot, runnerCwd, uvAvailable, pythonCommand }) {
3562
+ if (!uvAvailable && !pythonCommand) return [];
3563
+ const file = await appRunnerCanonicalFileInsideProject(cwd, relativePath, canonicalProjectRoot);
3564
+ if (!file) return [];
3565
+ const extension = path.extname(relativePath).toLowerCase();
3566
+ if (extension !== ".py") {
3567
+ if (path.basename(relativePath).includes(".")) return [];
3568
+ const text = await appRunnerFilePrefix(file.canonicalPath);
3569
+ if (!pythonFromShebang(text)) return [];
3570
+ }
3571
+ const directory = path.dirname(relativePath);
3572
+ const descriptionSuffix = directory && directory !== "." ? ` in ${directory}` : "";
3573
+ const candidates = [];
3574
+ if (uvAvailable) {
3575
+ candidates.push(appRunnerCandidate({
3576
+ id: appRunnerId("python", "uv", relativePath),
3577
+ label: `uv run ${path.basename(relativePath)}`,
3578
+ kind: "python",
3579
+ command: "uv",
3580
+ args: ["run", relativePath],
3581
+ projectFile: relativePath,
3582
+ description: `Detected Python script${descriptionSuffix} from a configured project discovery path`,
3583
+ priority: 56,
3584
+ cwd: runnerCwd,
3585
+ }));
3586
+ }
3587
+ if (pythonCommand) {
3588
+ candidates.push(appRunnerCandidate({
3589
+ id: appRunnerId("python", pythonCommand, relativePath),
3590
+ label: `${pythonCommand} ${path.basename(relativePath)}`,
3591
+ kind: "python",
3592
+ command: pythonCommand,
3593
+ args: [relativePath],
3594
+ projectFile: relativePath,
3595
+ description: `Detected Python script${descriptionSuffix} from a configured project discovery path`,
3596
+ priority: 69,
3597
+ cwd: runnerCwd,
3598
+ }));
3599
+ }
3600
+ return candidates;
3601
+ }
3602
+
3603
+ function shellScriptEntrySupported(entry) {
3604
+ const extension = path.extname(entry.name).toLowerCase();
3605
+ return APP_RUNNER_SHELL_EXTENSIONS.has(extension) || !entry.name.includes(".");
3606
+ }
3607
+
3608
+ function configuredScriptEntrySupported(entry) {
3609
+ return shellScriptEntrySupported(entry) || path.extname(entry.name).toLowerCase() === ".py";
3610
+ }
3611
+
3612
+ async function addConfiguredScriptRunners(runners, cwd) {
3613
+ const projectRoot = await findAppRunnerProjectRoot(cwd);
3614
+ const config = await readAppRunnerConfig(projectRoot);
3615
+ const [uvAvailable, python3Available, pythonAvailable] = await Promise.all([
3616
+ appRunnerCommandAvailable("uv", projectRoot),
3617
+ appRunnerCommandAvailable("python3", projectRoot),
3618
+ appRunnerCommandAvailable("python", projectRoot),
3619
+ ]);
3620
+ const pythonCommand = python3Available ? "python3" : pythonAvailable ? "python" : "";
3621
+ let pythonFilesAdded = 0;
3622
+ for (const directory of config.availableSearchPaths) {
3623
+ const shellLimitReached = runners.filter((item) => item.kind === "shell").length >= APP_RUNNER_SHELL_SCRIPT_LIMIT;
3624
+ if (shellLimitReached && pythonFilesAdded >= APP_RUNNER_PYTHON_SCRIPT_LIMIT) break;
3625
+ const entries = await readdir(directory.canonicalPath, { withFileTypes: true }).catch(() => []);
3626
+ const sortedEntries = entries
3627
+ .filter((entry) => (entry.isFile() || entry.isSymbolicLink()) && configuredScriptEntrySupported(entry))
3628
+ .sort((a, b) => a.name.localeCompare(b.name, undefined, { numeric: true, sensitivity: "base" }))
3629
+ .slice(0, APP_RUNNER_CONFIGURED_SCRIPT_SCAN_LIMIT);
3630
+ for (const entry of sortedEntries) {
3631
+ const relativePath = directory.path === "." ? entry.name : `${directory.path}/${entry.name}`;
3632
+ if (runners.filter((item) => item.kind === "shell").length < APP_RUNNER_SHELL_SCRIPT_LIMIT && shellScriptEntrySupported(entry)) {
3633
+ const shellRunner = await shellScriptRunnerForFile(projectRoot, relativePath, {
3634
+ canonicalProjectRoot: config.canonicalProjectRoot,
3635
+ runnerCwd: projectRoot,
3636
+ });
3637
+ if (shellRunner) addAppRunner(runners, shellRunner);
3638
+ }
3639
+ if (pythonFilesAdded < APP_RUNNER_PYTHON_SCRIPT_LIMIT && (path.extname(entry.name).toLowerCase() === ".py" || !entry.name.includes("."))) {
3640
+ const pythonRunners = await pythonScriptRunnersForFile(projectRoot, relativePath, {
3641
+ canonicalProjectRoot: config.canonicalProjectRoot,
3642
+ runnerCwd: projectRoot,
3643
+ uvAvailable,
3644
+ pythonCommand,
3645
+ });
3646
+ for (const pythonRunner of pythonRunners) addAppRunner(runners, pythonRunner);
3647
+ if (pythonRunners.length) pythonFilesAdded += 1;
3648
+ }
3649
+ if (runners.filter((item) => item.kind === "shell").length >= APP_RUNNER_SHELL_SCRIPT_LIMIT && pythonFilesAdded >= APP_RUNNER_PYTHON_SCRIPT_LIMIT) break;
3650
+ }
3651
+ }
3652
+ }
3653
+
3221
3654
  async function addShellScriptRunners(runners, cwd) {
3222
3655
  const candidates = [];
3223
3656
  for (const directory of APP_RUNNER_SHELL_SCRIPT_DIRS) {
@@ -3228,9 +3661,7 @@ async function addShellScriptRunners(runners, cwd) {
3228
3661
  for (const entry of entries) {
3229
3662
  if (!entry.isFile()) continue;
3230
3663
  const relativePath = directory ? `${directory}/${entry.name}` : entry.name;
3231
- const extension = path.extname(entry.name).toLowerCase();
3232
- const explicitShellExtension = APP_RUNNER_SHELL_EXTENSIONS.has(extension);
3233
- if (!explicitShellExtension && entry.name.includes(".")) continue;
3664
+ if (!shellScriptEntrySupported(entry)) continue;
3234
3665
  candidates.push(relativePath);
3235
3666
  }
3236
3667
  }
@@ -3240,6 +3671,7 @@ async function addShellScriptRunners(runners, cwd) {
3240
3671
  if (runner) addAppRunner(runners, runner);
3241
3672
  if (runners.filter((item) => item.kind === "shell").length >= APP_RUNNER_SHELL_SCRIPT_LIMIT) break;
3242
3673
  }
3674
+ await addConfiguredScriptRunners(runners, cwd);
3243
3675
  }
3244
3676
 
3245
3677
  function firstTaskFromText(text, names) {
@@ -4778,6 +5210,13 @@ async function getWorkspaceInfo(cwd, startedAt) {
4778
5210
  let activeGitWorkflowProcess = null;
4779
5211
  const GIT_CHANGES_COMMAND_TIMEOUT_MS = 5000;
4780
5212
  const GIT_CHANGES_DIFF_MAX_OUTPUT = 500_000;
5213
+ const GIT_FILE_DIFF_CATEGORIES = new Set(["staged", "unstaged", "conflicted", "untracked"]);
5214
+ const GIT_FILE_DIFF_LABELS = Object.freeze({
5215
+ staged: "Staged",
5216
+ unstaged: "Unstaged",
5217
+ conflicted: "Conflicted",
5218
+ untracked: "Untracked",
5219
+ });
4781
5220
  const GIT_PULL_TIMEOUT_MS = 15 * 60 * 1000;
4782
5221
  // Must remain byte-for-byte aligned with pi-extension-aur-review/src/git.ts.
4783
5222
  const STAGED_CONTENT_HASH_DOMAIN = "firstpick/aur-review/staged-content/v1\0";
@@ -5088,11 +5527,14 @@ function normalizeGitRelativePath(root, relativePath) {
5088
5527
  return path.relative(root, resolved).split(path.sep).join("/");
5089
5528
  }
5090
5529
 
5091
- async function readGitUntrackedEntry(root, file) {
5530
+ async function readGitUntrackedEntry(root, file, { maxBytes = Number.POSITIVE_INFINITY } = {}) {
5092
5531
  const normalized = normalizeGitRelativePath(root, file);
5093
5532
  const filePath = resolveGitRelativePath(root, normalized);
5094
5533
  const info = await stat(filePath);
5095
5534
  if (!info.isFile()) return { path: normalized, size: info.size, binary: false, content: "", error: "Not a regular file" };
5535
+ if (Number.isFinite(maxBytes) && info.size > maxBytes) {
5536
+ return { path: normalized, size: info.size, binary: false, content: "", error: `File is too large to preview (limit ${formatBytes(maxBytes)})` };
5537
+ }
5096
5538
  const buffer = await readFile(filePath);
5097
5539
  const binary = isLikelyBinaryBuffer(buffer);
5098
5540
  return {
@@ -5115,13 +5557,64 @@ async function readGitUntrackedEntries(root, files) {
5115
5557
  return entries;
5116
5558
  }
5117
5559
 
5118
- async function readGitUntrackedFile(cwd, requestedPath) {
5560
+ async function readGitUntrackedFile(cwd, requestedPath, options = {}) {
5119
5561
  const root = await getGitRoot(cwd);
5120
5562
  const normalized = normalizeGitRelativePath(root, requestedPath);
5121
5563
  const listed = await runGitReadCommand(root, ["ls-files", "--others", "--exclude-standard", "--", normalized], { maxOutputLength: 120_000 });
5122
5564
  const files = listed.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
5123
5565
  if (!files.includes(normalized)) throw new Error(`Not an untracked file: ${normalized}`);
5124
- return readGitUntrackedEntry(root, normalized);
5566
+ return readGitUntrackedEntry(root, normalized, options);
5567
+ }
5568
+
5569
+ function normalizeGitFileDiffCategory(requestedCategory) {
5570
+ const category = String(requestedCategory || "").trim();
5571
+ if (!GIT_FILE_DIFF_CATEGORIES.has(category)) {
5572
+ throw new Error("Git file diff category must be staged, unstaged, conflicted, or untracked");
5573
+ }
5574
+ return category;
5575
+ }
5576
+
5577
+ function gitFileDiffArgs(category, normalizedPath) {
5578
+ const args = ["diff"];
5579
+ if (category === "staged") args.push("--cached");
5580
+ if (category === "conflicted") args.push("--cc");
5581
+ args.push("--no-ext-diff", "--no-textconv", "--no-color", "--unified=3", "--src-prefix=a/", "--dst-prefix=b/", "--", normalizedPath);
5582
+ return args;
5583
+ }
5584
+
5585
+ async function readGitFileDiff(cwd, requestedPath, requestedCategory) {
5586
+ const root = await getGitRoot(cwd);
5587
+ const category = normalizeGitFileDiffCategory(requestedCategory);
5588
+ const normalizedPath = normalizeGitRelativePath(root, requestedPath);
5589
+ const label = GIT_FILE_DIFF_LABELS[category];
5590
+
5591
+ if (category === "untracked") {
5592
+ const untracked = await readGitUntrackedFile(root, normalizedPath, { maxBytes: GIT_CHANGES_DIFF_MAX_OUTPUT });
5593
+ return {
5594
+ root,
5595
+ path: normalizedPath,
5596
+ category,
5597
+ label,
5598
+ command: formatGitCommand(["ls-files", "--others", "--exclude-standard", "--", normalizedPath]),
5599
+ diff: "",
5600
+ truncated: false,
5601
+ capBytes: GIT_CHANGES_DIFF_MAX_OUTPUT,
5602
+ ...untracked,
5603
+ };
5604
+ }
5605
+
5606
+ const args = gitFileDiffArgs(category, normalizedPath);
5607
+ const result = await runGitReadCommandDetailed(root, args);
5608
+ return {
5609
+ root,
5610
+ path: normalizedPath,
5611
+ category,
5612
+ label,
5613
+ command: formatGitCommand(args),
5614
+ diff: result.output.trimEnd(),
5615
+ truncated: result.truncated,
5616
+ capBytes: result.capBytes,
5617
+ };
5125
5618
  }
5126
5619
 
5127
5620
  async function gitUpstreamRef(root) {
@@ -6596,12 +7089,14 @@ async function openWorktreeResultForTab(sourceTab, result, body = {}) {
6596
7089
 
6597
7090
  if (sameResolvedPath(worktreePath, sourceTab.cwd)) {
6598
7091
  sourceTab.gitWorkspace = gitWorkspaceFromWorktreeResult(result, worktree);
7092
+ scheduleSupervisorMetadataUpdate(sourceTab);
6599
7093
  return { ...result, session: null, tab: tabMeta(sourceTab), tabs: listTabs(), openedTab: false, openedCurrent: true };
6600
7094
  }
6601
7095
 
6602
7096
  const existingTab = [...tabs.values()].find((item) => sameResolvedPath(item.cwd, worktreePath));
6603
7097
  if (existingTab) {
6604
7098
  existingTab.gitWorkspace = gitWorkspaceFromWorktreeResult(result, worktree);
7099
+ scheduleSupervisorMetadataUpdate(existingTab);
6605
7100
  return { ...result, session: null, tab: tabMeta(existingTab), tabs: listTabs(), openedTab: false, openedExistingTab: true };
6606
7101
  }
6607
7102
 
@@ -7159,7 +7654,7 @@ async function readBundledThemes() {
7159
7654
  function normalizeStaticPath(urlPath) {
7160
7655
  if (urlPath === "/") return "index.html";
7161
7656
  const name = urlPath.startsWith("/") ? urlPath.slice(1) : urlPath;
7162
- if (!["index.html", "app.js", "fast-output-live.mjs", "subagent-launch-slot-state.mjs", "voice-conversation.mjs", "aur-review-payload.mjs", "guided-git-command-state.mjs", "guided-git-review-state.mjs", "styles.css", "favicon.svg", "apple-touch-icon.png", "icon-192.png", "icon-512.png", "catppuccin-mocha-background.png", "matrix-background.webp", "manifest.webmanifest", "service-worker.js"].includes(name)) return undefined;
7657
+ if (!["index.html", "app.js", "issue-wizard-state.mjs", "issue-bot-client.mjs", "fast-output-live.mjs", "subagent-launch-slot-state.mjs", "subagent-gate-visibility.mjs", "workflow-status-stack.mjs", "voice-conversation.mjs", "aur-review-payload.mjs", "guided-git-command-state.mjs", "guided-git-review-state.mjs", "styles.css", "favicon.svg", "apple-touch-icon.png", "icon-192.png", "icon-512.png", "catppuccin-mocha-background.png", "matrix-background.webp", "manifest.webmanifest", "service-worker.js"].includes(name)) return undefined;
7163
7658
  return name;
7164
7659
  }
7165
7660
 
@@ -7512,6 +8007,7 @@ if (Number.isFinite(startupDelayMs) && startupDelayMs > 0) {
7512
8007
  }
7513
8008
 
7514
8009
  const restoreTabs = readRestoreTabsFromEnv();
8010
+ const supervisorAttachCursor = readSupervisorCursorFromEnv();
7515
8011
 
7516
8012
  function normalizedRestoreString(value, maxLength) {
7517
8013
  const text = typeof value === "string" ? value.trim() : "";
@@ -7554,6 +8050,19 @@ function readRestoreTabsFromEnv() {
7554
8050
  }
7555
8051
  }
7556
8052
 
8053
+ function readSupervisorCursorFromEnv() {
8054
+ const raw = process.env.PI_WEBUI_RPC_SUPERVISOR_CURSOR;
8055
+ delete process.env.PI_WEBUI_RPC_SUPERVISOR_CURSOR;
8056
+ if (!raw) return undefined;
8057
+ try {
8058
+ const cursor = JSON.parse(raw);
8059
+ if (typeof cursor?.epoch === "string" && typeof cursor?.seq === "string") return cursor;
8060
+ } catch {
8061
+ // A malformed inherited cursor must not prevent a clean authenticated attach.
8062
+ }
8063
+ return undefined;
8064
+ }
8065
+
7557
8066
  async function packageNameForResourcePath(resourcePath) {
7558
8067
  let current = path.dirname(resourcePath);
7559
8068
  while (current && current !== path.dirname(current)) {
@@ -7762,6 +8271,207 @@ async function resolvePiCommand(piArgs) {
7762
8271
  const tabs = new Map();
7763
8272
  const closedRestorableTabs = [];
7764
8273
  let nextTabIndex = 1;
8274
+ let rpcSupervisor = null;
8275
+ let rpcSupervisorSnapshot = null;
8276
+ let rpcSupervisorEventUnsubscribe = null;
8277
+ let rpcSupervisorSequenceState = null;
8278
+
8279
+ function markRpcSupervisorDiscontinuity(reason) {
8280
+ if (!rpcSupervisorSnapshot) return;
8281
+ const message = String(reason || "unknown discontinuity");
8282
+ rpcSupervisorSnapshot.gap = true;
8283
+ const state = rpcSupervisorSequenceState;
8284
+ const previousSize = state?.discontinuities.size || 0;
8285
+ state?.discontinuities.add(message);
8286
+ if (state?.startupComplete && state.discontinuities.size > previousSize && !state.recoveryScheduled) {
8287
+ state.recoveryScheduled = true;
8288
+ queueMicrotask(async () => {
8289
+ await Promise.all([...tabs.values()].flatMap((tab) => [
8290
+ safeRpcData(tab, { type: "get_state" }).catch(() => {}),
8291
+ safeRpcData(tab, { type: "get_messages" }).catch(() => {}),
8292
+ ]));
8293
+ for (const tab of tabs.values()) {
8294
+ broadcastTabEvent(tab, {
8295
+ type: "webui_supervisor_replay_gap",
8296
+ tabId: tab.id,
8297
+ tabTitle: tab.title,
8298
+ reason: message,
8299
+ ...rpcSupervisorBrowserState(),
8300
+ });
8301
+ }
8302
+ state.recoveryScheduled = false;
8303
+ });
8304
+ }
8305
+ }
8306
+
8307
+ function validateRpcSupervisorEvent(event) {
8308
+ const state = rpcSupervisorSequenceState;
8309
+ if (!state) return true;
8310
+ const sequenceText = String(event?.seq ?? "");
8311
+ if (event?.type !== "event" || event.scopeId !== state.scopeId || event.epoch !== state.epoch || !/^[1-9]\d*$/.test(sequenceText)) {
8312
+ markRpcSupervisorDiscontinuity("malformed or mismatched supervisor event envelope");
8313
+ return false;
8314
+ }
8315
+ const sequence = BigInt(sequenceText);
8316
+ if (state.lastSequence !== null) {
8317
+ if (sequence <= state.lastSequence) {
8318
+ markRpcSupervisorDiscontinuity(`duplicate or out-of-order supervisor sequence ${sequenceText}`);
8319
+ return false;
8320
+ }
8321
+ if (sequence !== state.lastSequence + 1n) {
8322
+ markRpcSupervisorDiscontinuity(`missing supervisor sequence before ${sequenceText}`);
8323
+ }
8324
+ }
8325
+ state.lastSequence = sequence;
8326
+ return true;
8327
+ }
8328
+
8329
+ function dispatchRpcSupervisorEvent(event) {
8330
+ if (!validateRpcSupervisorEvent(event)) return;
8331
+ const tab = tabs.get(event.tabId);
8332
+ if (!tab) {
8333
+ markRpcSupervisorDiscontinuity(`supervisor event ${event.seq} targeted an unknown tab`);
8334
+ return;
8335
+ }
8336
+ tab.rpc.receiveSupervisorEvent?.(event);
8337
+ }
8338
+
8339
+ function installRpcSupervisorEventDispatch(snapshot) {
8340
+ if (!rpcSupervisor || !snapshot) return;
8341
+ const attachSequence = supervisorAttachCursor?.epoch === snapshot.epoch && snapshot.gap !== true
8342
+ ? BigInt(supervisorAttachCursor.seq)
8343
+ : snapshot.latestSeq === "0" ? 0n : null;
8344
+ rpcSupervisorSequenceState = {
8345
+ scopeId: snapshot.scopeId,
8346
+ epoch: snapshot.epoch,
8347
+ lastSequence: attachSequence,
8348
+ discontinuities: new Set(snapshot.gap === true ? ["supervisor reported a replay gap"] : []),
8349
+ startupComplete: false,
8350
+ recoveryScheduled: false,
8351
+ };
8352
+ rpcSupervisorEventUnsubscribe = rpcSupervisor.onEvent(dispatchRpcSupervisorEvent);
8353
+ }
8354
+
8355
+ function finishRpcSupervisorReplay(snapshot) {
8356
+ if (!snapshot || !rpcSupervisorSequenceState) return;
8357
+ const latestSequence = BigInt(snapshot.latestSeq);
8358
+ const observed = rpcSupervisorSequenceState.lastSequence;
8359
+ if (observed === null) {
8360
+ if (latestSequence > 0n) markRpcSupervisorDiscontinuity("retained replay did not include the supervisor latest sequence");
8361
+ } else if (observed !== latestSequence) {
8362
+ markRpcSupervisorDiscontinuity(`retained replay ended at ${observed} instead of ${latestSequence}`);
8363
+ }
8364
+ // A known replay gap is repaired authoritatively. Resume continuity checks
8365
+ // from the attach snapshot boundary before draining attach-window events.
8366
+ rpcSupervisorSequenceState.lastSequence = latestSequence;
8367
+ }
8368
+
8369
+ async function finishRpcSupervisorStartup(initialTabs) {
8370
+ if (!rpcSupervisor || !rpcSupervisorSnapshot) return;
8371
+ finishRpcSupervisorReplay(rpcSupervisorSnapshot);
8372
+ rpcSupervisor.drainStartupEvents();
8373
+ if (rpcSupervisorSnapshot.tabs?.length) {
8374
+ await Promise.all(initialTabs.map((tab) => primeTabRpc(tab).catch(() => {})));
8375
+ }
8376
+ if (rpcSupervisorSnapshot.gap === true) {
8377
+ await Promise.all(initialTabs.flatMap((tab) => [
8378
+ safeRpcData(tab, { type: "get_state" }).catch(() => {}),
8379
+ safeRpcData(tab, { type: "get_messages" }).catch(() => {}),
8380
+ ]));
8381
+ recordEvent({
8382
+ type: "webui_supervisor_replay_gap",
8383
+ tabCount: initialTabs.length,
8384
+ reason: [...(rpcSupervisorSequenceState?.discontinuities || [])].join("; "),
8385
+ });
8386
+ }
8387
+ rpcSupervisorSequenceState.startupComplete = true;
8388
+ }
8389
+
8390
+ function rpcSupervisorDisabled() {
8391
+ return ["0", "false", "no", "off"].includes(String(process.env.PI_WEBUI_RPC_SUPERVISOR || "").trim().toLowerCase());
8392
+ }
8393
+
8394
+ async function initializeRpcSupervisor() {
8395
+ if (rpcSupervisorDisabled()) {
8396
+ const paths = await supervisorPaths({ agentDir, port: options.port });
8397
+ const state = await readSupervisorState(paths);
8398
+ if (state?.tabs?.length) {
8399
+ throw new Error("PI_WEBUI_RPC_SUPERVISOR is disabled but this WebUI scope still has managed Pi tabs; use /api/shutdown before starting direct mode.");
8400
+ }
8401
+ return null;
8402
+ }
8403
+ return discoverStartAttachRpcSupervisor({
8404
+ agentDir,
8405
+ port: options.port,
8406
+ cursor: supervisorAttachCursor,
8407
+ // The detached host inherits only the existing Pi child environment. Keep
8408
+ // recovery routing available without persisting it in supervisor metadata.
8409
+ environment: piRpcEnvironment(),
8410
+ });
8411
+ }
8412
+
8413
+ function supervisedTabMetadata(tab, { cwd = tab.cwd } = {}) {
8414
+ return {
8415
+ index: tab.index,
8416
+ title: tab.title,
8417
+ titleSource: tab.titleSource,
8418
+ conversationStarted: tab.conversationStarted === true,
8419
+ cwd,
8420
+ sessionFile: tabRestorableSessionFile(tab),
8421
+ gitWorkspace: tab.gitWorkspace || null,
8422
+ createdAt: tab.createdAt,
8423
+ };
8424
+ }
8425
+
8426
+ function scheduleSupervisorMetadataUpdate(tab) {
8427
+ if (!(tab?.rpc instanceof SupervisorPiRpcProcess)) return;
8428
+ if (tab.cwdChangeInProgress) return;
8429
+ if (tab.supervisorMetadataUpdateQueued) return;
8430
+ tab.supervisorMetadataUpdateQueued = true;
8431
+ queueMicrotask(() => {
8432
+ tab.supervisorMetadataUpdateQueued = false;
8433
+ if (!(tab.rpc instanceof SupervisorPiRpcProcess) || !tabs.has(tab.id)) return;
8434
+ void tab.rpc.updateMetadata(supervisedTabMetadata(tab)).catch((error) => {
8435
+ console.warn(`failed to update managed Pi tab metadata: ${sanitizeError(error)}`);
8436
+ });
8437
+ });
8438
+ }
8439
+
8440
+ function rpcSupervisorDiagnostics() {
8441
+ if (!rpcSupervisor) return { enabled: false, attached: false, managedTabCount: 0 };
8442
+ return {
8443
+ enabled: true,
8444
+ attached: rpcSupervisor.isConnected(),
8445
+ managedTabCount: tabs.size,
8446
+ };
8447
+ }
8448
+
8449
+ function rpcSupervisorBrowserState() {
8450
+ if (!rpcSupervisor || !rpcSupervisorSnapshot) return {};
8451
+ return {
8452
+ supervisorScopeId: rpcSupervisorSnapshot.scopeId,
8453
+ supervisorEpoch: rpcSupervisorSnapshot.epoch,
8454
+ supervisorReplayGap: rpcSupervisorSnapshot.gap === true,
8455
+ };
8456
+ }
8457
+
8458
+ async function prepareRpcSupervisorHandoff() {
8459
+ if (!rpcSupervisor) return undefined;
8460
+ const handoff = await rpcSupervisor.prepareHandoff();
8461
+ return { epoch: handoff.epoch, seq: handoff.latestSeq };
8462
+ }
8463
+
8464
+ async function detachRpcSupervisor() {
8465
+ if (!rpcSupervisor) return;
8466
+ try {
8467
+ if (rpcSupervisor.isConnected()) await rpcSupervisor.detach();
8468
+ } finally {
8469
+ rpcSupervisorEventUnsubscribe?.();
8470
+ rpcSupervisorEventUnsubscribe = null;
8471
+ rpcSupervisor.close();
8472
+ rpcSupervisor = null;
8473
+ }
8474
+ }
7765
8475
  const TAB_ACTIVITY_IDLE_RECONCILE_GRACE_MS = 1200;
7766
8476
  const TAB_ACTIVITY_STATE_RECONCILE_INTERVAL_MS = 2500;
7767
8477
  const TAB_ACTIVITY_STATE_RECONCILE_TIMEOUT_MS = 1200;
@@ -7774,6 +8484,7 @@ function rememberTabState(tab, state) {
7774
8484
  if (!tab || !state || typeof state !== "object") return;
7775
8485
  tab.lastState = state;
7776
8486
  if (!options.noSession && Object.prototype.hasOwnProperty.call(state, "sessionFile")) tab.sessionFile = sessionFileFromState(state);
8487
+ scheduleSupervisorMetadataUpdate(tab);
7777
8488
  }
7778
8489
 
7779
8490
  function patchTabState(tab, patch) {
@@ -7817,6 +8528,7 @@ function forgetTabState(tab) {
7817
8528
  tab.lastState = null;
7818
8529
  tab.sessionFile = undefined;
7819
8530
  tab.pendingThinkingLevel = undefined;
8531
+ scheduleSupervisorMetadataUpdate(tab);
7820
8532
  }
7821
8533
 
7822
8534
  function tabRestorableSessionFile(tab) {
@@ -7828,6 +8540,7 @@ function createTabActivity(now = new Date().toISOString()) {
7828
8540
  return {
7829
8541
  status: "idle",
7830
8542
  isWorking: false,
8543
+ runStarted: false,
7831
8544
  completionSerial: 0,
7832
8545
  lastChangedAt: now,
7833
8546
  lastStartedAt: null,
@@ -7891,6 +8604,10 @@ function normalizeWebuiSubagentText(value, maxLength = 240) {
7891
8604
  return text ? text.slice(0, maxLength) : "";
7892
8605
  }
7893
8606
 
8607
+ function normalizeWebuiSubagentSource(value) {
8608
+ return value === "foreground" || value === "workflow" ? value : "async";
8609
+ }
8610
+
7894
8611
  function normalizeWebuiSubagentPayload(value) {
7895
8612
  if (!value || typeof value !== "object" || value.version !== 1) return null;
7896
8613
  const runs = [];
@@ -7917,7 +8634,7 @@ function normalizeWebuiSubagentPayload(value) {
7917
8634
  if (!agents.length) continue;
7918
8635
  runs.push({
7919
8636
  id,
7920
- source: rawRun.source === "foreground" ? "foreground" : "async",
8637
+ source: normalizeWebuiSubagentSource(rawRun.source),
7921
8638
  mode: ["single", "parallel", "chain"].includes(rawRun.mode) ? rawRun.mode : "single",
7922
8639
  status: "running",
7923
8640
  startedAt: Number.isFinite(rawRun.startedAt) ? rawRun.startedAt : Date.now(),
@@ -8429,10 +9146,11 @@ async function cancelPendingExtensionUiRequests(tab) {
8429
9146
  return ids.length;
8430
9147
  }
8431
9148
 
8432
- function markTabWorking(tab, timestamp = new Date().toISOString()) {
9149
+ function markTabWorking(tab, timestamp = new Date().toISOString(), { runStarted = false } = {}) {
8433
9150
  const activity = tab.activity || createTabActivity(timestamp);
8434
9151
  activity.status = "working";
8435
9152
  activity.isWorking = true;
9153
+ activity.runStarted = activity.runStarted === true || runStarted === true;
8436
9154
  activity.lastStartedAt = timestamp;
8437
9155
  activity.lastChangedAt = timestamp;
8438
9156
  tab.activity = activity;
@@ -8442,6 +9160,7 @@ function markTabDone(tab, timestamp = new Date().toISOString()) {
8442
9160
  const activity = tab.activity || createTabActivity(timestamp);
8443
9161
  activity.status = "done";
8444
9162
  activity.isWorking = false;
9163
+ activity.runStarted = false;
8445
9164
  activity.completionSerial = (Number(activity.completionSerial) || 0) + 1;
8446
9165
  activity.lastCompletedAt = timestamp;
8447
9166
  activity.lastChangedAt = timestamp;
@@ -8452,6 +9171,7 @@ function markTabIdle(tab, timestamp = new Date().toISOString()) {
8452
9171
  const activity = tab.activity || createTabActivity(timestamp);
8453
9172
  activity.status = "idle";
8454
9173
  activity.isWorking = false;
9174
+ activity.runStarted = false;
8455
9175
  activity.lastChangedAt = timestamp;
8456
9176
  tab.activity = activity;
8457
9177
  }
@@ -8481,11 +9201,14 @@ function reconcileTabActivityFromState(tab, state, timestamp = new Date().toISOS
8481
9201
  return tabActivitySnapshot(tab);
8482
9202
  }
8483
9203
  if (stateHasVisibleWork(state)) {
8484
- if (!tab.activity?.isWorking) markTabWorking(tab, timestamp);
9204
+ if (!tab.activity?.isWorking || (state.isStreaming && !tab.activity?.runStarted)) {
9205
+ markTabWorking(tab, timestamp, { runStarted: state.isStreaming === true });
9206
+ }
8485
9207
  return tabActivitySnapshot(tab);
8486
9208
  }
8487
9209
  if (tab.activity?.isWorking && !activityRecentlyStarted(tab.activity)) {
8488
- markTabDone(tab, timestamp);
9210
+ if (tab.activity.runStarted) markTabDone(tab, timestamp);
9211
+ else markTabIdle(tab, timestamp);
8489
9212
  }
8490
9213
  return tabActivitySnapshot(tab);
8491
9214
  }
@@ -8517,27 +9240,30 @@ function updateTabActivityFromEvent(tab, event) {
8517
9240
  switch (event?.type) {
8518
9241
  case "agent_start":
8519
9242
  patchTabState(tab, { isStreaming: true });
8520
- markTabWorking(tab, timestamp);
9243
+ markTabWorking(tab, timestamp, { runStarted: true });
8521
9244
  break;
8522
9245
  case "compaction_start":
8523
9246
  patchTabState(tab, { isCompacting: true });
8524
9247
  markTabWorking(tab, timestamp);
8525
9248
  break;
8526
9249
  case "agent_end":
9250
+ // A low-level run ended, but Pi may still retry, compact, or process a follow-up.
9251
+ break;
9252
+ case "agent_settled":
8527
9253
  patchTabState(tab, { isStreaming: false });
8528
- markTabDone(tab, timestamp);
9254
+ if (tab.activity?.runStarted) markTabDone(tab, timestamp);
9255
+ else if (tab.activity?.isWorking) markTabIdle(tab, timestamp);
8529
9256
  break;
8530
9257
  case "compaction_end":
8531
9258
  patchTabState(tab, { isCompacting: false });
8532
- markTabDone(tab, timestamp);
9259
+ if (!tab.lastState?.isStreaming && !tab.activity?.runStarted) markTabIdle(tab, timestamp);
8533
9260
  break;
8534
9261
  case "queue_update":
8535
9262
  patchTabState(tab, { pendingMessageCount: (event.steering?.length || 0) + (event.followUp?.length || 0) });
8536
9263
  break;
8537
9264
  case "pi_process_exit":
8538
9265
  case "pi_process_error":
8539
- if (tab.activity?.isWorking) markTabDone(tab, timestamp);
8540
- else markTabIdle(tab, timestamp);
9266
+ markTabIdle(tab, timestamp);
8541
9267
  break;
8542
9268
  case "response":
8543
9269
  if (event.command === "get_state" && event.success !== false) {
@@ -8598,27 +9324,14 @@ function attachRpcToTab(tab, rpc) {
8598
9324
  });
8599
9325
  }
8600
9326
 
8601
- async function createTab({ id: requestedId, index, title, titleSource, conversationStarted, cwd, sessionFile, gitWorkspace } = {}) {
8602
- const tabIndex = Number.isInteger(index) && index > 0 ? index : nextTabIndex;
8603
- nextTabIndex = Math.max(nextTabIndex, tabIndex + 1);
8604
- const explicitTitle = String(title || "").trim();
8605
- const tabTitle = explicitTitle || defaultTabTitle(tabIndex);
8606
- const titleIsExplicit = Boolean(explicitTitle || (options.name && tabIndex === 1));
8607
- const resolvedTitleSource = ["explicit", "auto", "default"].includes(titleSource) ? titleSource : titleIsExplicit ? "explicit" : "default";
8608
- const tabCwd = cwd ? await resolveCwd(cwd, options.cwd) : options.cwd;
8609
- const id = requestedId && !tabs.has(requestedId) ? requestedId : randomUUID();
8610
- const piArgs = await buildPiArgsForTab(tabIndex, tabTitle, tabCwd);
8611
- if (sessionFile && !options.noSession) piArgs.push("--session", sessionFile);
8612
- const piCommand = await resolvePiCommand(piArgs);
8613
- const rpc = new PiRpcProcess({ ...piCommand, cwd: tabCwd, env: piRpcEnvironment() });
8614
- const createdAt = new Date().toISOString();
9327
+ function createTabRecord({ id, index, title, titleSource, conversationStarted, cwd, createdAt = new Date().toISOString(), sessionFile, gitWorkspace, rpc }) {
8615
9328
  const tab = {
8616
9329
  id,
8617
- index: tabIndex,
8618
- title: tabTitle,
8619
- titleSource: resolvedTitleSource,
9330
+ index,
9331
+ title,
9332
+ titleSource,
8620
9333
  conversationStarted: conversationStarted === true,
8621
- cwd: tabCwd,
9334
+ cwd,
8622
9335
  createdAt,
8623
9336
  sessionFile: options.noSession ? undefined : normalizedRestoreString(sessionFile, 4096),
8624
9337
  gitWorkspace: gitWorkspace || null,
@@ -8637,20 +9350,62 @@ async function createTab({ id: requestedId, index, title, titleSource, conversat
8637
9350
  bashQueueDraining: false,
8638
9351
  compactionQueue: [],
8639
9352
  compactionQueueDraining: false,
8640
- rpc: undefined,
9353
+ cwdChangeInProgress: false,
9354
+ rpc,
8641
9355
  rpcUnsubscribe: undefined,
8642
9356
  sseClients: new Set(),
8643
9357
  };
8644
9358
  resetNaturalConversationMode(tab);
9359
+ return tab;
9360
+ }
9361
+
9362
+ async function createTab({ id: requestedId, index, title, titleSource, conversationStarted, cwd, sessionFile, gitWorkspace } = {}) {
9363
+ const tabIndex = Number.isInteger(index) && index > 0 ? index : nextTabIndex;
9364
+ nextTabIndex = Math.max(nextTabIndex, tabIndex + 1);
9365
+ const explicitTitle = String(title || "").trim();
9366
+ const tabTitle = explicitTitle || defaultTabTitle(tabIndex);
9367
+ const titleIsExplicit = Boolean(explicitTitle || (options.name && tabIndex === 1));
9368
+ const resolvedTitleSource = ["explicit", "auto", "default"].includes(titleSource) ? titleSource : titleIsExplicit ? "explicit" : "default";
9369
+ const tabCwd = cwd ? await resolveCwd(cwd, options.cwd) : options.cwd;
9370
+ const id = requestedId && !tabs.has(requestedId) ? requestedId : randomUUID();
9371
+ const piArgs = await buildPiArgsForTab(tabIndex, tabTitle, tabCwd);
9372
+ if (sessionFile && !options.noSession) piArgs.push("--session", sessionFile);
9373
+ const piCommand = await resolvePiCommand(piArgs);
9374
+ const createdAt = new Date().toISOString();
9375
+ const rpc = rpcSupervisor
9376
+ ? new SupervisorPiRpcProcess({ supervisor: rpcSupervisor, tabId: id, displayCommand: piCommand.displayCommand, cwd: tabCwd, snapshot: { startedAt: createdAt, running: false } })
9377
+ : new PiRpcProcess({ ...piCommand, cwd: tabCwd, env: piRpcEnvironment() });
9378
+ const tab = createTabRecord({
9379
+ id,
9380
+ index: tabIndex,
9381
+ title: tabTitle,
9382
+ titleSource: resolvedTitleSource,
9383
+ conversationStarted,
9384
+ cwd: tabCwd,
9385
+ createdAt,
9386
+ sessionFile,
9387
+ gitWorkspace,
9388
+ rpc,
9389
+ });
8645
9390
 
8646
9391
  attachRpcToTab(tab, rpc);
8647
9392
  tabs.set(id, tab);
8648
- rpc.start();
8649
9393
  try {
9394
+ if (rpc instanceof SupervisorPiRpcProcess) {
9395
+ const snapshot = await rpcSupervisor.createTab({
9396
+ tabId: id,
9397
+ metadata: supervisedTabMetadata(tab),
9398
+ child: { command: piCommand.command, args: piCommand.args, cwd: tabCwd },
9399
+ });
9400
+ rpc.applySnapshot(snapshot);
9401
+ } else {
9402
+ rpc.start();
9403
+ }
8650
9404
  await primeTabRpc(tab);
8651
9405
  } catch (error) {
8652
9406
  if (!tab.rpc.isRunning()) {
8653
9407
  tab.rpcUnsubscribe?.();
9408
+ rpc.dispose?.();
8654
9409
  gitLiveWatcher.unsubscribe(id);
8655
9410
  tabs.delete(id);
8656
9411
  throw new Error(`Pi RPC process failed while starting ${tabTitle}: ${sanitizeError(error)}`);
@@ -8662,6 +9417,56 @@ async function createTab({ id: requestedId, index, title, titleSource, conversat
8662
9417
  return tab;
8663
9418
  }
8664
9419
 
9420
+ async function hydrateManagedTabs(snapshot) {
9421
+ const managedTabs = Array.isArray(snapshot?.tabs) ? snapshot.tabs : [];
9422
+ if (!managedTabs.length) return [];
9423
+ const hydrated = [];
9424
+ try {
9425
+ for (const managed of managedTabs) {
9426
+ const metadata = managed?.metadata;
9427
+ const descriptor = normalizeRestoreTabDescriptor({ id: managed?.id, ...metadata }, new Set());
9428
+ if (!descriptor?.id || !descriptor.cwd || tabs.has(descriptor.id)) {
9429
+ throw new Error("RPC supervisor returned invalid or duplicate managed tab metadata");
9430
+ }
9431
+ const tabIndex = Number.isInteger(descriptor.index) && descriptor.index > 0 ? descriptor.index : nextTabIndex;
9432
+ nextTabIndex = Math.max(nextTabIndex, tabIndex + 1);
9433
+ const tabTitle = descriptor.title || defaultTabTitle(tabIndex);
9434
+ const resolvedTitleSource = ["explicit", "auto", "default"].includes(descriptor.titleSource) ? descriptor.titleSource : "default";
9435
+ const rpc = new SupervisorPiRpcProcess({
9436
+ supervisor: rpcSupervisor,
9437
+ tabId: descriptor.id,
9438
+ cwd: descriptor.cwd,
9439
+ snapshot: managed,
9440
+ });
9441
+ const tab = createTabRecord({
9442
+ id: descriptor.id,
9443
+ index: tabIndex,
9444
+ title: tabTitle,
9445
+ titleSource: resolvedTitleSource,
9446
+ conversationStarted: descriptor.conversationStarted,
9447
+ cwd: descriptor.cwd,
9448
+ createdAt: normalizedRestoreString(metadata?.createdAt, 128) || managed.startedAt || new Date().toISOString(),
9449
+ sessionFile: descriptor.sessionFile,
9450
+ gitWorkspace: metadata?.gitWorkspace || null,
9451
+ rpc,
9452
+ });
9453
+ attachRpcToTab(tab, rpc);
9454
+ tabs.set(tab.id, tab);
9455
+ hydrated.push(tab);
9456
+ }
9457
+ } catch (error) {
9458
+ for (const tab of hydrated) {
9459
+ tab.rpcUnsubscribe?.();
9460
+ tab.rpc.dispose?.();
9461
+ tabs.delete(tab.id);
9462
+ }
9463
+ throw error;
9464
+ }
9465
+
9466
+ for (const event of snapshot.replay || []) dispatchRpcSupervisorEvent(event);
9467
+ return hydrated;
9468
+ }
9469
+
8665
9470
  function firstTab() {
8666
9471
  return tabs.values().next().value;
8667
9472
  }
@@ -8816,7 +9621,7 @@ function normalizeWebuiSubagentOutput(value, selection) {
8816
9621
  return {
8817
9622
  version: 1,
8818
9623
  runId: normalizeWebuiSubagentText(value.runId, 160) || selection.run.id,
8819
- source: value.source === "foreground" ? "foreground" : "async",
9624
+ source: normalizeWebuiSubagentSource(selection.run?.source || value.source),
8820
9625
  mode: ["single", "parallel", "chain"].includes(value.mode) ? value.mode : selection.run.mode,
8821
9626
  startedAt: Number.isFinite(value.startedAt) ? value.startedAt : selection.run.startedAt,
8822
9627
  updatedAt: Number.isFinite(value.updatedAt) ? value.updatedAt : Date.now(),
@@ -8901,12 +9706,14 @@ async function restorableTabsForRestart() {
8901
9706
  return mergeRestorableTabDescriptors(liveDescriptors);
8902
9707
  }
8903
9708
 
8904
- function spawnRestartServer(restorableTabs) {
9709
+ function spawnRestartServer(restorableTabs, supervisorCursor) {
8905
9710
  const env = {
8906
9711
  ...process.env,
8907
9712
  PI_WEBUI_RESTORE_TABS: JSON.stringify(restorableTabs || []),
8908
9713
  PI_WEBUI_START_DELAY_MS: "1200",
8909
9714
  };
9715
+ if (supervisorCursor) env.PI_WEBUI_RPC_SUPERVISOR_CURSOR = JSON.stringify(supervisorCursor);
9716
+ else delete env.PI_WEBUI_RPC_SUPERVISOR_CURSOR;
8910
9717
  if (webuiDevServer) env.PI_WEBUI_DEV = "1";
8911
9718
  else delete env.PI_WEBUI_DEV;
8912
9719
  const child = spawn(process.execPath, process.argv.slice(1), {
@@ -9369,7 +10176,8 @@ async function runPiUpdateAndPrepareRestart({ all = false } = {}) {
9369
10176
 
9370
10177
  updateStatusCache = null;
9371
10178
  updateStatusCacheAt = 0;
9372
- const child = spawnRestartServer(restorableTabs);
10179
+ const supervisorCursor = await prepareRpcSupervisorHandoff();
10180
+ const child = spawnRestartServer(restorableTabs, supervisorCursor);
9373
10181
  restartPrepared = true;
9374
10182
  recordEvent({ type: "webui_update_restarting", command, updateAll: all, nextWebuiPid: child.pid, restorableTabCount: restorableTabs.length });
9375
10183
  return {
@@ -9437,6 +10245,7 @@ function renameTab(tab, title, { source = "explicit", maxLength, unique = source
9437
10245
  tab.title = nextTitle;
9438
10246
  tab.titleSource = source;
9439
10247
  if (previousTitle === nextTitle) return false;
10248
+ scheduleSupervisorMetadataUpdate(tab);
9440
10249
 
9441
10250
  broadcastTabEvent(tab, {
9442
10251
  type: "webui_tab_renamed",
@@ -9454,6 +10263,7 @@ function maybeNameTabForConversation(tab, command) {
9454
10263
  if (!tab || !commandStartsConversation(command)) return false;
9455
10264
  const shouldRename = !tab.conversationStarted && tab.titleSource !== "explicit";
9456
10265
  tab.conversationStarted = true;
10266
+ scheduleSupervisorMetadataUpdate(tab);
9457
10267
  if (!shouldRename) return false;
9458
10268
  const title = generatedTabTitleFromPrompt(command.message) || `Conversation ${tab.index}`;
9459
10269
  return renameTab(tab, title, { source: "auto", maxLength: AUTO_TAB_TITLE_MAX_LENGTH });
@@ -9467,9 +10277,23 @@ function responseWithTab(response, tab) {
9467
10277
  async function updateTabCwd(id, cwd) {
9468
10278
  const tab = tabs.get(id);
9469
10279
  if (!tab) throw makeHttpError(404, `Unknown Pi tab: ${id}`);
10280
+ if (tab.cwdChangeInProgress) throw makeHttpError(409, `${tab.title} is already changing its working folder`);
10281
+
10282
+ tab.cwdChangeInProgress = true;
10283
+ try {
10284
+ return await performTabCwdUpdate(tab, cwd);
10285
+ } finally {
10286
+ tab.cwdChangeInProgress = false;
10287
+ scheduleSupervisorMetadataUpdate(tab);
10288
+ }
10289
+ }
9470
10290
 
10291
+ async function performTabCwdUpdate(tab, cwd) {
9471
10292
  const nextCwd = await resolveCwd(cwd, tab.cwd);
9472
10293
  if (nextCwd === tab.cwd) return { tab, changed: false };
10294
+ if (tab.rpc instanceof SupervisorPiRpcProcess && !tab.rpc.supervisor.isCurrentVersion()) {
10295
+ throw makeHttpError(503, "The detached Pi supervisor is from an older WebUI build. Fully shut down Pi WebUI (not Restart), then start it again before changing working folders.");
10296
+ }
9473
10297
 
9474
10298
  // Capture the live session before stopping the old RPC so the conversation
9475
10299
  // survives the cwd restart, mirroring restartTabRpc. Best-effort: a dead RPC
@@ -9480,27 +10304,47 @@ async function updateTabCwd(id, cwd) {
9480
10304
  const piArgs = await buildPiArgsForTab(tab.index, tab.title, nextCwd);
9481
10305
  if (sessionFile && !options.noSession) piArgs.push("--session", sessionFile);
9482
10306
  const piCommand = await resolvePiCommand(piArgs);
9483
- gitLiveWatcher.unsubscribe(tab.id);
9484
10307
  const restartingEvent = { type: "webui_tab_restarting", tabId: tab.id, tabTitle: tab.title, cwd: nextCwd, sessionFile };
9485
10308
  broadcastTabEvent(tab, restartingEvent);
9486
10309
 
9487
10310
  const oldRpc = tab.rpc;
9488
- tab.rpcUnsubscribe?.();
9489
- tab.rpcUnsubscribe = undefined;
9490
10311
  rejectTabBashQueue(tab, new Error("Pi tab is restarting; queued bash commands were cancelled"));
9491
10312
  stopAppRunnerForTab(tab, "cwd changed", { force: true });
9492
- oldRpc.stop();
9493
-
9494
- tab.cwd = nextCwd;
9495
- resetTabActivity(tab);
9496
10313
  clearPendingExtensionUiRequests(tab);
9497
10314
  clearExtensionStatuses(tab);
9498
10315
  clearExtensionWidgets(tab);
9499
10316
  clearWebuiSubagents(tab);
9500
10317
  resetNaturalConversationMode(tab);
9501
- const rpc = new PiRpcProcess({ ...piCommand, cwd: tab.cwd, env: piRpcEnvironment() });
10318
+
10319
+ let rpc;
10320
+ let startDirectRpc = false;
10321
+ try {
10322
+ if (oldRpc instanceof SupervisorPiRpcProcess) {
10323
+ const snapshot = await oldRpc.replace({
10324
+ child: { command: piCommand.command, args: piCommand.args, cwd: nextCwd },
10325
+ metadata: supervisedTabMetadata(tab, { cwd: nextCwd }),
10326
+ displayCommand: piCommand.displayCommand,
10327
+ });
10328
+ oldRpc.dispose();
10329
+ rpc = new SupervisorPiRpcProcess({ supervisor: rpcSupervisor, tabId: tab.id, displayCommand: piCommand.displayCommand, cwd: nextCwd, snapshot });
10330
+ } else {
10331
+ oldRpc.stop();
10332
+ rpc = new PiRpcProcess({ ...piCommand, cwd: nextCwd, env: piRpcEnvironment() });
10333
+ startDirectRpc = true;
10334
+ }
10335
+ } catch (error) {
10336
+ const detail = sanitizeError(error);
10337
+ broadcastTabEvent(tab, { type: "webui_cwd_change_failed", tabId: tab.id, tabTitle: tab.title, cwd: nextCwd, error: detail });
10338
+ throw makeHttpError(502, `Could not restart ${tab.title} in ${displayPath(nextCwd)}: ${detail}`);
10339
+ }
10340
+
10341
+ tab.rpcUnsubscribe?.();
10342
+ tab.rpcUnsubscribe = undefined;
10343
+ tab.cwd = nextCwd;
10344
+ resetTabActivity(tab);
9502
10345
  attachRpcToTab(tab, rpc);
9503
- rpc.start();
10346
+ if (startDirectRpc) rpc.start();
10347
+ gitLiveWatcher.unsubscribe(tab.id);
9504
10348
  // Non-fatal: a failed start surfaces through pi_process_error/exit events.
9505
10349
  await primeTabRpc(tab).catch(() => {});
9506
10350
 
@@ -9526,7 +10370,6 @@ async function restartTabRpc(tab, reason = "reload") {
9526
10370
  tab.rpcUnsubscribe?.();
9527
10371
  tab.rpcUnsubscribe = undefined;
9528
10372
  rejectTabBashQueue(tab, new Error("Pi tab is reloading; queued bash commands were cancelled"));
9529
- oldRpc.stop();
9530
10373
 
9531
10374
  resetTabActivity(tab);
9532
10375
  clearPendingExtensionUiRequests(tab);
@@ -9534,9 +10377,22 @@ async function restartTabRpc(tab, reason = "reload") {
9534
10377
  clearExtensionWidgets(tab);
9535
10378
  clearWebuiSubagents(tab);
9536
10379
  resetNaturalConversationMode(tab);
9537
- const rpc = new PiRpcProcess({ ...piCommand, cwd: tab.cwd, env: piRpcEnvironment() });
9538
- attachRpcToTab(tab, rpc);
9539
- rpc.start();
10380
+ let rpc;
10381
+ if (oldRpc instanceof SupervisorPiRpcProcess) {
10382
+ const snapshot = await oldRpc.replace({
10383
+ child: { command: piCommand.command, args: piCommand.args, cwd: tab.cwd },
10384
+ metadata: supervisedTabMetadata(tab),
10385
+ displayCommand: piCommand.displayCommand,
10386
+ });
10387
+ oldRpc.dispose();
10388
+ rpc = new SupervisorPiRpcProcess({ supervisor: rpcSupervisor, tabId: tab.id, displayCommand: piCommand.displayCommand, cwd: tab.cwd, snapshot });
10389
+ attachRpcToTab(tab, rpc);
10390
+ } else {
10391
+ oldRpc.stop();
10392
+ rpc = new PiRpcProcess({ ...piCommand, cwd: tab.cwd, env: piRpcEnvironment() });
10393
+ attachRpcToTab(tab, rpc);
10394
+ rpc.start();
10395
+ }
9540
10396
 
9541
10397
  const reloadedEvent = { type: "webui_tab_reloaded", tabId: tab.id, tabTitle: tab.title, cwd: tab.cwd, pid: tab.rpc.child?.pid, reason, sessionFile: state.data?.sessionFile, tabActivity: tabActivitySnapshot(tab) };
9542
10398
  broadcastTabEvent(tab, reloadedEvent);
@@ -11305,6 +12161,7 @@ async function switchTabSession(tab, sessionPath) {
11305
12161
  if (response.success === false) return response;
11306
12162
  if (!response.data?.cancelled) {
11307
12163
  tab.cwd = manager.getCwd();
12164
+ scheduleSupervisorMetadataUpdate(tab);
11308
12165
  const state = await safeRpcData(tab, { type: "get_state" }, STATUS_RPC_TIMEOUT_MS);
11309
12166
  if (state.ok) rememberTabState(tab, state.data);
11310
12167
  }
@@ -11656,7 +12513,8 @@ async function closeTab(id) {
11656
12513
  tab.rpcUnsubscribe?.();
11657
12514
  rejectTabBashQueue(tab, new Error("Pi tab closed; queued bash commands were cancelled"));
11658
12515
  stopAppRunnerForTab(tab, "tab closed", { force: true });
11659
- tab.rpc.stop();
12516
+ await tab.rpc.stop();
12517
+ tab.rpc.dispose?.();
11660
12518
  tabs.delete(id);
11661
12519
  return tab;
11662
12520
  }
@@ -11667,7 +12525,8 @@ async function discardTab(tab) {
11667
12525
  tab.rpcUnsubscribe?.();
11668
12526
  rejectTabBashQueue(tab, new Error("Pi recovery tab initialization failed"));
11669
12527
  stopAppRunnerForTab(tab, "recovery initialization failed", { force: true });
11670
- tab.rpc.stop();
12528
+ await tab.rpc.stop();
12529
+ tab.rpc.dispose?.();
11671
12530
  tabs.delete(tab.id);
11672
12531
  }
11673
12532
 
@@ -11766,6 +12625,8 @@ function directoryPickerActiveCwd(req, url, body = {}) {
11766
12625
  }
11767
12626
 
11768
12627
  async function createInitialTabs() {
12628
+ const managedTabs = await hydrateManagedTabs(rpcSupervisorSnapshot);
12629
+ if (rpcSupervisorSnapshot?.tabs?.length) return managedTabs;
11769
12630
  if (!restoreTabs.length) return options.cwdExplicit ? [await createTab()] : [];
11770
12631
 
11771
12632
  const created = [];
@@ -11784,7 +12645,11 @@ const serverStartedAt = new Date().toISOString();
11784
12645
  const persistedStartupSettings = await readWebuiSettings(undefined, { reportInvalidOutputMode: true });
11785
12646
  let persistedRemoteAuthEnabled = persistedStartupSettings.remoteAuthEnabled === true;
11786
12647
  let persistedOutputModeDefault = persistedStartupSettings.outputModeDefault;
12648
+ rpcSupervisor = await initializeRpcSupervisor();
12649
+ rpcSupervisorSnapshot = rpcSupervisor?.snapshot || null;
12650
+ installRpcSupervisorEventDispatch(rpcSupervisorSnapshot);
11787
12651
  const initialTabs = await createInitialTabs();
12652
+ await finishRpcSupervisorStartup(initialTabs);
11788
12653
  const initialTab = initialTabs[0];
11789
12654
  let currentHost = options.host;
11790
12655
  let networkRebindInProgress = false;
@@ -12223,6 +13088,7 @@ async function webuiStatus({ detailed = false, eventLimit = 40, includeAuthPin =
12223
13088
  pageUrl: network.localUrl,
12224
13089
  boundUrl: `http://${formatUrlHost(currentHost)}:${options.port}/`,
12225
13090
  network,
13091
+ rpcSupervisor: rpcSupervisorDiagnostics(),
12226
13092
  piPid: tab?.rpc.child?.pid,
12227
13093
  piRunning: !!tab?.rpc.child && tab.rpc.child.exitCode === null,
12228
13094
  outputMode: outputModeMetadata(),
@@ -12276,6 +13142,37 @@ const server = createServer(async (req, res) => {
12276
13142
  return;
12277
13143
  }
12278
13144
 
13145
+ if (url.pathname === "/api/workflow-policy" && req.method === "GET") {
13146
+ requireLocalhost(req, "Workflow policy setup is only allowed from localhost.");
13147
+ try {
13148
+ const policyModule = await workflowPolicyModule();
13149
+ const state = await policyModule.readWorkflowPolicyState({ agentDir });
13150
+ // Suggestions are advisory helpers only and are never part of the persisted v1 policy.
13151
+ sendJson(res, 200, { ok: true, data: { ...state, suggestions: policyModule.WORKFLOW_POLICY_SUGGESTIONS } });
13152
+ } catch (error) {
13153
+ throw workflowPolicyRequestError(error);
13154
+ }
13155
+ return;
13156
+ }
13157
+
13158
+ if (url.pathname === "/api/workflow-policy" && req.method === "POST") {
13159
+ requireLocalhostRoute(req, url.pathname);
13160
+ requireWorkflowPolicyJsonRequest(req);
13161
+ const body = workflowPolicySaveBody(await readJsonBody(req));
13162
+ ensureWorkflowPolicyMutationAllowed();
13163
+ try {
13164
+ const policyModule = await workflowPolicyModule();
13165
+ sendJson(res, 200, { ok: true, data: await policyModule.writeWorkflowPolicyState({
13166
+ agentDir,
13167
+ policy: body.policy,
13168
+ expectedRevision: body.expectedRevision,
13169
+ }) });
13170
+ } catch (error) {
13171
+ throw workflowPolicyRequestError(error);
13172
+ }
13173
+ return;
13174
+ }
13175
+
12279
13176
  if (url.pathname === "/api/remote-auth/settings" && req.method === "POST") {
12280
13177
  requireLocalhostRoute(req, url.pathname);
12281
13178
  const body = await readJsonBody(req);
@@ -12410,7 +13307,24 @@ const server = createServer(async (req, res) => {
12410
13307
  tabActivity: tabActivitySnapshot(tab),
12411
13308
  pendingExtensionUiRequestCount: pendingExtensionUiRequests(tab).length,
12412
13309
  activeRun: publicAppRunnerState(tab.appRunner),
13310
+ ...rpcSupervisorBrowserState(),
12413
13311
  });
13312
+ if (rpcSupervisor) {
13313
+ sendSseToClient(client, {
13314
+ type: "webui_supervisor_reconnected",
13315
+ tabId: tab.id,
13316
+ tabTitle: tab.title,
13317
+ ...rpcSupervisorBrowserState(),
13318
+ });
13319
+ if (rpcSupervisorSnapshot?.gap === true) {
13320
+ sendSseToClient(client, {
13321
+ type: "webui_supervisor_replay_gap",
13322
+ tabId: tab.id,
13323
+ tabTitle: tab.title,
13324
+ ...rpcSupervisorBrowserState(),
13325
+ });
13326
+ }
13327
+ }
12414
13328
  replayExtensionStatuses(tab, client);
12415
13329
  replayExtensionWidgets(tab, client);
12416
13330
  replayPendingExtensionUiRequests(tab, client);
@@ -12436,6 +13350,7 @@ const server = createServer(async (req, res) => {
12436
13350
  cwd: status.cwd,
12437
13351
  outputMode: status.outputMode,
12438
13352
  network: status.network,
13353
+ rpcSupervisor: status.rpcSupervisor,
12439
13354
  tabs: status.tabs,
12440
13355
  restorableTabs: status.restorableTabs,
12441
13356
  });
@@ -12552,9 +13467,10 @@ const server = createServer(async (req, res) => {
12552
13467
  if (url.pathname === "/api/restart" && req.method === "POST") {
12553
13468
  requireLocalhostRoute(req, url.pathname);
12554
13469
  const restorableTabs = await restorableTabsForRestart();
12555
- const child = spawnRestartServer(restorableTabs);
13470
+ const supervisorCursor = await prepareRpcSupervisorHandoff();
13471
+ const child = spawnRestartServer(restorableTabs, supervisorCursor);
12556
13472
  sendJson(res, 200, { ok: true, message: "Pi Web UI restarting", webuiPid: process.pid, nextWebuiPid: child.pid, restorableTabCount: restorableTabs.length });
12557
- setTimeout(() => shutdown("api restart"), 20).unref();
13473
+ setTimeout(() => { void shutdown("api restart", { preserveSessions: true }); }, 20).unref();
12558
13474
  return;
12559
13475
  }
12560
13476
 
@@ -12565,14 +13481,14 @@ const server = createServer(async (req, res) => {
12565
13481
  const bodyAll = body?.all === true || String(body?.mode || "").toLowerCase() === "all";
12566
13482
  const data = await runPiUpdateAndPrepareRestart({ all: queryAll || bodyAll });
12567
13483
  sendJson(res, 200, { ok: true, data });
12568
- setTimeout(() => shutdown("api update"), 20).unref();
13484
+ setTimeout(() => { void shutdown("api update", { preserveSessions: true }); }, 20).unref();
12569
13485
  return;
12570
13486
  }
12571
13487
 
12572
13488
  if (url.pathname === "/api/shutdown" && req.method === "POST") {
12573
13489
  requireLocalhostRoute(req, url.pathname);
12574
13490
  sendJson(res, 200, { ok: true, message: "Pi Web UI shutting down", webuiPid: process.pid });
12575
- setTimeout(() => shutdown("api shutdown"), 20).unref();
13491
+ setTimeout(() => { void shutdown("api shutdown", { preserveSessions: false }); }, 20).unref();
12576
13492
  return;
12577
13493
  }
12578
13494
 
@@ -12644,7 +13560,12 @@ const server = createServer(async (req, res) => {
12644
13560
  const body = await readJsonBody(req);
12645
13561
  const tab = getRequestedTab(req, url, body);
12646
13562
  ensureNaturalConversationRouteAllowed(tab, "app runner configuration changes are blocked");
12647
- sendJson(res, 200, { ok: true, data: await saveCustomAppRunner(tab, body.runner || body) });
13563
+ if (Object.prototype.hasOwnProperty.call(body, "searchPaths")) {
13564
+ if (body.runner !== undefined) throw makeHttpError(400, "Choose either a custom runner or searchPaths for this mutation");
13565
+ sendJson(res, 200, { ok: true, data: await saveAppRunnerSearchPaths(tab, body.searchPaths) });
13566
+ } else {
13567
+ sendJson(res, 200, { ok: true, data: await saveCustomAppRunner(tab, body.runner || body) });
13568
+ }
12648
13569
  return;
12649
13570
  }
12650
13571
 
@@ -13120,6 +14041,18 @@ const server = createServer(async (req, res) => {
13120
14041
  return;
13121
14042
  }
13122
14043
 
14044
+ if (url.pathname === "/api/git-file-diff" && req.method === "GET") {
14045
+ const tab = getRequestedTab(req, url);
14046
+ try {
14047
+ const data = await readGitFileDiff(tab.cwd, url.searchParams.get("path") || "", url.searchParams.get("category") || "");
14048
+ trackGitRepositoryForTab(tab, data.root);
14049
+ sendJson(res, 200, { ok: true, data });
14050
+ } catch (error) {
14051
+ sendJson(res, 200, { ok: false, error: sanitizeError(error) });
14052
+ }
14053
+ return;
14054
+ }
14055
+
13123
14056
  if (url.pathname === "/api/git-root" && req.method === "GET") {
13124
14057
  const tab = getRequestedTab(req, url);
13125
14058
  try {
@@ -13425,11 +14358,7 @@ server.on("error", (error) => {
13425
14358
  return;
13426
14359
  }
13427
14360
  console.error("Web UI server failed:", sanitizeError(error));
13428
- for (const tab of tabs.values()) {
13429
- stopAppRunnerForTab(tab, "server error", { force: true });
13430
- tab.rpc.stop();
13431
- }
13432
- process.exit(1);
14361
+ void shutdown("server error", { preserveSessions: true, exitCode: 1 });
13433
14362
  });
13434
14363
 
13435
14364
  function sweepWebuiTempArtifacts() {
@@ -13452,24 +14381,51 @@ server.listen(options.port, currentHost, () => {
13452
14381
  }
13453
14382
  });
13454
14383
 
13455
- function shutdown(signal) {
14384
+ let shutdownInProgress = false;
14385
+
14386
+ async function shutdown(signal, { preserveSessions = false, exitCode = 0 } = {}) {
14387
+ if (shutdownInProgress) return;
14388
+ shutdownInProgress = true;
13456
14389
  console.log(`\n${signal}: shutting down Pi Web UI...`);
13457
14390
  gitLiveWatcher.closeAll();
14391
+ for (const tab of tabs.values()) stopAppRunnerForTab(tab, "server shutdown", { force: true });
14392
+
14393
+ const forceExit = setTimeout(() => process.exit(exitCode), 4000);
14394
+ forceExit.unref?.();
14395
+ try {
14396
+ if (rpcSupervisor) {
14397
+ if (preserveSessions) await detachRpcSupervisor();
14398
+ else {
14399
+ try {
14400
+ if (rpcSupervisor.isConnected()) await rpcSupervisor.shutdown();
14401
+ } finally {
14402
+ rpcSupervisor.close();
14403
+ rpcSupervisor = null;
14404
+ }
14405
+ }
14406
+ } else {
14407
+ await Promise.all([...tabs.values()].map((tab) => Promise.resolve(tab.rpc.stop()).catch(() => {})));
14408
+ }
14409
+ } catch (error) {
14410
+ console.error("Web UI RPC shutdown failed:", sanitizeError(error));
14411
+ }
14412
+
13458
14413
  const forceCloseTimer = setTimeout(() => {
13459
14414
  server.closeAllConnections?.();
13460
14415
  }, NETWORK_REBIND_FORCE_CLOSE_MS);
13461
14416
  forceCloseTimer.unref?.();
13462
- server.close(() => {
13463
- clearTimeout(forceCloseTimer);
13464
- process.exit(0);
14417
+ await new Promise((resolve) => {
14418
+ if (!server.listening) {
14419
+ resolve();
14420
+ return;
14421
+ }
14422
+ server.close(() => resolve());
14423
+ server.closeIdleConnections?.();
13465
14424
  });
13466
- server.closeIdleConnections?.();
13467
- for (const tab of tabs.values()) {
13468
- stopAppRunnerForTab(tab, "server shutdown", { force: true });
13469
- tab.rpc.stop();
13470
- }
13471
- setTimeout(() => process.exit(0), 4000).unref();
14425
+ clearTimeout(forceCloseTimer);
14426
+ clearTimeout(forceExit);
14427
+ process.exit(exitCode);
13472
14428
  }
13473
14429
 
13474
- process.on("SIGINT", () => shutdown("SIGINT"));
13475
- process.on("SIGTERM", () => shutdown("SIGTERM"));
14430
+ process.on("SIGINT", () => { void shutdown("SIGINT", { preserveSessions: false }); });
14431
+ process.on("SIGTERM", () => { void shutdown("SIGTERM", { preserveSessions: true }); });