@firstpick/pi-package-webui 0.7.6 → 0.7.7

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 (39) hide show
  1. package/README.md +37 -4
  2. package/bin/pi-webui-rpc-supervisor.mjs +518 -0
  3. package/bin/pi-webui.mjs +1003 -82
  4. package/lib/WEBUI_TUI_NATIVE_PARITY.json +13 -0
  5. package/lib/rpc-supervisor-client.mjs +301 -0
  6. package/lib/rpc-supervisor-protocol.mjs +236 -0
  7. package/lib/rpc-supervisor-state.mjs +165 -0
  8. package/lib/trust-boundaries.mjs +1 -0
  9. package/package.json +2 -2
  10. package/public/app.js +1237 -82
  11. package/public/index.html +334 -25
  12. package/public/service-worker.js +6 -1
  13. package/public/styles.css +366 -52
  14. package/public/subagent-gate-visibility.mjs +36 -0
  15. package/public/workflow-status-stack.mjs +69 -0
  16. package/tests/app-runner-process-tree-harness.test.mjs +37 -3
  17. package/tests/boot-failure-diagnostics.test.mjs +180 -0
  18. package/tests/durable-rpc-supervisor-harness.test.mjs +252 -0
  19. package/tests/fast-mode-client-static.test.mjs +2 -2
  20. package/tests/fixtures/compacting-pi.mjs +0 -0
  21. package/tests/fixtures/fake-pi.mjs +81 -2
  22. package/tests/git-panel-file-preview-static.test.mjs +221 -0
  23. package/tests/http-endpoints-harness.test.mjs +458 -33
  24. package/tests/mobile-static.test.mjs +74 -12
  25. package/tests/native-parity-harness.test.mjs +2 -1
  26. package/tests/native-parity.test.mjs +11 -0
  27. package/tests/numpad-decimal-input-static.test.mjs +128 -0
  28. package/tests/prompt-routing-input-clear-static.test.mjs +34 -0
  29. package/tests/prompt-routing-tab-status.test.mjs +103 -0
  30. package/tests/rpc-supervisor-host.test.mjs +275 -0
  31. package/tests/rpc-supervisor-protocol.test.mjs +67 -0
  32. package/tests/rpc-supervisor-state.test.mjs +62 -0
  33. package/tests/run-all.mjs +4 -1
  34. package/tests/streaming-ui-coupling.test.mjs +15 -0
  35. package/tests/subagent-gate-visibility.test.mjs +66 -0
  36. package/tests/subagent-launch-slots-static.test.mjs +1 -1
  37. package/tests/subagents-helper.test.mjs +136 -0
  38. package/tests/workflow-status-stack.test.mjs +87 -0
  39. 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", "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,205 @@ 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) {
8414
+ return {
8415
+ index: tab.index,
8416
+ title: tab.title,
8417
+ titleSource: tab.titleSource,
8418
+ conversationStarted: tab.conversationStarted === true,
8419
+ cwd: tab.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) || tab.supervisorMetadataUpdateQueued) return;
8428
+ tab.supervisorMetadataUpdateQueued = true;
8429
+ queueMicrotask(() => {
8430
+ tab.supervisorMetadataUpdateQueued = false;
8431
+ if (!(tab.rpc instanceof SupervisorPiRpcProcess) || !tabs.has(tab.id)) return;
8432
+ void tab.rpc.updateMetadata(supervisedTabMetadata(tab)).catch((error) => {
8433
+ console.warn(`failed to update managed Pi tab metadata: ${sanitizeError(error)}`);
8434
+ });
8435
+ });
8436
+ }
8437
+
8438
+ function rpcSupervisorDiagnostics() {
8439
+ if (!rpcSupervisor) return { enabled: false, attached: false, managedTabCount: 0 };
8440
+ return {
8441
+ enabled: true,
8442
+ attached: rpcSupervisor.isConnected(),
8443
+ managedTabCount: tabs.size,
8444
+ };
8445
+ }
8446
+
8447
+ function rpcSupervisorBrowserState() {
8448
+ if (!rpcSupervisor || !rpcSupervisorSnapshot) return {};
8449
+ return {
8450
+ supervisorScopeId: rpcSupervisorSnapshot.scopeId,
8451
+ supervisorEpoch: rpcSupervisorSnapshot.epoch,
8452
+ supervisorReplayGap: rpcSupervisorSnapshot.gap === true,
8453
+ };
8454
+ }
8455
+
8456
+ async function prepareRpcSupervisorHandoff() {
8457
+ if (!rpcSupervisor) return undefined;
8458
+ const handoff = await rpcSupervisor.prepareHandoff();
8459
+ return { epoch: handoff.epoch, seq: handoff.latestSeq };
8460
+ }
8461
+
8462
+ async function detachRpcSupervisor() {
8463
+ if (!rpcSupervisor) return;
8464
+ try {
8465
+ if (rpcSupervisor.isConnected()) await rpcSupervisor.detach();
8466
+ } finally {
8467
+ rpcSupervisorEventUnsubscribe?.();
8468
+ rpcSupervisorEventUnsubscribe = null;
8469
+ rpcSupervisor.close();
8470
+ rpcSupervisor = null;
8471
+ }
8472
+ }
7765
8473
  const TAB_ACTIVITY_IDLE_RECONCILE_GRACE_MS = 1200;
