@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/public/app.js CHANGED
@@ -200,6 +200,7 @@ const elements = {
200
200
  optionsNameButton: $("#optionsNameButton"),
201
201
  optionsCloneButton: $("#optionsCloneButton"),
202
202
  optionsSettingsButton: $("#optionsSettingsButton"),
203
+ optionsAppendSystemButton: $("#optionsAppendSystemButton"),
203
204
  optionsSummarySetupButton: $("#optionsSummarySetupButton"),
204
205
  optionsWorkflowSetupButton: $("#optionsWorkflowSetupButton"),
205
206
  optionsSafetyGuardSetupButton: $("#optionsSafetyGuardSetupButton"),
@@ -1089,6 +1090,7 @@ let gitPanelRenderSignature = null;
1089
1090
  let gitChangesRequestSerial = 0;
1090
1091
  const gitChangesUntrackedContentRequests = new Set();
1091
1092
  let nativeCommandTabId = null;
1093
+ let nativeCommandDialogGeneration = 0;
1092
1094
  let nativeSettingsDirty = false;
1093
1095
  let guidedGitSetupDialogOwner = null;
1094
1096
  let sessionSummaryOverlayTabId = null;
@@ -17206,6 +17208,19 @@ function terminalTabActiveTooltip(tab) {
17206
17208
  return active.join(" · ");
17207
17209
  }
17208
17210
 
17211
+ function terminalTabPromptTooltip(tab) {
17212
+ const prompt = tab?.prompt;
17213
+ if (!prompt || typeof prompt !== "object" || Array.isArray(prompt) || Object.keys(prompt).length !== 2 || !Object.hasOwn(prompt, "kind") || !Object.hasOwn(prompt, "path") || prompt.kind !== "append-system") return "";
17214
+ const path = prompt.path;
17215
+ const absolute = typeof path === "string" && (path.startsWith("/") || /^[A-Za-z]:[\\/]/.test(path) || path.startsWith("\\\\"));
17216
+ if (!absolute || path.length > 4096 || /[\u0000-\u001f\u007f]/.test(path)) return "";
17217
+ return `Append-system prompt: ${path}`;
17218
+ }
17219
+
17220
+ function terminalTabGroupRepresentedTab(groupTabs = []) {
17221
+ return groupTabs.find((tab) => typeof activeTabId !== "undefined" && tab?.id === activeTabId) || groupTabs[0] || null;
17222
+ }
17223
+
17209
17224
  function terminalTabTooltip(tab) {
17210
17225
  const lines = [
17211
17226
  `${tab?.title || "Terminal tab"} · ${tabIndicator(tab).label}`,
@@ -17215,6 +17230,8 @@ function terminalTabTooltip(tab) {
17215
17230
  if (git) lines.push(`Git: ${git}`);
17216
17231
  const active = terminalTabActiveTooltip(tab);
17217
17232
  if (active) lines.push(`Active: ${active}`);
17233
+ const prompt = terminalTabPromptTooltip(tab);
17234
+ if (prompt) lines.push(prompt);
17218
17235
  lines.push("Click to switch · Drag to group");
17219
17236
  return lines.join("\n");
17220
17237
  }
@@ -17261,6 +17278,8 @@ function terminalTabGroupTooltip(group, groupTitle = terminalDisplayGroupTitle(g
17261
17278
  ];
17262
17279
  const active = terminalTabGroupActiveTooltip(groupTabs);
17263
17280
  if (active) lines.push(`Active: ${active}`);
17281
+ const prompt = terminalTabPromptTooltip(terminalTabGroupRepresentedTab(groupTabs));
17282
+ if (prompt) lines.push(prompt);
17264
17283
  lines.push(isMobileView() ? "Tap to open group terminals" : "Click to switch · Drop tabs here to add");
17265
17284
  return lines.join("\n");
17266
17285
  }
@@ -17319,7 +17338,7 @@ function renderTerminalTab(tab, { showCwdAdd = false } = {}) {
17319
17338
  button.setAttribute("role", "tab");
17320
17339
  button.setAttribute("aria-selected", isActive ? "true" : "false");
17321
17340
  button.setAttribute("aria-label", `${tab.title}: ${indicator.label}${appRunnerLabel ? `, ${appRunnerLabel}` : ""}${conversationLabel}${workflowModeActive ? ", workflow mode active" : ""}${workflowCount ? `, ${workflowCount} workflow runs active` : ""}`);
17322
- applyStyledTooltip(button, terminalTabTooltip(tab), { ariaLabel: false, align: "start", description: true, variant: "workspace", targetKey: `terminal-tab:${tab.id}:switch` });
17341
+ applyStyledTooltip(button, terminalTabTooltip(tab), { ariaLabel: false, align: "start", description: true, preserveInternalSpaces: true, variant: "workspace", targetKey: `terminal-tab:${tab.id}:switch` });
17323
17342
  appendTerminalTabContent(button, { title: tab.title, indicator, meta: terminalTabMeta(tab, indicator), appRunnerRun, conversationModeActive, workflowModeActive, workflowCount });
17324
17343
  button.addEventListener("click", () => switchTab(tab.id));
17325
17344
  wrapper.append(button, createTerminalTabActions(tab));
@@ -17359,7 +17378,7 @@ function renderTerminalTabGroupItem(tab, group) {
17359
17378
  button.setAttribute("role", "tab");
17360
17379
  button.setAttribute("aria-selected", isActive ? "true" : "false");
17361
17380
  button.setAttribute("aria-label", `${tab.title}: ${indicator.label}${appRunnerLabel ? `, ${appRunnerLabel}` : ""}${conversationLabel}${workflowModeActive ? ", workflow mode active" : ""}${workflowCount ? `, ${workflowCount} workflow runs active` : ""}`);
17362
- applyStyledTooltip(button, terminalTabTooltip(tab), { ariaLabel: false, align: "start", description: true, variant: "workspace", targetKey: `terminal-tab:${tab.id}:switch` });
17381
+ applyStyledTooltip(button, terminalTabTooltip(tab), { ariaLabel: false, align: "start", description: true, preserveInternalSpaces: true, variant: "workspace", targetKey: `terminal-tab:${tab.id}:switch` });
17363
17382
  appendTerminalTabContent(button, { title: tab.title, indicator, meta: terminalTabMeta(tab, indicator), appRunnerRun, conversationModeActive, workflowModeActive, workflowCount });
17364
17383
  button.addEventListener("click", (event) => {
17365
17384
  event.stopPropagation();
@@ -17390,7 +17409,7 @@ function shouldRenderTerminalTabGroup(group, groupCount) {
17390
17409
 
17391
17410
  function renderTerminalTabGroup(group, groupCount = 1) {
17392
17411
  const groupTabs = group.tabs;
17393
- const activeGroupTab = groupTabs.find((tab) => tab.id === activeTabId) || groupTabs[0];
17412
+ const activeGroupTab = terminalTabGroupRepresentedTab(groupTabs);
17394
17413
  const isActive = !activeSubagentTerminalId && groupTabs.some((tab) => tab.id === activeTabId);
17395
17414
  const isStopped = groupTabs.every((tab) => !tab.running);
17396
17415
  const indicator = tabGroupIndicator(groupTabs);
@@ -17431,7 +17450,7 @@ function renderTerminalTabGroup(group, groupCount = 1) {
17431
17450
  button.setAttribute("aria-haspopup", "true");
17432
17451
  button.setAttribute("aria-expanded", group.key === openTerminalTabGroupKey ? "true" : "false");
17433
17452
  button.setAttribute("aria-label", `${groupTitle} ${group.custom ? "custom" : "cwd"} group: ${groupTabs.length} tabs, ${indicator.label}${appRunnerSummary ? `, ${appRunnerSummary}` : ""}${workflowModeActive ? ", workflow mode active" : ""}${workflowCount ? `, ${workflowCount} workflow runs active` : ""}. Active ${activeTitle}. ${isMobileView() ? "Toggle group terminal list" : "Switch to the active group terminal"}`);
17434
- applyStyledTooltip(button, terminalTabGroupTooltip(group, groupTitle), { ariaLabel: false, description: true, placement: "right", variant: "workspace", targetKey: `terminal-group:${group.key}:switch` });
17453
+ applyStyledTooltip(button, terminalTabGroupTooltip(group, groupTitle), { ariaLabel: false, description: true, placement: "right", preserveInternalSpaces: true, variant: "workspace", targetKey: `terminal-group:${group.key}:switch` });
17435
17454
  appendTerminalTabContent(button, { title: activeTitle, indicator, meta: `${groupTitle} · ${indicator.meta}${groupAppRunnerMeta ? ` · ${groupAppRunnerMeta}` : ""}${workflowModeActive ? " · workflow mode" : ""}${workflowCount ? ` · ${workflowCount} workflows` : ""}`, appRunnerRun, count: groupTabs.length, workflowModeActive, workflowCount, dropdown: true });
17436
17455
  button.addEventListener("click", () => {
17437
17456
  if (isMobileView()) {
@@ -19425,8 +19444,12 @@ function textFromContent(content) {
19425
19444
  .join("\n");
19426
19445
  }
19427
19446
 
19428
- function cleanTooltipText(value) {
19429
- return stripAnsi(value).replace(/\r\n?/g, "\n").replace(/[^\S\n]+/g, " ").replace(/\n{3,}/g, "\n\n").trim();
19447
+ function cleanTooltipText(value, { preserveInternalSpaces = false } = {}) {
19448
+ const normalized = stripAnsi(value).replace(/\r\n?/g, "\n");
19449
+ const whitespaceNormalized = preserveInternalSpaces
19450
+ ? normalized.replace(/[^\S\n ]+/g, " ")
19451
+ : normalized.replace(/[^\S\n]+/g, " ");
19452
+ return whitespaceNormalized.replace(/\n{3,}/g, "\n\n").trim();
19430
19453
  }
19431
19454
 
19432
19455
  const TOOLTIP_HOVER_DELAY_MS = 500;
@@ -19557,7 +19580,7 @@ let styledTooltipDescriptionSerial = 0;
19557
19580
 
19558
19581
  function applyStyledTooltip(node, tooltip, options = {}) {
19559
19582
  if (!node) return node;
19560
- const text = cleanTooltipText(tooltip);
19583
+ const text = cleanTooltipText(tooltip, { preserveInternalSpaces: options.preserveInternalSpaces === true });
19561
19584
  if (!text) return node;
19562
19585
  node.setAttribute("data-tooltip", text);
19563
19586
  node.removeAttribute("title");
@@ -30789,6 +30812,12 @@ function formatStatsCost(value) {
30789
30812
  return `$${cost.toFixed(2)}`;
30790
30813
  }
30791
30814
 
30815
+ function formatStatsCostWithCoverage(value, unpricedMessages) {
30816
+ const cost = statsNumber(value);
30817
+ if (statsNumber(unpricedMessages) <= 0) return formatStatsCost(cost);
30818
+ return cost > 0 ? `${formatStatsCost(cost)} recorded + unavailable` : "unavailable";
30819
+ }
30820
+
30792
30821
  function formatStatsPercent(value) {
30793
30822
  return `${statsNumber(value).toFixed(1)}%`;
30794
30823
  }
@@ -30812,6 +30841,10 @@ function formatStatsNullableCost(value) {
30812
30841
  return number === null ? "n/a" : formatStatsCost(number);
30813
30842
  }
30814
30843
 
30844
+ function formatStatsNullableCostWithCoverage(value, unpricedMessages) {
30845
+ return statsNumber(unpricedMessages) > 0 ? formatStatsCostWithCoverage(value, unpricedMessages) : formatStatsNullableCost(value);
30846
+ }
30847
+
30815
30848
  function formatStatsNullableTokens(value) {
30816
30849
  const number = statsNullableNumber(value);
30817
30850
  return number === null ? "n/a" : `${formatStatsTokens(number)} tok`;
@@ -30880,7 +30913,9 @@ function statsSpendComparison(summary) {
30880
30913
  recentStartDay: typeof comparison.recentStartDay === "string" ? comparison.recentStartDay : "",
30881
30914
  recentEndDay: typeof comparison.recentEndDay === "string" ? comparison.recentEndDay : "",
30882
30915
  recentCost: statsNumber(comparison.recentCost),
30916
+ recentUnpricedMessages: Math.max(0, statsNumber(comparison.recentUnpricedMessages)),
30883
30917
  priorCost: statsNumber(comparison.priorCost),
30918
+ priorUnpricedMessages: Math.max(0, statsNumber(comparison.priorUnpricedMessages)),
30884
30919
  changeCost: statsNullableNumber(comparison.changeCost),
30885
30920
  changePercent: statsNullableNumber(comparison.changePercent),
30886
30921
  };
@@ -30892,6 +30927,7 @@ function statsModelDriverEntries(payload) {
30892
30927
  name: model?.model || "unknown",
30893
30928
  cost: statsNumber(model?.cost),
30894
30929
  share: statsCostShareOf(model?.cost, totalCost),
30930
+ unpricedMessages: statsNumber(model?.unpricedMessages),
30895
30931
  }));
30896
30932
  }
30897
30933
 
@@ -30901,9 +30937,15 @@ function statsSessionDriverEntries(payload) {
30901
30937
  name: session?.displayName || session?.sessionId || "unknown",
30902
30938
  cost: statsNumber(session?.cost),
30903
30939
  share: statsCostShareOf(session?.cost, totalCost),
30940
+ unpricedMessages: statsNumber(session?.unpricedMessages),
30904
30941
  }));
30905
30942
  }
30906
30943
 
30944
+ function statsCostWarning(payload) {
30945
+ const warning = payload?.costInfo?.warning;
30946
+ return typeof warning === "string" ? warning.trim().slice(0, 600) : "";
30947
+ }
30948
+
30907
30949
  function parseStatsWebuiPayloadRaw(raw) {
30908
30950
  if (!raw) return null;
30909
30951
  try {
@@ -31057,14 +31099,14 @@ function renderStatsBarRows(daily = []) {
31057
31099
  make("span", "stats-overlay-bar-day", row.day || "—"),
31058
31100
  bar,
31059
31101
  make("span", "stats-overlay-bar-value", `${formatStatsTokens(row.total)} tok`),
31060
- make("span", "stats-overlay-bar-cost", formatStatsCost(row.cost)),
31102
+ make("span", "stats-overlay-bar-cost", formatStatsCostWithCoverage(row.cost, row.unpricedMessages)),
31061
31103
  );
31062
31104
  list.append(item);
31063
31105
  }
31064
31106
  wrapper.append(
31065
31107
  legend,
31066
31108
  list,
31067
- make("p", "stats-overlay-chart-caption muted", `${capped[0]?.day || "—"} → ${capped.at(-1)?.day || "—"} · peak ${formatStatsTokens(peakTokens?.total)} tok on ${peakTokens?.day || "—"} · peak spend ${formatStatsCost(peakCost?.cost)} on ${peakCost?.day || "—"}`),
31109
+ make("p", "stats-overlay-chart-caption muted", `${capped[0]?.day || "—"} → ${capped.at(-1)?.day || "—"} · peak ${formatStatsTokens(peakTokens?.total)} tok on ${peakTokens?.day || "—"} · peak spend ${formatStatsCostWithCoverage(peakCost?.cost, peakCost?.unpricedMessages)} on ${peakCost?.day || "—"}`),
31068
31110
  );
31069
31111
  const note = statsChartWindowNote(windowed, "active days");
31070
31112
  if (note) wrapper.append(note);
@@ -31072,13 +31114,14 @@ function renderStatsBarRows(daily = []) {
31072
31114
  }
31073
31115
 
31074
31116
  function renderStatsSpendChart(daily = []) {
31075
- const rows = statsArray(daily).map((row) => ({ day: String(row?.day || "—"), cost: Math.max(0, statsNumber(row?.cost)) }));
31117
+ const rows = statsArray(daily).map((row) => ({ day: String(row?.day || "—"), cost: Math.max(0, statsNumber(row?.cost)), unpricedMessages: Math.max(0, statsNumber(row?.unpricedMessages)) }));
31076
31118
  if (!rows.length) return make("p", "stats-overlay-empty muted", "No daily usage in this range.");
31077
31119
  const windowed = statsChartWindow(rows);
31078
31120
  const capped = windowed.capped;
31079
31121
  const maxCost = Math.max(0, ...capped.map((row) => row.cost));
31080
31122
  const total = capped.reduce((acc, row) => acc + row.cost, 0);
31081
- if (total <= 0) return make("p", "stats-overlay-empty muted", "No spend recorded in this range.");
31123
+ const unpricedMessages = capped.reduce((acc, row) => acc + row.unpricedMessages, 0);
31124
+ if (total <= 0) return make("p", "stats-overlay-empty muted", unpricedMessages > 0 ? `Recorded spend is unavailable for ${unpricedMessages} message${unpricedMessages === 1 ? "" : "s"} in this range.` : "No spend recorded in this range.");
31082
31125
  const peak = capped.reduce((best, row) => (row.cost > (best?.cost ?? -1) ? row : best), null);
31083
31126
  const wrapper = make("div", "stats-overlay-spend");
31084
31127
  const chart = make("div", "stats-overlay-spend-chart");
@@ -31089,11 +31132,11 @@ function renderStatsSpendChart(daily = []) {
31089
31132
  const bar = make("span", "stats-overlay-spend-bar");
31090
31133
  const height = maxCost > 0 ? Math.min(100, Math.max(row.cost > 0 ? 3 : 0, (row.cost / maxCost) * 100)) : 0;
31091
31134
  bar.style.height = `${height}%`;
31092
- col.title = `${row.day}: ${formatStatsCost(row.cost)}`;
31135
+ col.title = `${row.day}: ${formatStatsCostWithCoverage(row.cost, row.unpricedMessages)}`;
31093
31136
  col.append(bar);
31094
31137
  chart.append(col);
31095
31138
  }
31096
- const caption = make("p", "stats-overlay-chart-caption muted", `Daily spend ${capped[0].day} → ${capped.at(-1).day} · total ${formatStatsCost(total)} · peak ${formatStatsCost(peak?.cost ?? 0)} on ${peak?.day ?? "—"}${windowed.truncated ? ` · latest ${capped.length} of ${windowed.total} days` : ""}`);
31139
+ const caption = make("p", "stats-overlay-chart-caption muted", `Daily spend ${capped[0].day} → ${capped.at(-1).day} · total ${formatStatsCostWithCoverage(total, unpricedMessages)} · peak ${formatStatsCostWithCoverage(peak?.cost ?? 0, peak?.unpricedMessages)} on ${peak?.day ?? "—"}${windowed.truncated ? ` · latest ${capped.length} of ${windowed.total} days` : ""}`);
31097
31140
  wrapper.append(chart, caption);
31098
31141
  return wrapper;
31099
31142
  }
@@ -31131,8 +31174,8 @@ function renderStatsComposition(totals = {}) {
31131
31174
 
31132
31175
  function renderStatsDriverList(entries = [], emptyText = "No cost drivers in this range.") {
31133
31176
  const rows = statsArray(entries)
31134
- .map((entry) => ({ name: entry?.name || "unknown", cost: Math.max(0, statsNumber(entry?.cost)), share: statsNullableNumber(entry?.share) }))
31135
- .filter((entry) => entry.cost > 0)
31177
+ .map((entry) => ({ name: entry?.name || "unknown", cost: Math.max(0, statsNumber(entry?.cost)), share: statsNullableNumber(entry?.share), unpricedMessages: Math.max(0, statsNumber(entry?.unpricedMessages)) }))
31178
+ .filter((entry) => entry.cost > 0 || entry.unpricedMessages > 0)
31136
31179
  .slice(0, 8);
31137
31180
  if (!rows.length) return make("p", "stats-overlay-empty muted", emptyText);
31138
31181
  const maxCost = Math.max(...rows.map((entry) => entry.cost));
@@ -31149,7 +31192,7 @@ function renderStatsDriverList(entries = [], emptyText = "No cost drivers in thi
31149
31192
  make("span", "stats-overlay-driver-rank", String(index + 1)),
31150
31193
  make("span", "stats-overlay-driver-name", entry.name),
31151
31194
  bar,
31152
- make("span", "stats-overlay-driver-value", `${formatStatsCost(entry.cost)} · ${formatStatsNullablePercent(entry.share)}`),
31195
+ make("span", "stats-overlay-driver-value", `${formatStatsCostWithCoverage(entry.cost, entry.unpricedMessages)} · ${formatStatsNullablePercent(entry.share)}`),
31153
31196
  );
31154
31197
  list.append(row);
31155
31198
  }
@@ -31171,6 +31214,14 @@ function renderStatsTopDrivers(payload) {
31171
31214
  return grid;
31172
31215
  }
31173
31216
 
31217
+ function renderStatsCostWarning(payload) {
31218
+ const warning = statsCostWarning(payload);
31219
+ if (!warning) return null;
31220
+ const note = make("p", "stats-overlay-cost-warning", warning);
31221
+ note.setAttribute("role", "note");
31222
+ return note;
31223
+ }
31224
+
31174
31225
  function renderStatsOverview(payload) {
31175
31226
  const node = make("div", "stats-overlay-pane stats-overlay-overview");
31176
31227
  const totals = payload?.totals || {};
@@ -31182,12 +31233,12 @@ function renderStatsOverview(payload) {
31182
31233
  const cards = make("div", "stats-overlay-cards");
31183
31234
  cards.append(
31184
31235
  statsMetricCard("Total tokens", formatStatsTokens(totals.total), `↑${formatStatsTokens(totals.input)} ↓${formatStatsTokens(totals.output)}`, "tone-blue"),
31185
- statsMetricCard("Cost", formatStatsCost(totals.cost), `projected 30d ${formatStatsCost(summary.projected30DayCost)}`, "tone-green"),
31186
- statsMetricCard("Effective $/1M", formatStatsNullableCost(statsEffectiveCostRate(summary, totals)), "blended rate, not provider list pricing", "tone-sky"),
31236
+ statsMetricCard("Cost", formatStatsCostWithCoverage(totals.cost, totals.unpricedMessages), `projected 30d ${formatStatsCostWithCoverage(summary.projected30DayCost, totals.unpricedMessages)}`, "tone-green"),
31237
+ statsMetricCard("Effective $/1M", formatStatsNullableCostWithCoverage(statsEffectiveCostRate(summary, totals), totals.unpricedMessages), "blended rate, not provider list pricing", "tone-sky"),
31187
31238
  statsMetricCard("Messages", String(statsNumber(totals.messages)), sessionDetail, "tone-mauve"),
31188
31239
  statsMetricCard("PI initial prompt", `~${formatStatsTokens(payload?.promptEstimate?.total)} tok`, `${statsPromptEstimateSourceLabel(payload?.promptEstimate)} · ${payload?.promptEstimate?.confidence || "estimate"}`, "tone-yellow"),
31189
31240
  statsMetricCard("Cached-input share", formatStatsNullablePercent(cachedShare), `reads ${formatStatsTokens(totals.cacheRead)} · writes ${formatStatsTokens(totals.cacheWrite)} of ${formatStatsTokens(statsPromptSideTokens(summary, totals))} prompt-side tok`, "tone-teal"),
31190
- statsMetricCard("Active days", `${payload?.activeDayCount ?? 0}/${payload?.dayCount ?? 0}`, highest ? `peak ${highest.day} · ${formatStatsCost(highest.cost)}` : "no peak yet", "tone-pink"),
31241
+ statsMetricCard("Active days", `${payload?.activeDayCount ?? 0}/${payload?.dayCount ?? 0}`, highest ? `peak ${highest.day} · ${formatStatsCostWithCoverage(highest.cost, highest.unpricedMessages)}` : "no peak yet", "tone-pink"),
31191
31242
  );
31192
31243
  node.append(cards, make("h3", undefined, "Daily usage"), renderStatsBarRows(payload?.daily));
31193
31244
  return node;
@@ -31201,7 +31252,7 @@ function renderStatsDaily(payload) {
31201
31252
  statsArray(payload?.daily).map((row) => [
31202
31253
  row.day || "—",
31203
31254
  formatStatsTokens(row.total),
31204
- formatStatsCost(row.cost),
31255
+ formatStatsCostWithCoverage(row.cost, row.unpricedMessages),
31205
31256
  formatStatsTokens(row.input),
31206
31257
  formatStatsTokens(row.output),
31207
31258
  `${formatStatsTokens(row.cacheRead)} / ${formatStatsTokens(row.cacheWrite)}`,
@@ -31225,9 +31276,9 @@ function renderStatsModels(payload) {
31225
31276
  model.model || "unknown",
31226
31277
  formatStatsTokens(model.tokens),
31227
31278
  formatStatsPercent(model.percent),
31228
- formatStatsCost(model.cost),
31279
+ formatStatsCostWithCoverage(model.cost, model.unpricedMessages),
31229
31280
  formatStatsPercent(model.costPercent),
31230
- formatStatsCost(model.avgCostPerMillion),
31281
+ statsNumber(model.unpricedMessages) > 0 ? "unavailable" : formatStatsCost(model.avgCostPerMillion),
31231
31282
  formatStatsTokens(Math.round(statsNumber(model.avgOutputTokens))),
31232
31283
  String(statsNumber(model.messages)),
31233
31284
  ]),
@@ -31248,7 +31299,7 @@ function renderStatsSessions(payload) {
31248
31299
  statsArray(payload?.expensiveSessions).map((session) => [
31249
31300
  session.day || "—",
31250
31301
  session.displayName || session.sessionId || "unknown",
31251
- formatStatsCost(session.cost),
31302
+ formatStatsCostWithCoverage(session.cost, session.unpricedMessages),
31252
31303
  formatStatsTokens(session.tokens),
31253
31304
  session.model || "unknown",
31254
31305
  ]),
@@ -31265,18 +31316,19 @@ function renderStatsCostCache(payload) {
31265
31316
  const comparison = statsSpendComparison(summary);
31266
31317
  const scopedSessions = statsNullableNumber(payload?.scopedSessionCount);
31267
31318
  const sessionDetail = scopedSessions !== null ? `per session in range (${scopedSessions})` : "per session file (legacy count)";
31319
+ const comparisonPartial = !!comparison && (comparison.recentUnpricedMessages > 0 || comparison.priorUnpricedMessages > 0);
31268
31320
  const cards = make("div", "stats-overlay-cards compact");
31269
31321
  cards.append(
31270
- statsMetricCard("Avg/day", formatStatsCost(summary.calendarAvgCost), "calendar average", "tone-green"),
31271
- statsMetricCard("Active avg", formatStatsCost(summary.activeAvgCost), "per active day", "tone-teal"),
31272
- statsMetricCard("Effective $/1M", formatStatsNullableCost(statsEffectiveCostRate(summary, totals)), "blended rate, not provider list pricing", "tone-blue"),
31322
+ statsMetricCard("Avg/day", formatStatsCostWithCoverage(summary.calendarAvgCost, totals.unpricedMessages), "calendar average", "tone-green"),
31323
+ statsMetricCard("Active avg", formatStatsCostWithCoverage(summary.activeAvgCost, totals.unpricedMessages), "per active day", "tone-teal"),
31324
+ statsMetricCard("Effective $/1M", formatStatsNullableCostWithCoverage(statsEffectiveCostRate(summary, totals), totals.unpricedMessages), "blended rate, not provider list pricing", "tone-blue"),
31273
31325
  statsMetricCard("Cached-input share", formatStatsNullablePercent(statsCachedInputShare(summary, totals)), `reads ${formatStatsTokens(totals.cacheRead)} of ${formatStatsTokens(statsPromptSideTokens(summary, totals))} prompt-side tok`, "tone-yellow"),
31274
- statsMetricCard("Avg cost/session", formatStatsNullableCost(statsAverageCostPerSession(summary, payload)), `${formatStatsNullableTokens(statsAverageTokensPerSession(summary, payload))} · ${sessionDetail}`, "tone-mauve"),
31326
+ statsMetricCard("Avg cost/session", formatStatsNullableCostWithCoverage(statsAverageCostPerSession(summary, payload), totals.unpricedMessages), `${formatStatsNullableTokens(statsAverageTokensPerSession(summary, payload))} · ${sessionDetail}`, "tone-mauve"),
31275
31327
  statsMetricCard(
31276
31328
  "Recent spend",
31277
- comparison ? formatStatsCost(comparison.recentCost) : "n/a",
31329
+ comparison ? formatStatsCostWithCoverage(comparison.recentCost, comparison.recentUnpricedMessages) : "n/a",
31278
31330
  comparison
31279
- ? `${comparison.recentStartDay} → ${comparison.recentEndDay} (${comparison.windowDays}d) vs prior ${comparison.windowDays}d ${formatStatsCost(comparison.priorCost)} · ${formatStatsSignedCost(comparison.changeCost)} (${formatStatsNullablePercent(comparison.changePercent)})`
31331
+ ? `${comparison.recentStartDay} → ${comparison.recentEndDay} (${comparison.windowDays}d) vs prior ${comparison.windowDays}d ${formatStatsCostWithCoverage(comparison.priorCost, comparison.priorUnpricedMessages)} · ${comparisonPartial ? "change unavailable" : `${formatStatsSignedCost(comparison.changeCost)} (${formatStatsNullablePercent(comparison.changePercent)})`}`
31280
31332
  : "requires the latest stats extension",
31281
31333
  "tone-pink",
31282
31334
  ),
@@ -31825,7 +31877,8 @@ function renderStatsOverlay() {
31825
31877
  elements.statsOverlayBody.setAttribute("aria-labelledby", `statsOverlayTab-${statsOverlayActiveTab}`);
31826
31878
 
31827
31879
  elements.statsOverlayRefreshButton.disabled = statsOverlayLoading;
31828
- elements.statsOverlayBody.replaceChildren(renderStatsOverlayPane(payload));
31880
+ const costWarning = renderStatsCostWarning(payload);
31881
+ elements.statsOverlayBody.replaceChildren(...(costWarning ? [costWarning, renderStatsOverlayPane(payload)] : [renderStatsOverlayPane(payload)]));
31829
31882
  }
31830
31883
 
31831
31884
  function scheduleStatsRefreshAfterCalibration(tabContext, delays = [1200]) {
@@ -42689,6 +42742,8 @@ function slashCommandName(message) {
42689
42742
  }
42690
42743
 
42691
42744
  function openNativeCommandDialog({ title, message = "", searchPlaceholder = "" } = {}) {
42745
+ nativeCommandDialogGeneration += 1;
42746
+ const dialogGeneration = nativeCommandDialogGeneration;
42692
42747
  nativeCommandTabId ||= activeTabId;
42693
42748
  elements.nativeCommandTitle.textContent = title || "Pi command";
42694
42749
  elements.nativeCommandMessage.textContent = message;
@@ -42696,6 +42751,7 @@ function openNativeCommandDialog({ title, message = "", searchPlaceholder = "" }
42696
42751
  elements.nativeCommandSearch.value = "";
42697
42752
  elements.nativeCommandSearch.placeholder = searchPlaceholder || "Filter choices…";
42698
42753
  elements.nativeCommandSearch.hidden = !searchPlaceholder;
42754
+ elements.nativeCommandSearch.disabled = false;
42699
42755
  elements.nativeCommandSearch.oninput = null;
42700
42756
  elements.nativeCommandBody.replaceChildren();
42701
42757
  elements.nativeCommandError.hidden = true;
@@ -42704,6 +42760,7 @@ function openNativeCommandDialog({ title, message = "", searchPlaceholder = "" }
42704
42760
  addNativeCommandAction("Cancel", closeNativeCommandDialog);
42705
42761
  if (!elements.nativeCommandDialog.open) elements.nativeCommandDialog.showModal();
42706
42762
  if (searchPlaceholder) queueMicrotask(() => elements.nativeCommandSearch.focus());
42763
+ return dialogGeneration;
42707
42764
  }
42708
42765
 
42709
42766
  function closeNativeCommandDialog({ force = false } = {}) {
@@ -42721,6 +42778,7 @@ function closeNativeCommandDialog({ force = false } = {}) {
42721
42778
  });
42722
42779
  return;
42723
42780
  }
42781
+ nativeCommandDialogGeneration += 1;
42724
42782
  if (elements.nativeCommandDialog.open) elements.nativeCommandDialog.close();
42725
42783
  elements.nativeCommandSearch.oninput = null;
42726
42784
  nativeSettingsDirty = false;
@@ -43001,6 +43059,127 @@ function openNativeThemeSelector() {
43001
43059
  });
43002
43060
  }
43003
43061
 
43062
+ // The rollback choice is browser-only; the server contract represents it as path: null.
43063
+ const APPEND_SYSTEM_DEFAULT_CHOICE_ID = "__pi-default-discovery__";
43064
+
43065
+ async function openNativeAppendSystemSelector() {
43066
+ const dialogGeneration = openNativeCommandDialog({
43067
+ title: "/append-system",
43068
+ message: "Choose one global APPEND_SYSTEM.md append prompt for WebUI-managed Pi tabs. The bounded scan uses the active tab folder and ~/.pi up to depth 10, follows file and folder links even outside those roots, and never shows file contents. New tabs and reloaded tabs use this choice.",
43069
+ searchPlaceholder: "Filter APPEND_SYSTEM.md files…",
43070
+ });
43071
+ const ownsNativeCommandDialog = () => dialogGeneration === nativeCommandDialogGeneration && elements.nativeCommandDialog.open;
43072
+ let saveInFlight = false;
43073
+ renderNativeLoading("Scanning APPEND_SYSTEM.md candidates…");
43074
+ try {
43075
+ const response = await nativeCommandApi("/api/append-system-files");
43076
+ if (!ownsNativeCommandDialog()) return;
43077
+ const data = response.data || {};
43078
+ const savedPath = typeof data.appendSystemPromptPath === "string" && data.appendSystemPromptPath ? data.appendSystemPromptPath : "";
43079
+ const candidates = Array.isArray(data.candidates) ? data.candidates : [];
43080
+ const diagnostics = Array.isArray(data.diagnostics) ? data.diagnostics : [];
43081
+ const savedIsInvalid = !!savedPath && diagnostics.some((diagnostic) => diagnostic?.kind === "saved-selection-invalid" && diagnostic?.path === savedPath);
43082
+ const savedIsCandidate = !!savedPath && !savedIsInvalid && candidates.some((candidate) => candidate?.path === savedPath);
43083
+ const items = [];
43084
+ if (savedPath && !savedIsCandidate) {
43085
+ items.push({
43086
+ id: `__invalid-saved__:${savedPath}`,
43087
+ label: savedPath,
43088
+ description: "Saved choice is no longer a valid APPEND_SYSTEM.md candidate. See the diagnostics below; Pi falls back to default discovery.",
43089
+ badge: "invalid",
43090
+ badgeClass: "disabled",
43091
+ disabled: true,
43092
+ });
43093
+ }
43094
+ items.push({
43095
+ id: APPEND_SYSTEM_DEFAULT_CHOICE_ID,
43096
+ label: "Use Pi default discovery",
43097
+ description: "Remove the override. Pi finds APPEND_SYSTEM.md itself (project .pi/APPEND_SYSTEM.md or ~/.pi/agent/APPEND_SYSTEM.md).",
43098
+ badge: savedIsCandidate ? "" : "current",
43099
+ appendSystemPath: null,
43100
+ });
43101
+ for (const candidate of candidates) {
43102
+ if (!candidate?.path) continue;
43103
+ items.push({
43104
+ id: candidate.path,
43105
+ label: candidate.path,
43106
+ description: `Visible path${candidate.rootLabel ? ` found below ${candidate.rootLabel}` : ""}; linked targets may be outside that root.`,
43107
+ meta: candidate.rootLabel || "",
43108
+ badge: savedIsCandidate && candidate.path === savedPath ? "current" : "",
43109
+ appendSystemPath: candidate.path,
43110
+ });
43111
+ }
43112
+ const appendDiagnostics = () => {
43113
+ if (!diagnostics.length) return;
43114
+ const note = make("div", "native-settings-note");
43115
+ note.append(make("strong", undefined, "Scan diagnostics"));
43116
+ for (const diagnostic of diagnostics.slice(0, 20)) {
43117
+ const line = [diagnostic?.kind, diagnostic?.path, diagnostic?.message].filter(Boolean).join(" · ");
43118
+ if (line) note.append(make("span", undefined, line));
43119
+ }
43120
+ elements.nativeCommandBody.append(note);
43121
+ };
43122
+ const render = () => {
43123
+ renderNativeSelectorItems(items, {
43124
+ emptyText: "No APPEND_SYSTEM.md files match this filter.",
43125
+ activeId: savedIsCandidate ? savedPath : APPEND_SYSTEM_DEFAULT_CHOICE_ID,
43126
+ onSelect: async (item) => {
43127
+ if (!ownsNativeCommandDialog() || saveInFlight) return;
43128
+ saveInFlight = true;
43129
+ elements.nativeCommandSearch.disabled = true;
43130
+ for (const button of nativeSelectorItemButtons()) button.disabled = true;
43131
+ setNativeCommandError("");
43132
+ const tabId = nativeCommandTabId || activeTabId;
43133
+ try {
43134
+ const response = await nativeCommandApi("/api/append-system-selection", {
43135
+ method: "POST",
43136
+ body: { tabId, path: item.appendSystemPath ?? null },
43137
+ });
43138
+ if (!ownsNativeCommandDialog()) return;
43139
+ const result = response.data || {};
43140
+ addTransientMessage({
43141
+ role: "native",
43142
+ title: "/append-system",
43143
+ content: result.changed === true
43144
+ ? `Append-system choice saved: ${item.label}.`
43145
+ : `Append-system choice unchanged: ${item.label}.`,
43146
+ level: "info",
43147
+ });
43148
+ closeNativeCommandDialog();
43149
+ if (result.changed === true && result.restartRequired === true) await confirmAppendSystemRestart(tabId);
43150
+ } catch (error) {
43151
+ if (!ownsNativeCommandDialog()) return;
43152
+ saveInFlight = false;
43153
+ elements.nativeCommandSearch.disabled = false;
43154
+ render();
43155
+ setNativeCommandError(error.message || String(error));
43156
+ }
43157
+ },
43158
+ });
43159
+ appendDiagnostics();
43160
+ };
43161
+ elements.nativeCommandSearch.oninput = render;
43162
+ render();
43163
+ } catch (error) {
43164
+ if (!ownsNativeCommandDialog()) return;
43165
+ setNativeCommandError(`Append-system scan failed: ${error.message || String(error)}`);
43166
+ elements.nativeCommandBody.replaceChildren();
43167
+ }
43168
+ }
43169
+
43170
+ async function confirmAppendSystemRestart(tabId) {
43171
+ const confirmed = await appConfirmText(
43172
+ "Restart the active Pi tab now to load the new append-system prompt?\n\nThe saved choice is global for WebUI tabs and already persists. Cancel keeps it for the next manual reload or new tab without restarting.",
43173
+ { affected: "The active Pi tab", confirmLabel: "Restart tab", danger: false },
43174
+ );
43175
+ if (!confirmed) return;
43176
+ try {
43177
+ await sendPrompt("prompt", "/reload", { targetTabId: tabId, throwOnError: true });
43178
+ } catch (error) {
43179
+ addEvent(`Append-system tab restart failed: ${error.message || String(error)}`, "error");
43180
+ }
43181
+ }
43182
+
43004
43183
  function nativeSettingsBadge(label, tone = "") {
43005
43184
  return make("span", `native-settings-badge${tone ? ` native-settings-badge-${tone}` : ""}`, label);
43006
43185
  }
@@ -47236,6 +47415,7 @@ function commandPaletteCoreItems() {
47236
47415
  { kind: "Pi", label: "/scoped-models", description: "Manage model cycling scope", keywords: "models cycle ctrl p", run: () => runNativeCommandMenu("/scoped-models") },
47237
47416
  { kind: "Pi", label: "/tools", description: "Manage active tools", keywords: "capabilities", run: () => runNativeCommandMenu("/tools") },
47238
47417
  { kind: "Pi", label: "/skills", description: "Manage active skills", keywords: "system prompt", run: () => runNativeCommandMenu("/skills") },
47418
+ { kind: "Pi", label: "/append-system", description: "Choose the APPEND_SYSTEM.md append prompt", keywords: "append system prompt settings global", run: () => openNativeAppendSystemSelector() },
47239
47419
  { kind: "Pi", label: "/theme", description: "Choose the Web UI theme", keywords: "dark light colors appearance", run: () => openNativeThemeSelector() },
47240
47420
  { kind: "Git", label: "Guided Git workflow", description: "Stage, commit, push, or open a pull request step by step", keywords: "git commit push pr publish", run: () => launchGuidedGitWorkflow() },
47241
47421
  { kind: "Git", label: "Git changes", description: "Review and stage local changes with diffs", keywords: "git diff stage unstage discard status", run: () => openGitChangesDialog() },
@@ -49684,6 +49864,10 @@ elements.optionsRemoteButton.addEventListener("click", () => runNativeCommandMen
49684
49864
  elements.optionsNameButton.addEventListener("click", () => runNativeCommandMenu("/name"));
49685
49865
  elements.optionsCloneButton.addEventListener("click", () => runNativeCommandMenu("/clone"));
49686
49866
  elements.optionsSettingsButton.addEventListener("click", () => runNativeCommandMenu("/settings"));
49867
+ elements.optionsAppendSystemButton?.addEventListener("click", () => {
49868
+ setOptionsMenuOpen(false);
49869
+ void openNativeAppendSystemSelector();
49870
+ });
49687
49871
  elements.optionsSummarySetupButton?.addEventListener("click", () => runNativeCommandMenu("/summary-setup"));
49688
49872
  elements.optionsWorkflowSetupButton?.addEventListener("click", () => runNativeCommandMenu("/workflow-setup"));
49689
49873
  elements.optionsSafetyGuardSetupButton?.addEventListener("click", () => runNativeCommandMenu("/safety-guard-setup"));
@@ -49796,6 +49980,7 @@ elements.nativeCommandDialog.querySelector("form")?.addEventListener("submit", (
49796
49980
  });
49797
49981
  elements.nativeCommandSearch.addEventListener("keydown", handleNativeSelectorSearchKeydown);
49798
49982
  elements.nativeCommandDialog.addEventListener("close", () => {
49983
+ nativeCommandDialogGeneration += 1;
49799
49984
  elements.nativeCommandSearch.oninput = null;
49800
49985
  nativeSettingsDirty = false;
49801
49986
  nativeCommandTabId = null;
package/public/index.html CHANGED
@@ -479,7 +479,7 @@
479
479
  aria-haspopup="menu"
480
480
  aria-expanded="false"
481
481
  aria-controls="optionsMenu"
482
- data-tooltip="Options: command palette, Workflow Permission Setup, Safety Guard Setup, Guided Git Setup, Git-footer Visibility, natural conversation, resume, reload, remote, name, clone, settings, export, fork, or tree."
482
+ data-tooltip="Options: command palette, Append-system Prompt, Workflow Permission Setup, Safety Guard Setup, Guided Git Setup, Git-footer Visibility, natural conversation, resume, reload, remote, name, clone, settings, export, fork, or tree."
483
483
  ><svg class="composer-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M4 7h16M4 12h16M4 17h16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/><circle cx="8" cy="7" r="1.6" fill="currentColor"/><circle cx="16" cy="12" r="1.6" fill="currentColor"/><circle cx="11" cy="17" r="1.6" fill="currentColor"/></svg></button>
484
484
  <div id="optionsMenu" class="composer-publish-menu-panel composer-options-menu-panel composer-auto-height-menu-panel" role="menu" aria-label="Common Pi options">
485
485
  <button id="optionsCommandPaletteButton" class="composer-publish-menu-item composer-options-menu-item" type="button" role="menuitem">
@@ -527,6 +527,9 @@
527
527
  <button class="composer-publish-menu-item composer-options-menu-item composer-options-submenu-back" type="button" role="menuitem" data-options-submenu-back>
528
528
  <span aria-hidden="true">‹</span><span>Back</span>
529
529
  </button>
530
+ <button id="optionsAppendSystemButton" class="composer-publish-menu-item composer-options-menu-item" type="button" role="menuitem">
531
+ <span>Append-system Prompt</span>
532
+ </button>
530
533
  <button id="optionsSummarySetupButton" class="composer-publish-menu-item composer-options-menu-item" type="button" role="menuitem" data-command="/summary-setup" hidden>
531
534
  <span>Session Summary Setup</span>
532
535
  </button>
@@ -1892,7 +1895,7 @@
1892
1895
  </form>
1893
1896
  </dialog>
1894
1897
 
1895
- <script id="webuiBootLoader" data-app-src="/app.js?v=182">
1898
+ <script id="webuiBootLoader" data-app-src="/app.js?v=183">
1896
1899
  (() => {
1897
1900
  "use strict";
1898
1901
 
@@ -1,4 +1,4 @@
1
- const CACHE_NAME = "pi-webui-pwa-v153";
1
+ const CACHE_NAME = "pi-webui-pwa-v154";
2
2
  const APP_SHELL = [
3
3
  "/",
4
4
  "/index.html",
package/public/styles.css CHANGED
@@ -13219,6 +13219,15 @@ body.subagent-terminal-active .composer-remote-mic-consent {
13219
13219
  color: var(--ctp-red);
13220
13220
  border-color: rgba(243, 139, 168, 0.38);
13221
13221
  }
13222
+ .stats-overlay-cost-warning {
13223
+ margin: 0 0 0.72rem;
13224
+ padding: 0.62rem 0.75rem;
13225
+ border: 1px solid rgba(249, 226, 175, 0.38);
13226
+ border-radius: 0.75rem;
13227
+ background: rgba(249, 226, 175, 0.08);
13228
+ color: var(--ctp-yellow);
13229
+ line-height: 1.45;
13230
+ }
13222
13231
  .stats-overlay-tabs {
13223
13232
  display: flex;
13224
13233
  gap: 0.42rem;