@firstpick/pi-package-webui 0.10.2 → 0.10.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/DEVELOPMENT.md +28 -0
  2. package/README.md +10 -0
  3. package/TECHNICAL.md +14 -0
  4. package/bin/pi-webui.mjs +236 -20
  5. package/lib/append-system-selection.mjs +311 -0
  6. package/lib/git-workflow-preferences.mjs +6 -0
  7. package/lib/trust-boundaries.mjs +37 -0
  8. package/package.json +2 -2
  9. package/public/app.js +215 -30
  10. package/public/index.html +5 -2
  11. package/public/service-worker.js +1 -1
  12. package/public/styles.css +9 -0
  13. package/tests/append-system-http.test.mjs +622 -0
  14. package/tests/append-system-selection.test.mjs +259 -0
  15. package/tests/append-system-selector-static.test.mjs +95 -0
  16. package/tests/boot-failure-diagnostics.test.mjs +2 -2
  17. package/tests/browser/stats-overlay.spec.mjs +13 -0
  18. package/tests/codex-fast-mode-static.test.mjs +2 -2
  19. package/tests/common-options-submenus-interaction-static.test.mjs +4 -0
  20. package/tests/common-options-submenus-markup-static.test.mjs +2 -1
  21. package/tests/composer-action-grid-reorder-static.test.mjs +2 -2
  22. package/tests/control-visibility-static.test.mjs +2 -2
  23. package/tests/controls-layout-static.test.mjs +2 -2
  24. package/tests/events-tree-context-menu-static.test.mjs +2 -2
  25. package/tests/fast-mode-client-static.test.mjs +1 -1
  26. package/tests/feature-decision-output-popup-static.test.mjs +1 -1
  27. package/tests/feature-system-prompt-optional-feature-static.test.mjs +1 -1
  28. package/tests/file-viewer-image-static.test.mjs +2 -2
  29. package/tests/fixtures/fake-pi.mjs +9 -1
  30. package/tests/guided-git-activation-static.test.mjs +2 -2
  31. package/tests/guided-git-fallback-ui-static.test.mjs +2 -2
  32. package/tests/intercom-conversation-viewer-static.test.mjs +2 -2
  33. package/tests/main-output-loading-static.test.mjs +2 -2
  34. package/tests/middle-button-drag-scroll-static.test.mjs +2 -2
  35. package/tests/mobile-continuity-tablet-static.test.mjs +2 -2
  36. package/tests/mobile-foundation-static.test.mjs +2 -2
  37. package/tests/mobile-phone-experience-static.test.mjs +1 -1
  38. package/tests/native-parity-harness.test.mjs +7 -0
  39. package/tests/open-issue-wizard-static.test.mjs +1 -1
  40. package/tests/optional-feature-prompt-impact-static.test.mjs +2 -2
  41. package/tests/persistent-ui-layout-static.test.mjs +2 -2
  42. package/tests/prompt-input-vertical-scroll-static.test.mjs +2 -2
  43. package/tests/questionnaire-dialog.test.mjs +2 -2
  44. package/tests/session-sampling-ui-static.test.mjs +2 -2
  45. package/tests/side-panel-section-height-removal-static.test.mjs +2 -2
  46. package/tests/stats-dashboard-static.test.mjs +11 -0
  47. package/tests/subagent-observability-static.test.mjs +2 -2
  48. package/tests/syntax-highlighting-static.test.mjs +2 -2
  49. package/tests/terminal-tab-prompt-tooltip-static.test.mjs +147 -0
  50. package/tests/terminal-tab-workspace-static.test.mjs +1 -1
  51. package/tests/theme-customizer-static.test.mjs +1 -1
  52. package/tests/windows-drive-cwd-picker-static.test.mjs +2 -2
package/DEVELOPMENT.md CHANGED
@@ -14,6 +14,34 @@ Focused contributor validation:
14
14
  node tests/resource-tui-extension.test.mjs