7766
8474
  const TAB_ACTIVITY_STATE_RECONCILE_INTERVAL_MS = 2500;
7767
8475
  const TAB_ACTIVITY_STATE_RECONCILE_TIMEOUT_MS = 1200;
@@ -7774,6 +8482,7 @@ function rememberTabState(tab, state) {
7774
8482
  if (!tab || !state || typeof state !== "object") return;
7775
8483
  tab.lastState = state;
7776
8484
  if (!options.noSession && Object.prototype.hasOwnProperty.call(state, "sessionFile")) tab.sessionFile = sessionFileFromState(state);
8485
+ scheduleSupervisorMetadataUpdate(tab);
7777
8486
  }
7778
8487
 
7779
8488
  function patchTabState(tab, patch) {
@@ -7817,6 +8526,7 @@ function forgetTabState(tab) {
7817
8526
  tab.lastState = null;
7818
8527
  tab.sessionFile = undefined;
7819
8528
  tab.pendingThinkingLevel = undefined;
8529
+ scheduleSupervisorMetadataUpdate(tab);
7820
8530
  }
7821
8531
 
7822
8532
  function tabRestorableSessionFile(tab) {
@@ -7891,6 +8601,10 @@ function normalizeWebuiSubagentText(value, maxLength = 240) {
7891
8601
  return text ? text.slice(0, maxLength) : "";
7892
8602
  }
7893
8603
 
8604
+ function normalizeWebuiSubagentSource(value) {
8605
+ return value === "foreground" || value === "workflow" ? value : "async";
8606
+ }
8607
+
7894
8608
  function normalizeWebuiSubagentPayload(value) {
7895
8609
  if (!value || typeof value !== "object" || value.version !== 1) return null;
7896
8610
  const runs = [];
@@ -7917,7 +8631,7 @@ function normalizeWebuiSubagentPayload(value) {
7917
8631
  if (!agents.length) continue;
7918
8632
  runs.push({
7919
8633
  id,
7920
- source: rawRun.source === "foreground" ? "foreground" : "async",
8634
+ source: normalizeWebuiSubagentSource(rawRun.source),
7921
8635
  mode: ["single", "parallel", "chain"].includes(rawRun.mode) ? rawRun.mode : "single",
7922
8636
  status: "running",
7923
8637
  startedAt: Number.isFinite(rawRun.startedAt) ? rawRun.startedAt : Date.now(),
@@ -8598,27 +9312,14 @@ function attachRpcToTab(tab, rpc) {
8598
9312
  });
8599
9313
  }
8600
9314
 
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();
9315
+ function createTabRecord({ id, index, title, titleSource, conversationStarted, cwd, createdAt = new Date().toISOString(), sessionFile, gitWorkspace, rpc }) {
8615
9316
  const tab = {
8616
9317
  id,
8617
- index: tabIndex,
8618
- title: tabTitle,
8619
- titleSource: resolvedTitleSource,
9318
+ index,
9319
+ title,
9320
+ titleSource,
8620
9321
  conversationStarted: conversationStarted === true,
8621
- cwd: tabCwd,
9322
+ cwd,
8622
9323
  createdAt,
8623
9324
  sessionFile: options.noSession ? undefined : normalizedRestoreString(sessionFile, 4096),
8624
9325
  gitWorkspace: gitWorkspace || null,
@@ -8637,20 +9338,61 @@ async function createTab({ id: requestedId, index, title, titleSource, conversat
8637
9338
  bashQueueDraining: false,
8638
9339
  compactionQueue: [],
8639
9340
  compactionQueueDraining: false,
8640
- rpc: undefined,
9341
+ rpc,
8641
9342
  rpcUnsubscribe: undefined,
8642
9343
  sseClients: new Set(),
8643
9344
  };
8644
9345
  resetNaturalConversationMode(tab);
9346
+ return tab;
9347
+ }
9348
+
9349
+ async function createTab({ id: requestedId, index, title, titleSource, conversationStarted, cwd, sessionFile, gitWorkspace } = {}) {
9350
+ const tabIndex = Number.isInteger(index) && index > 0 ? index : nextTabIndex;
9351
+ nextTabIndex = Math.max(nextTabIndex, tabIndex + 1);
9352
+ const explicitTitle = String(title || "").trim();
9353
+ const tabTitle = explicitTitle || defaultTabTitle(tabIndex);
9354
+ const titleIsExplicit = Boolean(explicitTitle || (options.name && tabIndex === 1));
9355
+ const resolvedTitleSource = ["explicit", "auto", "default"].includes(titleSource) ? titleSource : titleIsExplicit ? "explicit" : "default";
9356
+ const tabCwd = cwd ? await resolveCwd(cwd, options.cwd) : options.cwd;
9357
+ const id = requestedId && !tabs.has(requestedId) ? requestedId : randomUUID();
9358
+ const piArgs = await buildPiArgsForTab(tabIndex, tabTitle, tabCwd);
9359
+ if (sessionFile && !options.noSession) piArgs.push("--session", sessionFile);
9360
+ const piCommand = await resolvePiCommand(piArgs);
9361
+ const createdAt = new Date().toISOString();
9362
+ const rpc = rpcSupervisor
9363
+ ? new SupervisorPiRpcProcess({ supervisor: rpcSupervisor, tabId: id, displayCommand: piCommand.displayCommand, cwd: tabCwd, snapshot: { startedAt: createdAt, running: false } })
9364
+ : new PiRpcProcess({ ...piCommand, cwd: tabCwd, env: piRpcEnvironment() });
9365
+ const tab = createTabRecord({
9366
+ id,
9367
+ index: tabIndex,
9368
+ title: tabTitle,
9369
+ titleSource: resolvedTitleSource,
9370
+ conversationStarted,
9371
+ cwd: tabCwd,
9372
+ createdAt,
9373
+ sessionFile,
9374
+ gitWorkspace,
9375
+ rpc,
9376
+ });
8645
9377
 
8646
9378
  attachRpcToTab(tab, rpc);
8647
9379
  tabs.set(id, tab);
8648
- rpc.start();
8649
9380
  try {
9381
+ if (rpc instanceof SupervisorPiRpcProcess) {
9382
+ const snapshot = await rpcSupervisor.createTab({
9383
+ tabId: id,
9384
+ metadata: supervisedTabMetadata(tab),
9385
+ child: { command: piCommand.command, args: piCommand.args, cwd: tabCwd },
9386
+ });
9387
+ rpc.applySnapshot(snapshot);
9388
+ } else {
9389
+ rpc.start();
9390
+ }
8650
9391
  await primeTabRpc(tab);
8651
9392
  } catch (error) {
8652
9393
  if (!tab.rpc.isRunning()) {
8653
9394
  tab.rpcUnsubscribe?.();
9395
+ rpc.dispose?.();
8654
9396
  gitLiveWatcher.unsubscribe(id);
8655
9397
  tabs.delete(id);
8656
9398
  throw new Error(`Pi RPC process failed while starting ${tabTitle}: ${sanitizeError(error)}`);
@@ -8662,6 +9404,56 @@ async function createTab({ id: requestedId, index, title, titleSource, conversat
8662
9404
  return tab;
8663
9405
  }
8664
9406
 
9407
+ async function hydrateManagedTabs(snapshot) {
9408
+ const managedTabs = Array.isArray(snapshot?.tabs) ? snapshot.tabs : [];
9409
+ if (!managedTabs.length) return [];
9410
+ const hydrated = [];
9411
+ try {
9412
+ for (const managed of managedTabs) {
9413
+ const metadata = managed?.metadata;
9414
+ const descriptor = normalizeRestoreTabDescriptor({ id: managed?.id, ...metadata }, new Set());
9415
+ if (!descriptor?.id || !descriptor.cwd || tabs.has(descriptor.id)) {
9416
+ throw new Error("RPC supervisor returned invalid or duplicate managed tab metadata");
9417
+ }
9418
+ const tabIndex = Number.isInteger(descriptor.index) && descriptor.index > 0 ? descriptor.index : nextTabIndex;
9419
+ nextTabIndex = Math.max(nextTabIndex, tabIndex + 1);
9420
+ const tabTitle = descriptor.title || defaultTabTitle(tabIndex);
9421
+ const resolvedTitleSource = ["explicit", "auto", "default"].includes(descriptor.titleSource) ? descriptor.titleSource : "default";
9422
+ const rpc = new SupervisorPiRpcProcess({
9423
+ supervisor: rpcSupervisor,
9424
+ tabId: descriptor.id,
9425
+ cwd: descriptor.cwd,
9426
+ snapshot: managed,
9427
+ });
9428
+ const tab = createTabRecord({
9429
+ id: descriptor.id,
9430
+ index: tabIndex,
9431
+ title: tabTitle,
9432
+ titleSource: resolvedTitleSource,
9433
+ conversationStarted: descriptor.conversationStarted,
9434
+ cwd: descriptor.cwd,
9435
+ createdAt: normalizedRestoreString(metadata?.createdAt, 128) || managed.startedAt || new Date().toISOString(),
9436
+ sessionFile: descriptor.sessionFile,
9437
+ gitWorkspace: metadata?.gitWorkspace || null,
9438
+ rpc,
9439
+ });
9440
+ attachRpcToTab(tab, rpc);
9441
+ tabs.set(tab.id, tab);
9442
+ hydrated.push(tab);
9443
+ }
9444
+ } catch (error) {
9445
+ for (const tab of hydrated) {
9446
+ tab.rpcUnsubscribe?.();
9447
+ tab.rpc.dispose?.();
9448
+ tabs.delete(tab.id);
9449
+ }
9450
+ throw error;
9451
+ }
9452
+
9453
+ for (const event of snapshot.replay || []) dispatchRpcSupervisorEvent(event);
9454
+ return hydrated;
9455
+ }
9456
+
8665
9457
  function firstTab() {
8666
9458
  return tabs.values().next().value;
8667
9459
  }
@@ -8816,7 +9608,7 @@ function normalizeWebuiSubagentOutput(value, selection) {
8816
9608
  return {
8817
9609
  version: 1,
8818
9610
  runId: normalizeWebuiSubagentText(value.runId, 160) || selection.run.id,
8819
- source: value.source === "foreground" ? "foreground" : "async",
9611
+ source: normalizeWebuiSubagentSource(selection.run?.source || value.source),
8820
9612
  mode: ["single", "parallel", "chain"].includes(value.mode) ? value.mode : selection.run.mode,
8821
9613
  startedAt: Number.isFinite(value.startedAt) ? value.startedAt : selection.run.startedAt,
8822
9614
  updatedAt: Number.isFinite(value.updatedAt) ? value.updatedAt : Date.now(),
@@ -8901,12 +9693,14 @@ async function restorableTabsForRestart() {
8901
9693
  return mergeRestorableTabDescriptors(liveDescriptors);
8902
9694
  }
8903
9695
 
8904
- function spawnRestartServer(restorableTabs) {
9696
+ function spawnRestartServer(restorableTabs, supervisorCursor) {
8905
9697
  const env = {
8906
9698
  ...process.env,
8907
9699
  PI_WEBUI_RESTORE_TABS: JSON.stringify(restorableTabs || []),
8908
9700
  PI_WEBUI_START_DELAY_MS: "1200",
8909
9701
  };
9702
+ if (supervisorCursor) env.PI_WEBUI_RPC_SUPERVISOR_CURSOR = JSON.stringify(supervisorCursor);
9703
+ else delete env.PI_WEBUI_RPC_SUPERVISOR_CURSOR;
8910
9704
  if (webuiDevServer) env.PI_WEBUI_DEV = "1";
8911
9705
  else delete env.PI_WEBUI_DEV;
8912
9706
  const child = spawn(process.execPath, process.argv.slice(1), {
@@ -9369,7 +10163,8 @@ async function runPiUpdateAndPrepareRestart({ all = false } = {}) {
9369
10163
 
9370
10164
  updateStatusCache = null;
9371
10165
  updateStatusCacheAt = 0;
9372
- const child = spawnRestartServer(restorableTabs);
10166
+ const supervisorCursor = await prepareRpcSupervisorHandoff();
10167
+ const child = spawnRestartServer(restorableTabs, supervisorCursor);
9373
10168
  restartPrepared = true;
9374
10169
  recordEvent({ type: "webui_update_restarting", command, updateAll: all, nextWebuiPid: child.pid, restorableTabCount: restorableTabs.length });
9375
10170
  return {
@@ -9437,6 +10232,7 @@ function renameTab(tab, title, { source = "explicit", maxLength, unique = source
9437
10232
  tab.title = nextTitle;
9438
10233
  tab.titleSource = source;
9439
10234
  if (previousTitle === nextTitle) return false;
10235
+ scheduleSupervisorMetadataUpdate(tab);
9440
10236
 
9441
10237
  broadcastTabEvent(tab, {
9442
10238
  type: "webui_tab_renamed",
@@ -9454,6 +10250,7 @@ function maybeNameTabForConversation(tab, command) {
9454
10250
  if (!tab || !commandStartsConversation(command)) return false;
9455
10251
  const shouldRename = !tab.conversationStarted && tab.titleSource !== "explicit";
9456
10252
  tab.conversationStarted = true;
10253
+ scheduleSupervisorMetadataUpdate(tab);
9457
10254
  if (!shouldRename) return false;
9458
10255
  const title = generatedTabTitleFromPrompt(command.message) || `Conversation ${tab.index}`;
9459
10256
  return renameTab(tab, title, { source: "auto", maxLength: AUTO_TAB_TITLE_MAX_LENGTH });
@@ -9489,7 +10286,6 @@ async function updateTabCwd(id, cwd) {
9489
10286
  tab.rpcUnsubscribe = undefined;
9490
10287
  rejectTabBashQueue(tab, new Error("Pi tab is restarting; queued bash commands were cancelled"));
9491
10288
  stopAppRunnerForTab(tab, "cwd changed", { force: true });
9492
- oldRpc.stop();
9493
10289
 
9494
10290
  tab.cwd = nextCwd;
9495
10291
  resetTabActivity(tab);
@@ -9498,9 +10294,22 @@ async function updateTabCwd(id, cwd) {
9498
10294
  clearExtensionWidgets(tab);
9499
10295
  clearWebuiSubagents(tab);
9500
10296
  resetNaturalConversationMode(tab);
9501
- const rpc = new PiRpcProcess({ ...piCommand, cwd: tab.cwd, env: piRpcEnvironment() });
9502
- attachRpcToTab(tab, rpc);
9503
- rpc.start();
10297
+ let rpc;
10298
+ if (oldRpc instanceof SupervisorPiRpcProcess) {
10299
+ const snapshot = await oldRpc.replace({
10300
+ child: { command: piCommand.command, args: piCommand.args, cwd: tab.cwd },
10301
+ metadata: supervisedTabMetadata(tab),
10302
+ displayCommand: piCommand.displayCommand,
10303
+ });
10304
+ oldRpc.dispose();
10305
+ rpc = new SupervisorPiRpcProcess({ supervisor: rpcSupervisor, tabId: tab.id, displayCommand: piCommand.displayCommand, cwd: tab.cwd, snapshot });
10306
+ attachRpcToTab(tab, rpc);
10307
+ } else {
10308
+ oldRpc.stop();
10309
+ rpc = new PiRpcProcess({ ...piCommand, cwd: tab.cwd, env: piRpcEnvironment() });
10310
+ attachRpcToTab(tab, rpc);
10311
+ rpc.start();
10312
+ }
9504
10313
  // Non-fatal: a failed start surfaces through pi_process_error/exit events.
9505
10314
  await primeTabRpc(tab).catch(() => {});
9506
10315
 
@@ -9526,7 +10335,6 @@ async function restartTabRpc(tab, reason = "reload") {
9526
10335
  tab.rpcUnsubscribe?.();
9527
10336
  tab.rpcUnsubscribe = undefined;
9528
10337
  rejectTabBashQueue(tab, new Error("Pi tab is reloading; queued bash commands were cancelled"));
9529
- oldRpc.stop();
9530
10338
 
9531
10339
  resetTabActivity(tab);
9532
10340
  clearPendingExtensionUiRequests(tab);
@@ -9534,9 +10342,22 @@ async function restartTabRpc(tab, reason = "reload") {
9534
10342
  clearExtensionWidgets(tab);
9535
10343
  clearWebuiSubagents(tab);
9536
10344
  resetNaturalConversationMode(tab);
9537
- const rpc = new PiRpcProcess({ ...piCommand, cwd: tab.cwd, env: piRpcEnvironment() });
9538
- attachRpcToTab(tab, rpc);
9539
- rpc.start();
10345
+ let rpc;
10346
+ if (oldRpc instanceof SupervisorPiRpcProcess) {
10347
+ const snapshot = await oldRpc.replace({
10348
+ child: { command: piCommand.command, args: piCommand.args, cwd: tab.cwd },
10349
+ metadata: supervisedTabMetadata(tab),
10350
+ displayCommand: piCommand.displayCommand,
10351
+ });
10352
+ oldRpc.dispose();
10353
+ rpc = new SupervisorPiRpcProcess({ supervisor: rpcSupervisor, tabId: tab.id, displayCommand: piCommand.displayCommand, cwd: tab.cwd, snapshot });
10354
+ attachRpcToTab(tab, rpc);
10355
+ } else {
10356
+ oldRpc.stop();
10357
+ rpc = new PiRpcProcess({ ...piCommand, cwd: tab.cwd, env: piRpcEnvironment() });
10358
+ attachRpcToTab(tab, rpc);
10359
+ rpc.start();
10360
+ }
9540
10361
 
9541
10362
  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
10363
  broadcastTabEvent(tab, reloadedEvent);
@@ -11305,6 +12126,7 @@ async function switchTabSession(tab, sessionPath) {
11305
12126
  if (response.success === false) return response;
11306
12127
  if (!response.data?.cancelled) {
11307
12128
  tab.cwd = manager.getCwd();
12129
+ scheduleSupervisorMetadataUpdate(tab);
11308
12130
  const state = await safeRpcData(tab, { type: "get_state" }, STATUS_RPC_TIMEOUT_MS);
11309
12131
  if (state.ok) rememberTabState(tab, state.data);
11310
12132
  }
@@ -11656,7 +12478,8 @@ async function closeTab(id) {
11656
12478
  tab.rpcUnsubscribe?.();
11657
12479
  rejectTabBashQueue(tab, new Error("Pi tab closed; queued bash commands were cancelled"));
11658
12480
  stopAppRunnerForTab(tab, "tab closed", { force: true });
11659
- tab.rpc.stop();
12481
+ await tab.rpc.stop();
12482
+ tab.rpc.dispose?.();
11660
12483
  tabs.delete(id);
11661
12484
  return tab;
11662
12485
  }
@@ -11667,7 +12490,8 @@ async function discardTab(tab) {
11667
12490
  tab.rpcUnsubscribe?.();
11668
12491
  rejectTabBashQueue(tab, new Error("Pi recovery tab initialization failed"));
11669
12492
  stopAppRunnerForTab(tab, "recovery initialization failed", { force: true });
11670
- tab.rpc.stop();
12493
+ await tab.rpc.stop();
12494
+ tab.rpc.dispose?.();
11671
12495
  tabs.delete(tab.id);
11672
12496
  }
11673
12497
 
@@ -11766,6 +12590,8 @@ function directoryPickerActiveCwd(req, url, body = {}) {
11766
12590
  }
11767
12591
 
11768
12592
  async function createInitialTabs() {
12593
+ const managedTabs = await hydrateManagedTabs(rpcSupervisorSnapshot);
12594
+ if (rpcSupervisorSnapshot?.tabs?.length) return managedTabs;
11769
12595
  if (!restoreTabs.length) return options.cwdExplicit ? [await createTab()] : [];
11770
12596
 
11771
12597
  const created = [];
@@ -11784,7 +12610,11 @@ const serverStartedAt = new Date().toISOString();
11784
12610
  const persistedStartupSettings = await readWebuiSettings(undefined, { reportInvalidOutputMode: true });
11785
12611
  let persistedRemoteAuthEnabled = persistedStartupSettings.remoteAuthEnabled === true;
11786
12612
  let persistedOutputModeDefault = persistedStartupSettings.outputModeDefault;
12613
+ rpcSupervisor = await initializeRpcSupervisor();
12614
+ rpcSupervisorSnapshot = rpcSupervisor?.snapshot || null;
12615
+ installRpcSupervisorEventDispatch(rpcSupervisorSnapshot);
11787
12616
  const initialTabs = await createInitialTabs();
12617
+ await finishRpcSupervisorStartup(initialTabs);
11788
12618
  const initialTab = initialTabs[0];
11789
12619
  let currentHost = options.host;
11790
12620
  let networkRebindInProgress = false;
@@ -12223,6 +13053,7 @@ async function webuiStatus({ detailed = false, eventLimit = 40, includeAuthPin =
12223
13053
  pageUrl: network.localUrl,
12224
13054
  boundUrl: `http://${formatUrlHost(currentHost)}:${options.port}/`,
12225
13055
  network,
13056
+ rpcSupervisor: rpcSupervisorDiagnostics(),
12226
13057
  piPid: tab?.rpc.child?.pid,
12227
13058
  piRunning: !!tab?.rpc.child && tab.rpc.child.exitCode === null,
12228
13059
  outputMode: outputModeMetadata(),
@@ -12276,6 +13107,37 @@ const server = createServer(async (req, res) => {
12276
13107
  return;
12277
13108
  }
12278
13109
 
13110
+ if (url.pathname === "/api/workflow-policy" && req.method === "GET") {
13111
+ requireLocalhost(req, "Workflow policy setup is only allowed from localhost.");
13112
+ try {
13113
+ const policyModule = await workflowPolicyModule();
13114
+ const state = await policyModule.readWorkflowPolicyState({ agentDir });
13115
+ // Suggestions are advisory helpers only and are never part of the persisted v1 policy.
13116
+ sendJson(res, 200, { ok: true, data: { ...state, suggestions: policyModule.WORKFLOW_POLICY_SUGGESTIONS } });
13117
+ } catch (error) {
13118
+ throw workflowPolicyRequestError(error);
13119
+ }
13120
+ return;
13121
+ }
13122
+
13123
+ if (url.pathname === "/api/workflow-policy" && req.method === "POST") {
13124
+ requireLocalhostRoute(req, url.pathname);
13125
+ requireWorkflowPolicyJsonRequest(req);
13126
+ const body = workflowPolicySaveBody(await readJsonBody(req));
13127
+ ensureWorkflowPolicyMutationAllowed();
13128
+ try {
13129
+ const policyModule = await workflowPolicyModule();
13130
+ sendJson(res, 200, { ok: true, data: await policyModule.writeWorkflowPolicyState({
13131
+ agentDir,
13132
+ policy: body.policy,
13133
+ expectedRevision: body.expectedRevision,
13134
+ }) });
13135
+ } catch (error) {
13136
+ throw workflowPolicyRequestError(error);
13137
+ }
13138
+ return;
13139
+ }
13140
+
12279
13141
  if (url.pathname === "/api/remote-auth/settings" && req.method === "POST") {
12280
13142
  requireLocalhostRoute(req, url.pathname);
12281
13143
  const body = await readJsonBody(req);
@@ -12410,7 +13272,24 @@ const server = createServer(async (req, res) => {
12410
13272
  tabActivity: tabActivitySnapshot(tab),
12411
13273
  pendingExtensionUiRequestCount: pendingExtensionUiRequests(tab).length,
12412
13274
  activeRun: publicAppRunnerState(tab.appRunner),
13275
+ ...rpcSupervisorBrowserState(),
12413
13276
  });
13277
+ if (rpcSupervisor) {
13278
+ sendSseToClient(client, {
13279
+ type: "webui_supervisor_reconnected",
13280
+ tabId: tab.id,
13281
+ tabTitle: tab.title,
13282
+ ...rpcSupervisorBrowserState(),
13283
+ });
13284
+ if (rpcSupervisorSnapshot?.gap === true) {
13285
+ sendSseToClient(client, {
13286
+ type: "webui_supervisor_replay_gap",
13287
+ tabId: tab.id,
13288
+ tabTitle: tab.title,
13289
+ ...rpcSupervisorBrowserState(),
13290
+ });
13291
+ }
13292
+ }
12414
13293
  replayExtensionStatuses(tab, client);
12415
13294
  replayExtensionWidgets(tab, client);
12416
13295
  replayPendingExtensionUiRequests(tab, client);
@@ -12436,6 +13315,7 @@ const server = createServer(async (req, res) => {
12436
13315
  cwd: status.cwd,
12437
13316
  outputMode: status.outputMode,
12438
13317
  network: status.network,
13318
+ rpcSupervisor: status.rpcSupervisor,
12439
13319
  tabs: status.tabs,
12440
13320
  restorableTabs: status.restorableTabs,
12441
13321
  });
@@ -12552,9 +13432,10 @@ const server = createServer(async (req, res) => {
12552
13432
  if (url.pathname === "/api/restart" && req.method === "POST") {
12553
13433
  requireLocalhostRoute(req, url.pathname);
12554
13434
  const restorableTabs = await restorableTabsForRestart();
12555
- const child = spawnRestartServer(restorableTabs);
13435
+ const supervisorCursor = await prepareRpcSupervisorHandoff();
13436
+ const child = spawnRestartServer(restorableTabs, supervisorCursor);
12556
13437
  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();
13438
+ setTimeout(() => { void shutdown("api restart", { preserveSessions: true }); }, 20).unref();
12558
13439
  return;
12559
13440
  }
12560
13441
 
@@ -12565,14 +13446,14 @@ const server = createServer(async (req, res) => {
12565
13446
  const bodyAll = body?.all === true || String(body?.mode || "").toLowerCase() === "all";
12566
13447
  const data = await runPiUpdateAndPrepareRestart({ all: queryAll || bodyAll });
12567
13448
  sendJson(res, 200, { ok: true, data });
12568
- setTimeout(() => shutdown("api update"), 20).unref();
13449
+ setTimeout(() => { void shutdown("api update", { preserveSessions: true }); }, 20).unref();
12569
13450
  return;
12570
13451
  }
12571
13452
 
12572
13453
  if (url.pathname === "/api/shutdown" && req.method === "POST") {
12573
13454
  requireLocalhostRoute(req, url.pathname);
12574
13455
  sendJson(res, 200, { ok: true, message: "Pi Web UI shutting down", webuiPid: process.pid });
12575
- setTimeout(() => shutdown("api shutdown"), 20).unref();
13456
+ setTimeout(() => { void shutdown("api shutdown", { preserveSessions: false }); }, 20).unref();
12576
13457
  return;
12577
13458
  }
12578
13459
 
@@ -12644,7 +13525,12 @@ const server = createServer(async (req, res) => {
12644
13525
  const body = await readJsonBody(req);
12645
13526
  const tab = getRequestedTab(req, url, body);
12646
13527
  ensureNaturalConversationRouteAllowed(tab, "app runner configuration changes are blocked");
12647
- sendJson(res, 200, { ok: true, data: await saveCustomAppRunner(tab, body.runner || body) });
13528
+ if (Object.prototype.hasOwnProperty.call(body, "searchPaths")) {
13529
+ if (body.runner !== undefined) throw makeHttpError(400, "Choose either a custom runner or searchPaths for this mutation");
13530
+ sendJson(res, 200, { ok: true, data: await saveAppRunnerSearchPaths(tab, body.searchPaths) });
13531
+ } else {
13532
+ sendJson(res, 200, { ok: true, data: await saveCustomAppRunner(tab, body.runner || body) });
13533
+ }
12648
13534
  return;
12649
13535
  }
12650
13536
 
@@ -13120,6 +14006,18 @@ const server = createServer(async (req, res) => {
13120
14006
  return;
13121
14007
  }
13122
14008
 
14009
+ if (url.pathname === "/api/git-file-diff" && req.method === "GET") {
14010
+ const tab = getRequestedTab(req, url);
14011
+ try {
14012
+ const data = await readGitFileDiff(tab.cwd, url.searchParams.get("path") || "", url.searchParams.get("category") || "");
14013
+ trackGitRepositoryForTab(tab, data.root);
14014
+ sendJson(res, 200, { ok: true, data });
14015
+ } catch (error) {
14016
+ sendJson(res, 200, { ok: false, error: sanitizeError(error) });
14017
+ }
14018
+ return;
14019
+ }
14020
+
13123
14021
  if (url.pathname === "/api/git-root" && req.method === "GET") {
13124
14022
  const tab = getRequestedTab(req, url);
13125
14023
  try {
@@ -13425,11 +14323,7 @@ server.on("error", (error) => {
13425
14323
  return;
13426
14324
  }
13427
14325
  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);
14326
+ void shutdown("server error", { preserveSessions: true, exitCode: 1 });
13433
14327
  });
13434
14328
 
13435
14329
  function sweepWebuiTempArtifacts() {
@@ -13452,24 +14346,51 @@ server.listen(options.port, currentHost, () => {
13452
14346
  }
13453
14347
  });
13454
14348
 
13455
- function shutdown(signal) {
14349
+ let shutdownInProgress = false;
14350
+
14351
+ async function shutdown(signal, { preserveSessions = false, exitCode = 0 } = {}) {
14352
+ if (shutdownInProgress) return;
14353
+ shutdownInProgress = true;
13456
14354
  console.log(`\n${signal}: shutting down Pi Web UI...`);
13457
14355
  gitLiveWatcher.closeAll();
14356
+ for (const tab of tabs.values()) stopAppRunnerForTab(tab, "server shutdown", { force: true });
14357
+
14358
+ const forceExit = setTimeout(() => process.exit(exitCode), 4000);
14359
+ forceExit.unref?.();
14360
+ try {
14361
+ if (rpcSupervisor) {
14362
+ if (preserveSessions) await detachRpcSupervisor();
14363
+ else {
14364
+ try {
14365
+ if (rpcSupervisor.isConnected()) await rpcSupervisor.shutdown();
14366
+ } finally {
14367
+ rpcSupervisor.close();
14368
+ rpcSupervisor = null;
14369
+ }
14370
+ }
14371
+ } else {
14372
+ await Promise.all([...tabs.values()].map((tab) => Promise.resolve(tab.rpc.stop()).catch(() => {})));
14373
+ }
14374
+ } catch (error) {
14375
+ console.error("Web UI RPC shutdown failed:", sanitizeError(error));
14376
+ }
14377
+
13458
14378
  const forceCloseTimer = setTimeout(() => {
13459
14379
  server.closeAllConnections?.();
13460
14380
  }, NETWORK_REBIND_FORCE_CLOSE_MS);
13461
14381
  forceCloseTimer.unref?.();
13462
- server.close(() => {
13463
- clearTimeout(forceCloseTimer);
13464
- process.exit(0);
14382
+ await new Promise((resolve) => {
14383
+ if (!server.listening) {
14384
+ resolve();
14385
+ return;
14386
+ }
14387
+ server.close(() => resolve());
14388
+ server.closeIdleConnections?.();
13465
14389
  });
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();
14390
+ clearTimeout(forceCloseTimer);
14391
+ clearTimeout(forceExit);
14392
+ process.exit(exitCode);
13472
14393
  }
13473
14394
 
13474
- process.on("SIGINT", () => shutdown("SIGINT"));
13475
- process.on("SIGTERM", () => shutdown("SIGTERM"));
14395
+ process.on("SIGINT", () => { void shutdown("SIGINT", { preserveSessions: false }); });
14396
+ process.on("SIGTERM", () => { void shutdown("SIGTERM", { preserveSessions: true }); });