@firstpick/pi-package-webui 0.10.1 → 0.10.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/DEVELOPMENT.md +41 -19
  2. package/README.md +13 -3
  3. package/TECHNICAL.md +16 -2
  4. package/bin/pi-webui.mjs +257 -76
  5. package/index.ts +1 -256
  6. package/lib/append-system-selection.mjs +311 -0
  7. package/lib/git-workflow-preferences.mjs +6 -0
  8. package/lib/trust-boundaries.mjs +37 -0
  9. package/package.json +1 -1
  10. package/public/app.js +162 -7
  11. package/public/index.html +5 -2
  12. package/public/service-worker.js +1 -1
  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/codex-fast-mode-static.test.mjs +2 -2
  18. package/tests/common-options-submenus-interaction-static.test.mjs +4 -0
  19. package/tests/common-options-submenus-markup-static.test.mjs +2 -1
  20. package/tests/composer-action-grid-reorder-static.test.mjs +2 -2
  21. package/tests/control-visibility-static.test.mjs +2 -2
  22. package/tests/controls-layout-static.test.mjs +2 -2
  23. package/tests/events-tree-context-menu-static.test.mjs +2 -2
  24. package/tests/fast-mode-client-static.test.mjs +1 -1
  25. package/tests/feature-decision-output-popup-static.test.mjs +1 -1
  26. package/tests/file-viewer-image-static.test.mjs +2 -2
  27. package/tests/guided-git-activation-static.test.mjs +10 -3
  28. package/tests/guided-git-fallback-runtime.test.mjs +46 -21
  29. package/tests/guided-git-fallback-ui-static.test.mjs +3 -3
  30. package/tests/intercom-conversation-viewer-static.test.mjs +2 -2
  31. package/tests/main-output-loading-static.test.mjs +2 -2
  32. package/tests/middle-button-drag-scroll-static.test.mjs +2 -2
  33. package/tests/mobile-continuity-tablet-static.test.mjs +2 -2
  34. package/tests/mobile-foundation-static.test.mjs +2 -2
  35. package/tests/mobile-phone-experience-static.test.mjs +1 -1
  36. package/tests/mobile-static.test.mjs +3 -2
  37. package/tests/native-parity-harness.test.mjs +7 -0
  38. package/tests/open-issue-wizard-static.test.mjs +1 -1
  39. package/tests/optional-feature-prompt-impact-static.test.mjs +2 -2
  40. package/tests/persistent-ui-layout-static.test.mjs +2 -2
  41. package/tests/prompt-input-vertical-scroll-static.test.mjs +2 -2
  42. package/tests/questionnaire-dialog.test.mjs +2 -2
  43. package/tests/resource-tui-extension.test.mjs +4 -18
  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/subagent-observability-static.test.mjs +2 -2
  47. package/tests/syntax-highlighting-static.test.mjs +2 -2
  48. package/tests/terminal-tab-prompt-tooltip-static.test.mjs +147 -0
  49. package/tests/terminal-tab-workspace-static.test.mjs +1 -1
  50. package/tests/theme-customizer-static.test.mjs +1 -1
  51. package/tests/windows-drive-cwd-picker-static.test.mjs +2 -2
  52. package/lib/tui-model-profile-selector.mjs +0 -183
  53. package/lib/tui-resource-selector.mjs +0 -173
  54. package/tests/tui-model-profile-selector.test.mjs +0 -102
  55. package/tests/tui-resource-selector.test.mjs +0 -74
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) {
@@ -3124,14 +3144,25 @@ async function triggerSessionSummary(tab, { refresh = false } = {}) {
3124
3144
  }
3125
3145
  }
3126
3146
 