15
15
  ```
16
16
 
17
+ ## Append-system prompt picker contract
18
+
19
+ The browser exposes one global `APPEND_SYSTEM.md` override through the native selector flow in `public/app.js`:
20
+
21
+ - `openNativeAppendSystemSelector` opens the shared native command dialog, fetches `GET /api/append-system-files?tab=<id>` via `nativeCommandApi`, and renders the returned candidates through the shared `renderNativeSelectorItems` implementation (filter input and keyboard navigation included). Candidate labels are visible alias paths and warn that followed targets can be outside the displayed root. It marks the saved candidate `current`, marks `Use Pi default discovery` current when no valid override is saved, and shows an invalid saved `appendSystemPromptPath` as a disabled row with a diagnostic. Scan `diagnostics` render as a bounded note (first 20 entries, kind/path/message only); prompt file contents are never fetched.
22
+ - Selecting an item posts `POST /api/append-system-selection` with `{ tabId, path }` (`path: null` for Pi default discovery). The save itself never reloads a tab. Only a response with `changed: true` and `restartRequired: true` proceeds to `confirmAppendSystemRestart`, which asks through the shared `appConfirmText` confirmation and, on approval, reuses the standard active-tab reload path (`sendPrompt("prompt", "/reload", { targetTabId, throwOnError: true })`); reload errors are surfaced in the events log. Cancellation keeps the saved choice for the next manual reload or new tab.
23
+ - The command palette lists the action as `/append-system` so the flow stays reachable from the browser-native settings surface.
24
+
25
+ Endpoint data contract (server side owned by the discovery/persistence workstream): `GET /api/append-system-files?tab=<id>` returns `appendSystemPromptPath` (saved override or `null`), `roots` (`{ path, label }`), bounded `candidates` (`{ path, rootLabel }`), bounded `diagnostics` (`{ kind, path, message }`), and `limits`. Discovery follows symlinked roots, directory entries, and exact-visible-name file links, including external targets, while candidate identity remains the visible absolute alias. Canonical directory identities are internal cycle/deduplication keys only. A provenance-valid global choice outside the active tab's roots is included as one deduplicated `Saved selection` candidate. `POST /api/append-system-selection` accepts `{ tabId, path }` and returns the same scan payload plus `changed` and `restartRequired`; it never returns file contents. Changed selections must be candidates of a fresh active-tab scan, while the exact provenance-valid saved path may be submitted unchanged from another project.
26
+
27
+ The exact lexical global Pi default `path.join(homedir(), ".pi", "agent", "APPEND_SYSTEM.md")` is excluded during discovery before candidate-limit accounting. Existing and submitted selections equal to it are normalized to `null` default discovery, so they do not produce an invalid saved row or `--append-system-prompt` override. No other global, nested, or project-local candidate is excluded.
28
+
29
+ Private settings persist both `appendSystemPromptPath` and its lexical `appendSystemPromptRootPath`. Child launch revalidates lexical containment, the exact visible name, the depth-10 bound, and the final followed target's regular-file status. The followed target may be outside the saved root, while the visible saved alias is passed unchanged to Pi. Broken, inaccessible, and non-regular targets fail closed. This intentionally allows a link to scan or load a prompt outside the two visible roots; canonical target identity is not persisted, and the accepted retargeting/validation-to-open race remains.
30
+
31
+ Each successful WebUI-managed Pi launch captures its validated selected path as tab-local runtime metadata. `tabMeta.prompt` and detached-supervisor metadata use only `null` or `{ "kind": "append-system", "path": "<absolute visible path>" }`. The path is capped at 4096 characters and cannot contain C0 control characters (`U+0000`–`U+001F`) or DEL (`U+007F`); restored values must also have exactly those two fields, the known kind, and an absolute path, or normalization returns `null`. Discovery omits candidates with those controls, and fresh or restored selections containing them fail closed. Tabs created by older builds therefore restore without a custom-prompt claim. Supervisor hydration retains valid descriptors, while supervised replacement stays atomic and direct create, working-folder replacement, and full reload update the live tab only after the child emits its successful spawn event.
32
+
33
+ Direct-mode `pi_process_start` is emitted from that child `spawn` event. A failed spawn emits `pi_process_error` without a preceding start. A failed direct working-folder replacement retains the prior live cwd and prompt descriptor and leaves cwd-dependent watcher subscriptions on that prior cwd; cwd, activity, prompt, and watcher publication move together only after the replacement spawn succeeds.
34
+
35
+ This descriptor comes directly from the validated saved selection used while constructing that process launch. It is never reconstructed from current global settings or by scanning final child arguments, so later selection changes do not rewrite existing tabs and arbitrary launcher `--append-system-prompt` values remain outside this contract. Prompt file contents, inline launcher text, and unrelated arguments are not copied into the descriptor.
36
+
37
+ Focused contributor validation:
38
+
39
+ ```bash
40
+ node tests/append-system-selection.test.mjs
41
+ node tests/append-system-http.test.mjs
42
+ node tests/append-system-selector-static.test.mjs
43
+ ```
44
+
17
45
  ## Web UI settings write lock
18
46
 
19
47
  `updateWebuiSettings` serializes same-process updates and uses per-writer records under `<settings-file>.lock` for cross-process writes. A process can exit after creating its record but before writing valid JSON, leaving an empty file. Lock acquisition removes incomplete records immediately when their PID is dead. It gives a live writer a one-second grace period, then removes records that are still empty or malformed so one interrupted write cannot block every later settings save.
package/README.md CHANGED
@@ -172,6 +172,16 @@ Enable tools for the current session, save a global default, or configure an exa
172
172
 
173
173
  Find installed skills and manage session, global, or exact-model activation. Selecting a configured model automatically applies its skill profile unless the session has its own skill selection. Pi's TUI `/skills` command belongs to the optional `@firstpick/pi-extension-setup-skills` companion and uses the same Session, Global, and Model scopes; WebUI does not register a competing command.
174
174
 
175
+ #### Append-system prompt picker
176
+
177
+ **Optional feature needed:** None. It is included in Pi Web UI core.
178
+
179
+ Choose one `APPEND_SYSTEM.md` file as a global append-system prompt for WebUI-managed Pi tabs. Open **Common Pi options**, choose **Feature Setup**, then select **Append-system Prompt**. You can also open the command palette and run **/append-system**. The picker shows files found by a bounded scan below your home `~/.pi` folder and the active tab's working directory, ready to filter and select. It follows file and folder links, including links to locations outside those two folders, while keeping the visible linked path in the list. The current choice is marked, and **Use Pi default discovery** removes the override again. Pi's exact global default file, `~/.pi/agent/APPEND_SYSTEM.md`, is represented by that default choice rather than a duplicate file row. Other files below `~/.pi`, including nested alternatives, remain selectable. Scan diagnostics explain when limits omit results; [TECHNICAL.md](TECHNICAL.md) lists the limits. The picker only shows file paths; it never edits or displays prompt file contents.
180
+
181
+ Saving the choice does not change a running Pi session by itself. After a changed save, the Web UI asks whether to restart the active Pi tab now; cancel keeps the saved choice for the next manual reload or new tab. Because the choice is global, it also applies to every new tab you open afterward. Pick files and links carefully: a followed link can scan or load a prompt from anywhere the Web UI process can read, and an append prompt changes Pi's high-priority instructions.
182
+
183
+ Hover a terminal tab to see the effective WebUI-selected non-default `APPEND_SYSTEM.md` visible path. Tabs using Pi's default discovery omit this line. Existing tabs keep their launch-time information until their Pi process is fully restarted or the tab is recreated, and the tooltip never reads or shows prompt contents.
184
+
175
185
  ### Project automation and Git
176
186
 
177
187
  #### App runners
package/TECHNICAL.md CHANGED
@@ -204,6 +204,20 @@ Tracked skill files appear as selectable tags above the composer. The strip keep
204
204
 
205
205
  When the browser page is hidden, the Web UI closes that page's live event stream so the browser cannot accumulate serialized output frames for later parsing and DOM rendering. Merely moving focus to another visible window does not pause streaming. On return, it first fetches authoritative tabs, state, and transcript snapshots, reconnects live events, and refreshes nonessential panels during browser idle time. Pending extension prompts are replayed by the server after reconnection, and completed output remains available from the authoritative transcript.
206
206
 
207
+ ## Append-system prompt selection
208
+
209
+ The command palette action **/append-system** opens a picker for one global WebUI append-system prompt override. The scan starts from exactly two visible roots: the active Pi tab's working directory and your `~/.pi` folder. It checks at most 2,048 directories to a maximum visible-path depth of 10, returns at most 256 candidates and 64 diagnostics, and matches only the exact case-sensitive visible filename `APPEND_SYSTEM.md`. Root, folder, and file symbolic links are followed, including links whose targets are outside both visible roots. Candidate rows keep the visible linked path. Broken links and links to unsupported file types are skipped with bounded diagnostics, and the scan never reads or displays prompt contents.
210
+
211
+ **Trust warning:** a followed link can make the picker scan directories or load a prompt anywhere the Web UI process can read. Check both the link and its current target before selecting it. Link cycles and repeated targets remain bounded, but a link may be retargeted later.
212
+
213
+ The saved choice is a global WebUI setting, discovered through the active tab's working directory but applied to every new or reloaded WebUI Pi tab. It persists in private WebUI settings and its visible path is passed to newly launched Pi processes as a `--append-system-prompt` argument; a running session keeps its current instructions until restart. The exact global default path `~/.pi/agent/APPEND_SYSTEM.md` is not shown as a separate candidate because **Use Pi default discovery** already represents it. Submitting or previously saving that exact path is also treated as default discovery, without a redundant launcher override. Project-local defaults and nested alternatives such as `~/.pi/agent/minimal/APPEND_SYSTEM.md` remain selectable.
214
+
215
+ After a changed save the picker asks once whether to restart the active Pi tab. Cancel keeps the saved choice ready for the next manual reload or new tab. A saved visible path remains valid if its followed target changes to another regular file. If the link breaks, resolves to an unsupported type, or the visible path otherwise stops being valid, it stays visible in the picker marked as invalid with a diagnostic, and launching falls back to Pi's normal `APPEND_SYSTEM.md` discovery until you pick a valid file or choose **Use Pi default discovery**.
216
+
217
+ Hover a terminal tab to see `Append-system prompt: <path>` when that tab's Pi process started with an effective WebUI-selected non-default prompt. A grouped item reports its own prompt, while a collapsed group reports its active represented tab. Tabs using default discovery omit the line. Changing the saved choice does not rewrite existing tabs; their launch-time information changes only after a full Pi-process restart or tab recreation. The tooltip displays only the validated visible path and never reads or shows prompt contents.
218
+
219
+ Discovery and saving are localhost-only; a request rejected from a non-local browser shows a clear error in the picker and changes nothing. User-supplied Pi launcher arguments are still appended after the saved override. Pi appends repeatable `--append-system-prompt` inputs in argument order, so both the saved prompt and any later launcher prompts contribute in that order.
220
+
207
221
  ## Events and session-tree navigation
208
222
 
209
223
  Visible non-Intercom tool start, finish, and failure rows in **Events** show the tool name, lifecycle status, a shortened call ID, completion duration when a matching start was observed, and a bounded path only for a small set of file-oriented tools. The panel never displays unrestricted arguments, raw results, or tool output. Select any event row to keep the existing jump-to-chat behavior.
package/bin/pi-webui.mjs CHANGED
@@ -21,6 +21,13 @@ import {
21
21
  validateTheme,
22
22
  } from "../public/theme-contract.mjs";
23
23
  import { authProvidersPayload, createAuthContext, logoutStoredProvider } from "../lib/auth-actions.mjs";
24
+ import {
25
+ APPEND_SYSTEM_DIAGNOSTIC_MESSAGES,
26
+ APPEND_SYSTEM_DISCOVERY_LIMITS,
27
+ discoverAppendSystemFiles,
28
+ validateAppendSystemSelection,
29
+ validateSavedAppendSystemSelection,
30
+ } from "../lib/append-system-selection.mjs";
24
31
  import { resolveCodexUsageAuth } from "../lib/codex-usage-auth.mjs";
25
32
  import { AgentRunIndex, canonicalAgentRunId, normalizeAgentInstance } from "../lib/agent-run-protocol.mjs";
26
33
  import { AgentRunRegistry } from "../lib/agent-run-registry.mjs";
@@ -138,6 +145,7 @@ import {
138
145
  evaluateDispatchTrustGuards,
139
146
  guardsForNativeCommand,
140
147
  isLocalRequest,
148
+ isLoopbackHostAuthority,
141
149
  projectTrustDecision,
142
150
  remoteShellTrustWarning,
143
151
  requireLocalhost,
@@ -320,6 +328,7 @@ const PATH_SUGGESTION_SCAN_LIMIT = 5000;
320
328
  const PATH_SUGGESTION_MAX_OUTPUT_LENGTH = 300000;
321
329
  const PATH_SUGGESTION_EXCLUDED_DIRS = new Set([".git", "node_modules"]);
322
330
  const RESTORE_TAB_LIMIT = 256;
331
+ const TAB_PROMPT_PATH_MAX_LENGTH = 4096;
323
332
  const UPDATE_HEALTH_GATE_MS = Math.max(90_000, Number.parseInt(process.env.PI_WEBUI_UPDATE_HEALTH_GATE_MS || "90000", 10) || 90_000);
324
333
  const bootIdentity = randomUUID();
325
334
  const SESSION_SELECTOR_LIMIT = 200;
@@ -954,6 +963,7 @@ class PiRpcProcess {
954
963
  this.cwd = cwd;
955
964
  this.env = env;
956
965
  this.child = undefined;
966
+ this.spawned = false;
957
967
  this.pending = new Map();
958
968
  this.listeners = new Set();
959
969
  this.startedAt = new Date().toISOString();
@@ -970,6 +980,7 @@ class PiRpcProcess {
970
980
  }
971
981
 
972
982
  start() {
983
+ this.spawned = false;
973
984
  this.child = spawn(this.command, this.args, {
974
985
  cwd: this.cwd,
975
986
  env: this.env,
@@ -977,10 +988,19 @@ class PiRpcProcess {
977
988
  windowsHide: true,
978
989
  });
979
990
 
980
- this.child.on("error", (error) => {
981
- const message = sanitizeError(error);
982
- this.emit({ type: "pi_process_error", error: message });
983
- this.rejectAll(new Error(message));
991
+ const startup = new Promise((resolve, reject) => {
992
+ this.child.once("spawn", () => {
993
+ this.spawned = true;
994
+ this.emit({ type: "pi_process_start", pid: this.child.pid, cwd: this.cwd, command: this.displayCommand, args: this.args });
995
+ resolve();
996
+ });
997
+ this.child.on("error", (error) => {
998
+ this.spawned = false;
999
+ const message = sanitizeError(error);
1000
+ this.emit({ type: "pi_process_error", error: message });
1001
+ this.rejectAll(new Error(message));
1002
+ reject(new Error(message));
1003
+ });
984
1004
  });
985
1005
 
986
1006
  this.child.on("exit", (code, signal) => {
@@ -998,11 +1018,11 @@ class PiRpcProcess {
998
1018
  }
999
1019
  });
1000
1020
 
1001
- this.emit({ type: "pi_process_start", pid: this.child.pid, cwd: this.cwd, command: this.displayCommand, args: this.args });
1021
+ return startup;
1002
1022
  }
1003
1023
 
1004
1024
  isRunning() {
1005
- return !!this.child && this.child.exitCode === null && !this.child.killed;
1025
+ return this.spawned && !!this.child && this.child.exitCode === null && !this.child.killed;
1006
1026
  }
1007
1027
 
1008
1028
  onEvent(listener) {
@@ -9703,6 +9723,18 @@ function normalizedRestoreString(value, maxLength) {
9703
9723
  return text ? text.slice(0, maxLength) : undefined;
9704
9724
  }
9705
9725
 
9726
+ function normalizeTabPromptDescriptor(value) {
9727
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
9728
+ if (Object.keys(value).length !== 2 || !Object.hasOwn(value, "kind") || !Object.hasOwn(value, "path")) return null;
9729
+ if (value.kind !== "append-system" || typeof value.path !== "string") return null;
9730
+ if (!value.path || value.path.length > TAB_PROMPT_PATH_MAX_LENGTH || /[\u0000-\u001f\u007f]/.test(value.path) || !path.isAbsolute(value.path)) return null;
9731
+ return { kind: "append-system", path: value.path };
9732
+ }
9733
+
9734
+ function appendSystemPromptDescriptor(appendSystemPromptPath) {
9735
+ return normalizeTabPromptDescriptor(appendSystemPromptPath ? { kind: "append-system", path: appendSystemPromptPath } : null);
9736
+ }
9737
+
9706
9738
  function normalizeRestoreTabDescriptor(item, seenIds) {
9707
9739
  if (!item || typeof item !== "object") return null;
9708
9740
  const state = item.state && typeof item.state === "object" ? item.state : {};
@@ -9902,7 +9934,39 @@ async function appendCuratedResourceArgs(args, normalResources, resourceType, fl
9902
9934
  appendResourceArgs(args, flag, await startedWebuiResourcePaths(resourceType));
9903
9935
  }
9904
9936
 
9905
- async function buildPiArgsForTab(tabIndex, title, tabCwd = options.cwd) {
9937
+ function globalPiAppendSystemPromptPath() {
9938
+ return path.join(homedir(), ".pi", "agent", "APPEND_SYSTEM.md");
9939
+ }
9940
+
9941
+ function isGlobalPiAppendSystemPromptPath(value) {
9942
+ return value === globalPiAppendSystemPromptPath();
9943
+ }
9944
+
9945
+ async function validatePersistedAppendSystemSelection(settings) {
9946
+ if (!settings.appendSystemPromptPath || !settings.appendSystemPromptRootPath) return null;
9947
+ if (isGlobalPiAppendSystemPromptPath(settings.appendSystemPromptPath)) return null;
9948
+ return validateSavedAppendSystemSelection(
9949
+ settings.appendSystemPromptPath,
9950
+ settings.appendSystemPromptRootPath,
9951
+ );
9952
+ }
9953
+
9954
+ async function selectedAppendSystemPromptPath() {
9955
+ let settings;
9956
+ try {
9957
+ settings = await readWebuiSettings();
9958
+ } catch (error) {
9959
+ console.warn(`failed to read the saved APPEND_SYSTEM.md selection: ${sanitizeError(error)}`);
9960
+ return null;
9961
+ }
9962
+ if (!settings.appendSystemPromptPath || isGlobalPiAppendSystemPromptPath(settings.appendSystemPromptPath)) return null;
9963
+ const validated = await validatePersistedAppendSystemSelection(settings);
9964
+ if (validated) return validated.path;
9965
+ console.warn(`Skipping unavailable saved APPEND_SYSTEM.md selection: ${settings.appendSystemPromptPath.slice(0, 4_096)}`);
9966
+ return null;
9967
+ }
9968
+
9969
+ async function buildPiLaunchForTab(tabIndex, title, tabCwd = options.cwd) {
9906
9970
  const args = ["--mode", "rpc", "--no-extensions", "--no-skills", "--no-prompt-templates", "--no-themes"];
9907
9971
  if (options.noSession) args.push("--no-session");
9908
9972
 
@@ -9922,11 +9986,14 @@ async function buildPiArgsForTab(tabIndex, title, tabCwd = options.cwd) {
9922
9986
  // depending on TUI-only extension UIs.
9923
9987
  args.push("--extension", webuiHelperExtensionPath);
9924
9988
 
9989
+ const appendSystemPromptPath = await selectedAppendSystemPromptPath();
9990
+ if (appendSystemPromptPath) args.push("--append-system-prompt", appendSystemPromptPath);
9991
+
9925
9992
  // Keep tab naming inside Web UI metadata. Some bundled Pi CLI versions do not
9926
9993
  // support --name, and passing Web UI-generated tab titles through to child
9927
9994
  // RPC processes makes every tab after the first exit immediately.
9928
9995
  args.push(...options.piArgs);
9929
- return args;
9996
+ return { args, prompt: appendSystemPromptDescriptor(appendSystemPromptPath) };
9930
9997
  }
9931
9998
 
9932
9999
  function isNodeScriptCommand(command) {
@@ -10140,7 +10207,7 @@ async function initializeRpcSupervisor() {
10140
10207
  });
10141
10208
  }
10142
10209
 
10143
- function supervisedTabMetadata(tab, { cwd = tab.cwd } = {}) {
10210
+ function supervisedTabMetadata(tab, { cwd = tab.cwd, prompt = tab.prompt } = {}) {
10144
10211
  return {
10145
10212
  index: tab.index,
10146
10213
  title: tab.title,
@@ -10150,6 +10217,7 @@ function supervisedTabMetadata(tab, { cwd = tab.cwd } = {}) {
10150
10217
  sessionFile: tabRestorableSessionFile(tab),
10151
10218
  gitWorkspace: tab.gitWorkspace || null,
10152
10219
  createdAt: tab.createdAt,
10220
+ prompt: normalizeTabPromptDescriptor(prompt),
10153
10221
  featureSystemPromptDetected: featureSystemPromptDetected(tab),
10154
10222
  };
10155
10223
  }
@@ -11514,7 +11582,7 @@ function attachRpcToTab(tab, rpc) {
11514
11582
  });
11515
11583
  }
11516
11584
 
11517
- function createTabRecord({ id, index, title, titleSource, conversationStarted, cwd, createdAt = new Date().toISOString(), sessionFile, gitWorkspace, rpc }) {
11585
+ function createTabRecord({ id, index, title, titleSource, conversationStarted, cwd, createdAt = new Date().toISOString(), sessionFile, gitWorkspace, prompt, rpc }) {
11518
11586
  const tab = {
11519
11587
  id,
11520
11588
  index,
@@ -11525,6 +11593,7 @@ function createTabRecord({ id, index, title, titleSource, conversationStarted, c
11525
11593
  createdAt,
11526
11594
  sessionFile: options.noSession ? undefined : normalizedRestoreString(sessionFile, 4096),
11527
11595
  gitWorkspace: gitWorkspace || null,
11596
+ prompt: normalizeTabPromptDescriptor(prompt),
11528
11597
  lastState: null,
11529
11598
  pendingThinkingLevel: undefined,
11530
11599
  thinkingStreamRecovery: new ThinkingStreamRecovery(),
@@ -11569,7 +11638,8 @@ async function createTab({ id: requestedId, index, title, titleSource, conversat
11569
11638
  const resolvedTitleSource = ["explicit", "auto", "default"].includes(titleSource) ? titleSource : titleIsExplicit ? "explicit" : "default";
11570
11639
  const tabCwd = cwd ? await resolveCwd(cwd, options.cwd) : options.cwd;
11571
11640
  const id = requestedId && !tabs.has(requestedId) ? requestedId : randomUUID();
11572
- const piArgs = await buildPiArgsForTab(tabIndex, tabTitle, tabCwd);
11641
+ const launch = await buildPiLaunchForTab(tabIndex, tabTitle, tabCwd);
11642
+ const piArgs = launch.args;
11573
11643
  if (sessionFile && !options.noSession) piArgs.push("--session", sessionFile);
11574
11644
  const piCommand = await resolvePiCommand(piArgs);
11575
11645
  const createdAt = new Date().toISOString();
@@ -11596,13 +11666,14 @@ async function createTab({ id: requestedId, index, title, titleSource, conversat
11596
11666
  if (rpc instanceof SupervisorPiRpcProcess) {
11597
11667
  const snapshot = await rpcSupervisor.createTab({
11598
11668
  tabId: id,
11599
- metadata: supervisedTabMetadata(tab),
11669
+ metadata: supervisedTabMetadata(tab, { prompt: launch.prompt }),
11600
11670
  child: { command: piCommand.command, args: piCommand.args, cwd: tabCwd },
11601
11671
  });
11602
11672
  rpc.applySnapshot(snapshot);
11603
11673
  } else {
11604
- rpc.start();
11674
+ await rpc.start();
11605
11675
  }
11676
+ tab.prompt = launch.prompt;
11606
11677
  await primeTabRpc(tab);
11607
11678
  } catch (error) {
11608
11679
  if (!tab.rpc.isRunning()) {
@@ -11651,6 +11722,7 @@ async function hydrateManagedTabs(snapshot) {
11651
11722
  createdAt: normalizedRestoreString(metadata?.createdAt, 128) || managed.startedAt || new Date().toISOString(),
11652
11723
  sessionFile: descriptor.sessionFile,
11653
11724
  gitWorkspace: metadata?.gitWorkspace || null,
11725
+ prompt: normalizeTabPromptDescriptor(metadata?.prompt),
11654
11726
  rpc,
11655
11727
  });
11656
11728
  restoreFeatureSystemPromptDetection(tab, metadata?.featureSystemPromptDetected === true);
@@ -11687,6 +11759,7 @@ function tabMeta(tab) {
11687
11759
  cwd: tab.cwd,
11688
11760
  sessionFile: tabRestorableSessionFile(tab),
11689
11761
  gitWorkspace: tab.gitWorkspace || null,
11762
+ prompt: normalizeTabPromptDescriptor(tab.prompt),
11690
11763
  pendingThinkingLevel: tab.pendingThinkingLevel || null,
11691
11764
  createdAt: tab.createdAt,
11692
11765
  startedAt: tab.rpc.startedAt,
@@ -12967,7 +13040,8 @@ async function performTabCwdUpdate(tab, cwd) {
12967
13040
  if (tab.rpc?.isRunning()) await safeRpcData(tab, { type: "get_state" }, STATUS_RPC_TIMEOUT_MS);
12968
13041
  const sessionFile = tabRestorableSessionFile(tab);
12969
13042
 
12970
- const piArgs = await buildPiArgsForTab(tab.index, tab.title, nextCwd);
13043
+ const launch = await buildPiLaunchForTab(tab.index, tab.title, nextCwd);
13044
+ const piArgs = launch.args;
12971
13045
  if (sessionFile && !options.noSession) piArgs.push("--session", sessionFile);
12972
13046
  const piCommand = await resolvePiCommand(piArgs);
12973
13047
  const restartingEvent = { type: "webui_tab_restarting", tabId: tab.id, tabTitle: tab.title, cwd: nextCwd, sessionFile };
@@ -12989,7 +13063,7 @@ async function performTabCwdUpdate(tab, cwd) {
12989
13063
  if (oldRpc instanceof SupervisorPiRpcProcess) {
12990
13064
  const snapshot = await oldRpc.replace({
12991
13065
  child: { command: piCommand.command, args: piCommand.args, cwd: nextCwd },
12992
- metadata: supervisedTabMetadata(tab, { cwd: nextCwd }),
13066
+ metadata: supervisedTabMetadata(tab, { cwd: nextCwd, prompt: launch.prompt }),
12993
13067
  displayCommand: piCommand.displayCommand,
12994
13068
  });
12995
13069
  oldRpc.dispose();
@@ -13007,10 +13081,19 @@ async function performTabCwdUpdate(tab, cwd) {
13007
13081
 
13008
13082
  tab.rpcUnsubscribe?.();
13009
13083
  tab.rpcUnsubscribe = undefined;
13084
+ attachRpcToTab(tab, rpc);
13085
+ if (startDirectRpc) {
13086
+ try {
13087
+ await rpc.start();
13088
+ } catch (error) {
13089
+ const detail = sanitizeError(error);
13090
+ broadcastTabEvent(tab, { type: "webui_cwd_change_failed", tabId: tab.id, tabTitle: tab.title, cwd: nextCwd, error: detail });
13091
+ throw makeHttpError(502, `Could not restart ${tab.title} in ${displayPath(nextCwd)}: ${detail}`);
13092
+ }
13093
+ }
13010
13094
  tab.cwd = nextCwd;
13011
13095
  resetTabActivity(tab);
13012
- attachRpcToTab(tab, rpc);
13013
- if (startDirectRpc) rpc.start();
13096
+ tab.prompt = launch.prompt;
13014
13097
  gitLiveWatcher.unsubscribe(tab.id);
13015
13098
  workspaceFilesLiveWatcher.unsubscribe(tab.id);
13016
13099
  workspaceFilesLiveWatcher.subscribe(tab.id, tab.cwd);
@@ -13029,7 +13112,8 @@ async function restartTabRpc(tab, reason = "reload") {
13029
13112
  if (state.data?.isStreaming) throw makeHttpError(409, "Wait for the current response to finish before reloading.");
13030
13113
  if (state.data?.isCompacting) throw makeHttpError(409, "Wait for compaction to finish before reloading.");
13031
13114
 
13032
- const piArgs = await buildPiArgsForTab(tab.index, tab.title, tab.cwd);
13115
+ const launch = await buildPiLaunchForTab(tab.index, tab.title, tab.cwd);
13116
+ const piArgs = launch.args;
13033
13117
  if (state.data?.sessionFile && !options.noSession) piArgs.push("--session", state.data.sessionFile);
13034
13118
  const piCommand = await resolvePiCommand(piArgs);
13035
13119
  const reloadingEvent = { type: "webui_tab_reloading", tabId: tab.id, tabTitle: tab.title, cwd: tab.cwd, reason, sessionFile: state.data?.sessionFile };
@@ -13051,7 +13135,7 @@ async function restartTabRpc(tab, reason = "reload") {
13051
13135
  if (oldRpc instanceof SupervisorPiRpcProcess) {
13052
13136
  const snapshot = await oldRpc.replace({
13053
13137
  child: { command: piCommand.command, args: piCommand.args, cwd: tab.cwd },
13054
- metadata: supervisedTabMetadata(tab),
13138
+ metadata: supervisedTabMetadata(tab, { prompt: launch.prompt }),
13055
13139
  displayCommand: piCommand.displayCommand,
13056
13140
  });
13057
13141
  oldRpc.dispose();
@@ -13061,8 +13145,9 @@ async function restartTabRpc(tab, reason = "reload") {
13061
13145
  oldRpc.stop();
13062
13146
  rpc = new PiRpcProcess({ ...piCommand, cwd: tab.cwd, env: piRpcEnvironment() });
13063
13147
  attachRpcToTab(tab, rpc);
13064
- rpc.start();
13148
+ await rpc.start();
13065
13149
  }
13150
+ tab.prompt = launch.prompt;
13066
13151
 
13067
13152
  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) };
13068
13153
  broadcastTabEvent(tab, reloadedEvent);
@@ -15609,6 +15694,113 @@ function directoryPickerActiveCwd(req, url, body = {}) {
15609
15694
  return firstTab()?.cwd || options.cwd;
15610
15695
  }
15611
15696
 
15697
+ function appendDiscoveryDiagnostic(discovery, kind, diagnosticPath = "") {
15698
+ if (discovery.diagnostics.some((item) => item.kind === kind && item.path === diagnosticPath)) return;
15699
+ if (discovery.diagnostics.length >= APPEND_SYSTEM_DISCOVERY_LIMITS.maxDiagnostics) {
15700
+ discovery.diagnostics.length = APPEND_SYSTEM_DISCOVERY_LIMITS.maxDiagnostics - 1;
15701
+ discovery.limits.truncated.diagnostics = true;
15702
+ }
15703
+ discovery.diagnostics.push({
15704
+ kind,
15705
+ path: diagnosticPath,
15706
+ message: APPEND_SYSTEM_DIAGNOSTIC_MESSAGES[kind],
15707
+ });
15708
+ }
15709
+
15710
+ async function appendSystemFilesData(tab, savedSettings) {
15711
+ const settings = savedSettings || await readWebuiSettings();
15712
+ const savedUsesPiDefault = isGlobalPiAppendSystemPromptPath(settings.appendSystemPromptPath);
15713
+ const discovery = await discoverAppendSystemFiles({
15714
+ piRoot: path.join(homedir(), ".pi"),
15715
+ cwd: tab.cwd,
15716
+ savedPath: savedUsesPiDefault ? null : settings.appendSystemPromptPath,
15717
+ excludedPaths: [globalPiAppendSystemPromptPath()],
15718
+ });
15719
+ if (!settings.appendSystemPromptPath || savedUsesPiDefault) return discovery;
15720
+
15721
+ const validated = await validatePersistedAppendSystemSelection(settings);
15722
+ if (!validated) {
15723
+ appendDiscoveryDiagnostic(discovery, "saved-selection-invalid", settings.appendSystemPromptPath);
15724
+ return discovery;
15725
+ }
15726
+
15727
+ discovery.diagnostics = discovery.diagnostics.filter((item) => item.kind !== "saved-selection-invalid" || item.path !== validated.path);
15728
+ if (!discovery.candidates.some((candidate) => candidate.path === validated.path)) {
15729
+ if (discovery.candidates.length >= APPEND_SYSTEM_DISCOVERY_LIMITS.maxCandidates) {
15730
+ discovery.candidates.pop();
15731
+ discovery.limits.truncated.candidates = true;
15732
+ appendDiscoveryDiagnostic(discovery, "candidate-limit");
15733
+ }
15734
+ discovery.candidates.push({ path: validated.path, rootLabel: "Saved selection" });
15735
+ discovery.candidates.sort((left, right) => left.path.localeCompare(right.path, "en"));
15736
+ }
15737
+ return discovery;
15738
+ }
15739
+
15740
+ function requireAppendSystemRequest(req, { json = false } = {}) {
15741
+ if (!isLoopbackHostAuthority(req.headers.host)) {
15742
+ throw makeHttpError(403, "APPEND_SYSTEM.md requests require a loopback Host authority.");
15743
+ }
15744
+ const fetchSite = String(req.headers["sec-fetch-site"] || "").trim().toLowerCase();
15745
+ if (fetchSite && fetchSite !== "same-origin" && fetchSite !== "none") {
15746
+ throw makeHttpError(403, "Cross-origin APPEND_SYSTEM.md requests are blocked.");
15747
+ }
15748
+ if (!json) return;
15749
+ const contentType = String(req.headers["content-type"] || "").split(";", 1)[0].trim().toLowerCase();
15750
+ if (contentType !== "application/json") {
15751
+ throw makeHttpError(415, "APPEND_SYSTEM.md selection saves require Content-Type: application/json.");
15752
+ }
15753
+ }
15754
+
15755
+ function validateAppendSystemSelectionBody(body) {
15756
+ if (!body || typeof body !== "object" || Array.isArray(body)) {
15757
+ throw makeHttpError(400, "APPEND_SYSTEM.md selection body must be an object with only tabId and path.");
15758
+ }
15759
+ const allowedFields = new Set(["tabId", "path"]);
15760
+ const unknownFields = Object.keys(body).filter((key) => !allowedFields.has(key));
15761
+ if (unknownFields.length) {
15762
+ throw makeHttpError(400, `APPEND_SYSTEM.md selection body contains unsupported field${unknownFields.length === 1 ? "" : "s"}: ${unknownFields.join(", ")}.`);
15763
+ }
15764
+ if (!Object.hasOwn(body, "tabId") || !Object.hasOwn(body, "path")) {
15765
+ throw makeHttpError(400, "APPEND_SYSTEM.md selection body requires tabId and path.");
15766
+ }
15767
+ if (typeof body.tabId !== "string" || !body.tabId.trim()) {
15768
+ throw makeHttpError(400, "tabId must be a non-empty string");
15769
+ }
15770
+ if (body.path !== null && typeof body.path !== "string") {
15771
+ throw makeHttpError(400, "path must be an APPEND_SYSTEM.md candidate path or null");
15772
+ }
15773
+ return body;
15774
+ }
15775
+
15776
+ async function saveAppendSystemSelection(tab, body) {
15777
+ const requestedPath = isGlobalPiAppendSystemPromptPath(body.path) ? null : body.path;
15778
+ const freshSelection = requestedPath === null
15779
+ ? null
15780
+ : await validateAppendSystemSelection(requestedPath, {
15781
+ piRoot: path.join(homedir(), ".pi"),
15782
+ cwd: tab.cwd,
15783
+ });
15784
+ let changed = false;
15785
+ const settings = await updateWebuiSettings(async (current) => {
15786
+ let selected = freshSelection;
15787
+ if (requestedPath !== null && !selected && current.appendSystemPromptPath === requestedPath) {
15788
+ selected = await validatePersistedAppendSystemSelection(current);
15789
+ }
15790
+ if (requestedPath !== null && !selected) {
15791
+ throw makeHttpError(400, "path must name an APPEND_SYSTEM.md candidate from a fresh discovery scan");
15792
+ }
15793
+
15794
+ const appendSystemPromptPath = selected?.path || null;
15795
+ const appendSystemPromptRootPath = selected?.rootPath || null;
15796
+ changed = current.appendSystemPromptPath !== appendSystemPromptPath
15797
+ || current.appendSystemPromptRootPath !== appendSystemPromptRootPath;
15798
+ return changed ? { appendSystemPromptPath, appendSystemPromptRootPath } : undefined;
15799
+ });
15800
+ const discovery = await appendSystemFilesData(tab, settings);
15801
+ return { ...discovery, changed, restartRequired: changed };
15802
+ }
15803
+
15612
15804
  async function createInitialTabs() {
15613
15805
  const managedTabs = await hydrateManagedTabs(rpcSupervisorSnapshot);
15614
15806
  if (rpcSupervisorSnapshot?.tabs?.length) return managedTabs;
@@ -16412,6 +16604,30 @@ const server = createServer(async (req, res) => {
16412
16604
  return;
16413
16605
  }
16414
16606
 
16607
+ if (url.pathname === "/api/append-system-files" && req.method === "GET") {
16608
+ requireLocalhost(req, "APPEND_SYSTEM.md discovery is only allowed from localhost");
16609
+ requireAppendSystemRequest(req);
16610
+ const tab = getRequestedTab(req, url);
16611
+ sendJson(res, 200, { ok: true, data: await appendSystemFilesData(tab) }, { "cache-control": "private, no-store" });
16612
+ return;
16613
+ }
16614
+
16615
+ if (url.pathname === "/api/append-system-selection" && req.method === "POST") {
16616
+ requireLocalhost(req, "Saving an APPEND_SYSTEM.md selection is only allowed from localhost");
16617
+ requireAppendSystemRequest(req, { json: true });
16618
+ let body;
16619
+ try {
16620
+ body = await readJsonBody(req);
16621
+ } catch (error) {
16622
+ if (error instanceof SyntaxError) throw makeHttpError(400, "APPEND_SYSTEM.md selection body must be valid JSON.");
16623
+ throw error;
16624
+ }
16625
+ validateAppendSystemSelectionBody(body);
16626
+ const tab = getRequestedTab(req, url, body);
16627
+ sendJson(res, 200, { ok: true, data: await saveAppendSystemSelection(tab, body) }, { "cache-control": "private, no-store" });
16628
+ return;
16629
+ }
16630
+
16415
16631
  const samplingParametersRoute = /^\/api\/tabs\/([^/]+)\/sampling-parameters$/.exec(url.pathname);
16416
16632
  if (samplingParametersRoute && (req.method === "GET" || req.method === "PUT")) {
16417
16633
  const tabId = decodeURIComponent(samplingParametersRoute[1]);