3127
- function gitWorkflowGenerationPrompt(kind, preferences, commandName) {
3147
+ function gitWorkflowGenerationProfileArgument(profile) {
3148
+ const payload = Buffer.from(JSON.stringify({
3149
+ version: 1,
3150
+ provider: profile.provider,
3151
+ modelId: profile.modelId,
3152
+ thinkingLevel: profile.thinkingLevel,
3153
+ }), "utf8").toString("base64url");
3154
+ return `--firstpick-webui-generation-profile=${payload}`;
3155
+ }
3156
+
3157
+ function gitWorkflowGenerationPrompt(kind, preferences, commandName, profile) {
3158
+ const generationProfile = gitWorkflowGenerationProfileArgument(profile);
3128
3159
  switch (kind) {
3129
3160
  case "commit":
3130
- return `/${commandName} ${preferences.commit.language} ${preferences.commit.scope}`;
3161
+ return `/${commandName} ${preferences.commit.language} ${preferences.commit.scope} ${generationProfile}`;
3131
3162
  case "branch":
3132
- return `/${commandName}`;
3163
+ return `/${commandName} ${generationProfile}`;
3133
3164
  case "pr":
3134
- return `/${commandName} ${preferences.commit.language}`;
3165
+ return `/${commandName} ${preferences.commit.language} ${generationProfile}`;
3135
3166
  default:
3136
3167
  throw makeHttpError(400, "generation kind must be commit, branch, or pr");
3137
3168
  }
@@ -3212,37 +3243,6 @@ function publicGitWorkflowGenerationProfile(profile) {
3212
3243
  };
3213
3244
  }
3214
3245
 
3215
- async function restoreGitWorkflowGenerationProfile(tab, expectedRecord = tab?.gitWorkflowGeneration) {
3216
- const record = expectedRecord && tab?.gitWorkflowGeneration === expectedRecord ? expectedRecord : null;
3217
- const restore = record?.restore || tab?.gitWorkflowGenerationRestore;
3218
- if (!restore) return;
3219
- if (record?.restorePromise) return record.restorePromise;
3220
- const operation = (async () => {
3221
- try {
3222
- if (!tab.rpc?.isRunning?.()) return;
3223
- if (restore.model?.provider && restore.model?.id) {
3224
- const modelResponse = await tab.rpc.send({ type: "set_model", provider: restore.model.provider, modelId: restore.model.id });
3225
- if (modelResponse.success === false) throw new Error(modelResponse.error || "Failed to restore model");
3226
- }
3227
- if (restore.thinkingLevel) {
3228
- const thinkingResponse = await setThinkingLevelForTab(tab, restore.thinkingLevel, { allowPending: false });
3229
- if (thinkingResponse.success === false) throw new Error(thinkingResponse.error || "Failed to restore thinking level");
3230
- }
3231
- recordEvent({ type: "git_workflow_generation_profile_restored", tabId: tab.id, tabTitle: tab.title });
3232
- } catch (error) {
3233
- console.error(`[guided-git] failed to restore generation profile for ${record?.generationId || tab.id}: ${sanitizeError(error)}`);
3234
- recordEvent({ type: "git_workflow_generation_profile_restore_failed", tabId: tab.id, tabTitle: tab.title, error: boundedGitWorkflowGenerationError("Guided Git could not restore the previous model profile.") });
3235
- } finally {
3236
- if (!record || tab.gitWorkflowGeneration === record) {
3237
- tab.gitWorkflowGeneration = null;
3238
- tab.gitWorkflowGenerationRestore = null;
3239
- }
3240
- }
3241
- })();
3242
- if (record) record.restorePromise = operation;
3243
- return operation;
3244
- }
3245
-
3246
3246
  async function createGitWorkflowArtifactGeneration(tab, generationId, kind) {
3247
3247
  const createdAt = Date.now();
3248
3248
  if (kind === "commit") {
@@ -3325,7 +3325,7 @@ async function finishGitWorkflowGeneration(tab, record, { successful }) {
3325
3325
  tab.gitWorkflowMessageGeneration = record.previousMessageGeneration;
3326
3326
  }
3327
3327
  markTabIdle(tab);
3328
- await restoreGitWorkflowGenerationProfile(tab, record);
3328
+ if (tab.gitWorkflowGeneration === record) tab.gitWorkflowGeneration = null;
3329
3329
  }
3330
3330
 
3331
3331
  async function dispatchGitWorkflowGenerationAttempt(tab, record, profile, attempt) {
@@ -3341,15 +3341,7 @@ async function dispatchGitWorkflowGenerationAttempt(tab, record, profile, attemp
3341
3341
  record.promptAccepted = false;
3342
3342
  record.pendingSettlement = null;
3343
3343
  record.nativeCommandError = null;
3344
- if (record.currentModelKey !== `${profile.provider}/${profile.modelId}`) {
3345
- const modelResponse = await tab.rpc.send({ type: "set_model", provider: profile.provider, modelId: profile.modelId });
3346
- assertGitWorkflowGenerationOwnership(tab, record);
3347
- if (modelResponse.success === false) throw new Error(modelResponse.error || `Failed to select ${profile.provider}/${profile.modelId}`);
3348
- record.currentModelKey = `${profile.provider}/${profile.modelId}`;
3349
- }
3350
- const thinkingResponse = await setThinkingLevelForTab(tab, profile.thinkingLevel, { allowPending: false });
3351
- assertGitWorkflowGenerationOwnership(tab, record);
3352
- if (thinkingResponse.success === false) throw new Error(thinkingResponse.error || `Failed to select thinking level ${profile.thinkingLevel}`);
3344
+ record.message = gitWorkflowGenerationPrompt(record.kind, record.preferences, record.nativeCommandName, profile);
3353
3345
 
3354
3346
  assertGitWorkflowGenerationOwnership(tab, record);
3355
3347
  markTabWorking(tab);
@@ -3452,7 +3444,7 @@ function consumeGitWorkflowGenerationEvent(tab, event, { finalError = false } =
3452
3444
  }
3453
3445
 
3454
3446
  async function startGitWorkflowGeneration(tab, body = {}) {
3455
- if (tab.gitWorkflowGeneration || tab.gitWorkflowGenerationRestore) throw makeHttpError(409, "A guided Git generation request is already active in this tab");
3447
+ if (tab.gitWorkflowGeneration) throw makeHttpError(409, "A guided Git generation request is already active in this tab");
3456
3448
  const kind = String(body.kind || "").trim();
3457
3449
  if (!new Set(["commit", "branch", "pr"]).has(kind)) throw makeHttpError(400, "generation kind must be commit, branch, or pr");
3458
3450
 
@@ -3462,7 +3454,7 @@ async function startGitWorkflowGeneration(tab, body = {}) {
3462
3454
  generationId: randomUUID(),
3463
3455
  kind,
3464
3456
  message: "",
3465
- restore: null,
3457
+ preferences: null,
3466
3458
  previousMessageGeneration: tab.gitWorkflowMessageGeneration || null,
3467
3459
  messageGeneration: null,
3468
3460
  artifactGeneration: null,
@@ -3475,7 +3467,6 @@ async function startGitWorkflowGeneration(tab, body = {}) {
3475
3467
  attemptRunStarted: false,
3476
3468
  promptAccepted: false,
3477
3469
  pendingSettlement: null,
3478
- currentModelKey: "",
3479
3470
  nativeCommandName: "",
3480
3471
  nativeCommandError: null,
3481
3472
  nativeGeneration: true,
@@ -3491,10 +3482,10 @@ async function startGitWorkflowGeneration(tab, body = {}) {
3491
3482
  const preferences = await readGitWorkflowPreferences();
3492
3483
  assertGitWorkflowGenerationOwnership(tab, record);
3493
3484
  if (!isGitWorkflowSetupComplete(preferences)) throw makeHttpError(409, "Run /git-workflow-setup or open Guided Git Setup before generating Git text");
3485
+ record.preferences = preferences;
3494
3486
  const nativeCommandName = await resolveGuidedGitNativeCommand(tab, kind);
3495
3487
  assertGitWorkflowGenerationOwnership(tab, record);
3496
3488
  record.nativeCommandName = nativeCommandName;
3497
- record.message = gitWorkflowGenerationPrompt(kind, preferences, nativeCommandName);
3498
3489
 
3499
3490
  const state = await currentSessionState(tab);
3500
3491
  assertGitWorkflowGenerationOwnership(tab, record);
@@ -3520,9 +3511,6 @@ async function startGitWorkflowGeneration(tab, body = {}) {
3520
3511
  )
3521
3512
  : null;
3522
3513
 
3523
- record.restore = { model: state.model || null, thinkingLevel: state.thinkingLevel || "off" };
3524
- record.currentModelKey = gitWorkflowModelKey(state.model);
3525
- tab.gitWorkflowGenerationRestore = record.restore;
3526
3514
  record.artifactGeneration = await createGitWorkflowArtifactGeneration(tab, record.generationId, kind);
3527
3515
  record.messageGeneration = kind === "commit" ? record.artifactGeneration : null;
3528
3516
  assertGitWorkflowGenerationOwnership(tab, record);
@@ -3546,8 +3534,7 @@ async function startGitWorkflowGeneration(tab, body = {}) {
3546
3534
  }
3547
3535
  } catch (error) {
3548
3536
  if (tab.gitWorkflowGeneration === record && !record.finishing) {
3549
- if (record.restore) await finishGitWorkflowGeneration(tab, record, { successful: false });
3550
- else tab.gitWorkflowGeneration = null;
3537
+ await finishGitWorkflowGeneration(tab, record, { successful: false });
3551
3538
  }
3552
3539
  throw error;
3553
3540
  }
@@ -9736,6 +9723,18 @@ function normalizedRestoreString(value, maxLength) {
9736
9723
  return text ? text.slice(0, maxLength) : undefined;
9737
9724
  }
9738
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
+
9739
9738
  function normalizeRestoreTabDescriptor(item, seenIds) {
9740
9739
  if (!item || typeof item !== "object") return null;
9741
9740
  const state = item.state && typeof item.state === "object" ? item.state : {};
@@ -9935,7 +9934,39 @@ async function appendCuratedResourceArgs(args, normalResources, resourceType, fl
9935
9934
  appendResourceArgs(args, flag, await startedWebuiResourcePaths(resourceType));
9936
9935
  }
9937
9936
 
9938
- 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) {
9939
9970
  const args = ["--mode", "rpc", "--no-extensions", "--no-skills", "--no-prompt-templates", "--no-themes"];
9940
9971
  if (options.noSession) args.push("--no-session");
9941
9972
 
@@ -9955,11 +9986,14 @@ async function buildPiArgsForTab(tabIndex, title, tabCwd = options.cwd) {
9955
9986
  // depending on TUI-only extension UIs.
9956
9987
  args.push("--extension", webuiHelperExtensionPath);
9957
9988
 
9989
+ const appendSystemPromptPath = await selectedAppendSystemPromptPath();
9990
+ if (appendSystemPromptPath) args.push("--append-system-prompt", appendSystemPromptPath);
9991
+
9958
9992
  // Keep tab naming inside Web UI metadata. Some bundled Pi CLI versions do not
9959
9993
  // support --name, and passing Web UI-generated tab titles through to child
9960
9994
  // RPC processes makes every tab after the first exit immediately.
9961
9995
  args.push(...options.piArgs);
9962
- return args;
9996
+ return { args, prompt: appendSystemPromptDescriptor(appendSystemPromptPath) };
9963
9997
  }
9964
9998
 
9965
9999
  function isNodeScriptCommand(command) {
@@ -10173,7 +10207,7 @@ async function initializeRpcSupervisor() {
10173
10207
  });
10174
10208
  }
10175
10209
 
10176
- function supervisedTabMetadata(tab, { cwd = tab.cwd } = {}) {
10210
+ function supervisedTabMetadata(tab, { cwd = tab.cwd, prompt = tab.prompt } = {}) {
10177
10211
  return {
10178
10212
  index: tab.index,
10179
10213
  title: tab.title,
@@ -10183,6 +10217,7 @@ function supervisedTabMetadata(tab, { cwd = tab.cwd } = {}) {
10183
10217
  sessionFile: tabRestorableSessionFile(tab),
10184
10218
  gitWorkspace: tab.gitWorkspace || null,
10185
10219
  createdAt: tab.createdAt,
10220
+ prompt: normalizeTabPromptDescriptor(prompt),
10186
10221
  featureSystemPromptDetected: featureSystemPromptDetected(tab),
10187
10222
  };
10188
10223
  }
@@ -11524,7 +11559,6 @@ function attachRpcToTab(tab, rpc) {
11524
11559
  tab.gitWorkflowArtifactGeneration.successful = false;
11525
11560
  }
11526
11561
  tab.gitWorkflowGeneration = null;
11527
- tab.gitWorkflowGenerationRestore = null;
11528
11562
  tab.gitWorkflowMessageGeneration = null;
11529
11563
  clearPendingExtensionUiRequests(tab);
11530
11564
  clearExtensionStatuses(tab);
@@ -11548,7 +11582,7 @@ function attachRpcToTab(tab, rpc) {
11548
11582
  });
11549
11583
  }
11550
11584
 
11551
- 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 }) {
11552
11586
  const tab = {
11553
11587
  id,
11554
11588
  index,
@@ -11559,11 +11593,11 @@ function createTabRecord({ id, index, title, titleSource, conversationStarted, c
11559
11593
  createdAt,
11560
11594
  sessionFile: options.noSession ? undefined : normalizedRestoreString(sessionFile, 4096),
11561
11595
  gitWorkspace: gitWorkspace || null,
11596
+ prompt: normalizeTabPromptDescriptor(prompt),
11562
11597
  lastState: null,
11563
11598
  pendingThinkingLevel: undefined,
11564
11599
  thinkingStreamRecovery: new ThinkingStreamRecovery(),
11565
11600
  gitWorkflowGeneration: null,
11566
- gitWorkflowGenerationRestore: null,
11567
11601
  gitWorkflowMessageGeneration: null,
11568
11602
  gitWorkflowArtifactGeneration: null,
11569
11603
  gitWorkflowFallbackLifecycle: null,
@@ -11604,7 +11638,8 @@ async function createTab({ id: requestedId, index, title, titleSource, conversat
11604
11638
  const resolvedTitleSource = ["explicit", "auto", "default"].includes(titleSource) ? titleSource : titleIsExplicit ? "explicit" : "default";
11605
11639
  const tabCwd = cwd ? await resolveCwd(cwd, options.cwd) : options.cwd;
11606
11640
  const id = requestedId && !tabs.has(requestedId) ? requestedId : randomUUID();
11607
- const piArgs = await buildPiArgsForTab(tabIndex, tabTitle, tabCwd);
11641
+ const launch = await buildPiLaunchForTab(tabIndex, tabTitle, tabCwd);
11642
+ const piArgs = launch.args;
11608
11643
  if (sessionFile && !options.noSession) piArgs.push("--session", sessionFile);
11609
11644
  const piCommand = await resolvePiCommand(piArgs);
11610
11645
  const createdAt = new Date().toISOString();
@@ -11631,13 +11666,14 @@ async function createTab({ id: requestedId, index, title, titleSource, conversat
11631
11666
  if (rpc instanceof SupervisorPiRpcProcess) {
11632
11667
  const snapshot = await rpcSupervisor.createTab({
11633
11668
  tabId: id,
11634
- metadata: supervisedTabMetadata(tab),
11669
+ metadata: supervisedTabMetadata(tab, { prompt: launch.prompt }),
11635
11670
  child: { command: piCommand.command, args: piCommand.args, cwd: tabCwd },
11636
11671
  });
11637
11672
  rpc.applySnapshot(snapshot);
11638
11673
  } else {
11639
- rpc.start();
11674
+ await rpc.start();
11640
11675
  }
11676
+ tab.prompt = launch.prompt;
11641
11677
  await primeTabRpc(tab);
11642
11678
  } catch (error) {
11643
11679
  if (!tab.rpc.isRunning()) {
@@ -11686,6 +11722,7 @@ async function hydrateManagedTabs(snapshot) {
11686
11722
  createdAt: normalizedRestoreString(metadata?.createdAt, 128) || managed.startedAt || new Date().toISOString(),
11687
11723
  sessionFile: descriptor.sessionFile,
11688
11724
  gitWorkspace: metadata?.gitWorkspace || null,
11725
+ prompt: normalizeTabPromptDescriptor(metadata?.prompt),
11689
11726
  rpc,
11690
11727
  });
11691
11728
  restoreFeatureSystemPromptDetection(tab, metadata?.featureSystemPromptDetected === true);
@@ -11722,6 +11759,7 @@ function tabMeta(tab) {
11722
11759
  cwd: tab.cwd,
11723
11760
  sessionFile: tabRestorableSessionFile(tab),
11724
11761
  gitWorkspace: tab.gitWorkspace || null,
11762
+ prompt: normalizeTabPromptDescriptor(tab.prompt),
11725
11763
  pendingThinkingLevel: tab.pendingThinkingLevel || null,
11726
11764
  createdAt: tab.createdAt,
11727
11765
  startedAt: tab.rpc.startedAt,
@@ -13002,7 +13040,8 @@ async function performTabCwdUpdate(tab, cwd) {
13002
13040
  if (tab.rpc?.isRunning()) await safeRpcData(tab, { type: "get_state" }, STATUS_RPC_TIMEOUT_MS);
13003
13041
  const sessionFile = tabRestorableSessionFile(tab);
13004
13042
 
13005
- const piArgs = await buildPiArgsForTab(tab.index, tab.title, nextCwd);
13043
+ const launch = await buildPiLaunchForTab(tab.index, tab.title, nextCwd);
13044
+ const piArgs = launch.args;
13006
13045
  if (sessionFile && !options.noSession) piArgs.push("--session", sessionFile);
13007
13046
  const piCommand = await resolvePiCommand(piArgs);
13008
13047
  const restartingEvent = { type: "webui_tab_restarting", tabId: tab.id, tabTitle: tab.title, cwd: nextCwd, sessionFile };
@@ -13024,7 +13063,7 @@ async function performTabCwdUpdate(tab, cwd) {
13024
13063
  if (oldRpc instanceof SupervisorPiRpcProcess) {
13025
13064
  const snapshot = await oldRpc.replace({
13026
13065
  child: { command: piCommand.command, args: piCommand.args, cwd: nextCwd },
13027
- metadata: supervisedTabMetadata(tab, { cwd: nextCwd }),
13066
+ metadata: supervisedTabMetadata(tab, { cwd: nextCwd, prompt: launch.prompt }),
13028
13067
  displayCommand: piCommand.displayCommand,
13029
13068
  });
13030
13069
  oldRpc.dispose();
@@ -13042,10 +13081,19 @@ async function performTabCwdUpdate(tab, cwd) {
13042
13081
 
13043
13082
  tab.rpcUnsubscribe?.();
13044
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
+ }
13045
13094
  tab.cwd = nextCwd;
13046
13095
  resetTabActivity(tab);
13047
- attachRpcToTab(tab, rpc);
13048
- if (startDirectRpc) rpc.start();
13096
+ tab.prompt = launch.prompt;
13049
13097
  gitLiveWatcher.unsubscribe(tab.id);
13050
13098
  workspaceFilesLiveWatcher.unsubscribe(tab.id);
13051
13099
  workspaceFilesLiveWatcher.subscribe(tab.id, tab.cwd);
@@ -13064,7 +13112,8 @@ async function restartTabRpc(tab, reason = "reload") {
13064
13112
  if (state.data?.isStreaming) throw makeHttpError(409, "Wait for the current response to finish before reloading.");
13065
13113
  if (state.data?.isCompacting) throw makeHttpError(409, "Wait for compaction to finish before reloading.");
13066
13114
 
13067
- 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;
13068
13117
  if (state.data?.sessionFile && !options.noSession) piArgs.push("--session", state.data.sessionFile);
13069
13118
  const piCommand = await resolvePiCommand(piArgs);
13070
13119
  const reloadingEvent = { type: "webui_tab_reloading", tabId: tab.id, tabTitle: tab.title, cwd: tab.cwd, reason, sessionFile: state.data?.sessionFile };
@@ -13086,7 +13135,7 @@ async function restartTabRpc(tab, reason = "reload") {
13086
13135
  if (oldRpc instanceof SupervisorPiRpcProcess) {
13087
13136
  const snapshot = await oldRpc.replace({
13088
13137
  child: { command: piCommand.command, args: piCommand.args, cwd: tab.cwd },
13089
- metadata: supervisedTabMetadata(tab),
13138
+ metadata: supervisedTabMetadata(tab, { prompt: launch.prompt }),
13090
13139
  displayCommand: piCommand.displayCommand,
13091
13140
  });
13092
13141
  oldRpc.dispose();
@@ -13096,8 +13145,9 @@ async function restartTabRpc(tab, reason = "reload") {
13096
13145
  oldRpc.stop();
13097
13146
  rpc = new PiRpcProcess({ ...piCommand, cwd: tab.cwd, env: piRpcEnvironment() });
13098
13147
  attachRpcToTab(tab, rpc);
13099
- rpc.start();
13148
+ await rpc.start();
13100
13149
  }
13150
+ tab.prompt = launch.prompt;
13101
13151
 
13102
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) };
13103
13153
  broadcastTabEvent(tab, reloadedEvent);
@@ -15644,6 +15694,113 @@ function directoryPickerActiveCwd(req, url, body = {}) {
15644
15694
  return firstTab()?.cwd || options.cwd;
15645
15695
  }
15646
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
+
15647
15804
  async function createInitialTabs() {
15648
15805
  const managedTabs = await hydrateManagedTabs(rpcSupervisorSnapshot);
15649
15806
  if (rpcSupervisorSnapshot?.tabs?.length) return managedTabs;
@@ -16447,6 +16604,30 @@ const server = createServer(async (req, res) => {
16447
16604
  return;
16448
16605
  }
16449
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
+
16450
16631
  const samplingParametersRoute = /^\/api\/tabs\/([^/]+)\/sampling-parameters$/.exec(url.pathname);
16451
16632
  if (samplingParametersRoute && (req.method === "GET" || req.method === "PUT")) {
16452
16633
  const tabId = decodeURIComponent(samplingParametersRoute[1]);