@firstpick/pi-package-webui 0.9.2 → 0.9.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 (78) hide show
  1. package/README.md +14 -8
  2. package/bin/pi-webui.mjs +256 -39
  3. package/index.ts +266 -1
  4. package/lib/git-workflow-preferences.mjs +8 -25
  5. package/lib/intercom-conversations.mjs +491 -0
  6. package/lib/intercom-transcript-filter.mjs +99 -0
  7. package/lib/resource-selection.mjs +140 -0
  8. package/package.json +2 -2
  9. package/public/app.js +1061 -119
  10. package/public/index.html +31 -6
  11. package/public/service-worker.js +2 -1
  12. package/public/stream-output-controller.mjs +15 -0
  13. package/public/styles.css +426 -1
  14. package/public/syntax-highlight.mjs +622 -0
  15. package/tests/boot-failure-diagnostics.test.mjs +3 -3
  16. package/tests/browser/interaction-continuity.spec.mjs +34 -0
  17. package/tests/browser/intercom-conversation-viewer.spec.mjs +357 -0
  18. package/tests/browser/persistent-ui-layout.spec.mjs +61 -0
  19. package/tests/browser/resource-profiles.spec.mjs +200 -0
  20. package/tests/browser/subagent-observability.spec.mjs +29 -0
  21. package/tests/codex-fast-mode-static.test.mjs +7 -6
  22. package/tests/common-options-submenus-interaction-static.test.mjs +2 -0
  23. package/tests/common-options-submenus-markup-static.test.mjs +1 -0
  24. package/tests/composer-action-grid-reorder-static.test.mjs +3 -3
  25. package/tests/composer-skill-tag-layout.test.mjs +32 -2
  26. package/tests/control-deck-component-updates-static.test.mjs +4 -0
  27. package/tests/controls-layout-static.test.mjs +3 -3
  28. package/tests/fast-mode-client-static.test.mjs +2 -2
  29. package/tests/feature-decision-output-popup-static.test.mjs +2 -2
  30. package/tests/feature-system-prompt-optional-feature-static.test.mjs +5 -5
  31. package/tests/file-viewer-image-static.test.mjs +69 -0
  32. package/tests/fixtures/fake-pi.mjs +105 -6
  33. package/tests/foreground-transcript-catch-up-static.test.mjs +1 -1
  34. package/tests/git-panel-file-preview-static.test.mjs +5 -5
  35. package/tests/git-panel-live-updates-static.test.mjs +3 -3
  36. package/tests/git-workflow-preferences.test.mjs +4 -4
  37. package/tests/http-endpoints-harness.test.mjs +124 -2
  38. package/tests/intercom-conversation-viewer-static.test.mjs +106 -0
  39. package/tests/intercom-conversations-http.test.mjs +252 -0
  40. package/tests/intercom-conversations.test.mjs +374 -0
  41. package/tests/intercom-main-transcript-suppression-static.test.mjs +52 -0
  42. package/tests/intercom-tag-layout-static.test.mjs +46 -0
  43. package/tests/intercom-transcript-filter.test.mjs +98 -0
  44. package/tests/main-output-loading-static.test.mjs +59 -0
  45. package/tests/middle-button-drag-scroll-static.test.mjs +3 -3
  46. package/tests/mobile-compact-layout.test.mjs +2 -3
  47. package/tests/mobile-continuity-tablet-static.test.mjs +6 -6
  48. package/tests/mobile-foundation-static.test.mjs +3 -3
  49. package/tests/mobile-phone-experience-static.test.mjs +1 -1
  50. package/tests/mobile-static.test.mjs +66 -42
  51. package/tests/native-parity.test.mjs +8 -7
  52. package/tests/open-issue-wizard-static.test.mjs +1 -1
  53. package/tests/optional-feature-migration-frontend.test.mjs +5 -5
  54. package/tests/optional-feature-resource-setup-static.test.mjs +29 -0
  55. package/tests/persistent-ui-layout-static.test.mjs +3 -3
  56. package/tests/questionnaire-dialog.test.mjs +3 -3
  57. package/tests/remote-auth-settings-harness.test.mjs +1 -1
  58. package/tests/resource-defaults-helper.test.mjs +60 -6
  59. package/tests/resource-selection.test.mjs +114 -0
  60. package/tests/resource-tui-extension.test.mjs +23 -0
  61. package/tests/session-sampling-ui-static.test.mjs +3 -3
  62. package/tests/side-panel-section-height-removal-static.test.mjs +3 -3
  63. package/tests/stream-output-controller.test.mjs +8 -0
  64. package/tests/stream-output-isolation-static.test.mjs +2 -2
  65. package/tests/streaming-ui-coupling.test.mjs +5 -0
  66. package/tests/subagent-gate-visibility.test.mjs +1 -1
  67. package/tests/subagent-launch-slots.test.mjs +1 -1
  68. package/tests/subagent-observability-static.test.mjs +5 -3
  69. package/tests/subagent-reliability-integration.test.mjs +23 -1
  70. package/tests/subagent-workflow-section-static.test.mjs +67 -0
  71. package/tests/subagents-helper.test.mjs +313 -1
  72. package/tests/syntax-highlight.test.mjs +235 -0
  73. package/tests/syntax-highlighting-static.test.mjs +84 -0
  74. package/tests/terminal-cwd-grouping-static.test.mjs +22 -0
  75. package/tests/theme-customizer-static.test.mjs +5 -5
  76. package/tests/thinking-format-parser.test.mjs +64 -0
  77. package/tests/webui-settings-locking.test.mjs +1 -1
  78. package/webui-rpc-helper.mjs +417 -74
package/README.md CHANGED
@@ -17,8 +17,8 @@ Pi Web UI keeps the normal Pi agent experience while giving you more room to man
17
17
 
18
18
  | Area | Highlights |
19
19
  | --- | --- |
20
- | **Sessions and workspaces** | Run several isolated Pi sessions, resume prior work, switch projects, preserve per-tab drafts, and create branch worktrees. |
21
- | **Live agent work** | Follow streaming Markdown, thinking, tool output, queues, todo progress, and managed or registered Pi agent runs without leaving the browser. |
20
+ | **Sessions and workspaces** | Run several isolated Pi sessions, resume prior work, switch projects, preserve per-tab drafts, add another tab directly from the tab strip, and create branch worktrees. |
21
+ | **Live agent work** | Follow streaming Markdown with syntax highlighting for code blocks, thinking, tool output, queues, todo progress, managed agent runs, and direct agent-to-agent conversations without leaving the browser. |
22
22
  | **Models and controls** | Change models and thinking effort, manage scoped models, configure tools and skills, and use the command palette. |
23
23
  | **Files and prompts** | Upload or paste files and images, edit text attachments, use slash-command suggestions, browse project files, and reference project paths with `@`. |
24
24
  | **Git workflows** | Inspect changes, switch branches, review diffs, stage work, generate commit messages, push, and prepare pull requests through guided steps. |
@@ -64,10 +64,16 @@ Check the server at any time with:
64
64
  5. Open the Control Deck for sessions, Git, app runners, themes, updates, and optional features. Under **Controls → Interface**, choose **Top bar** or **Sidebar** for terminal tabs, then choose **Right**, **Left**, or **Both** for the Control Deck. In **Sidebar**, **Both** is unavailable; choosing **Right** or **Left** swaps the Control Deck and terminal/tabs rails across the chat.
65
65
  6. On desktop, drag the workspace-facing edge of any visible Control Deck—or the terminal/tabs rail in **Sidebar**—to choose a comfortable width. In **Both**, resize the left and right Control Decks independently; widths return on your next visit.
66
66
 
67
- Open **Subagents** to follow agent runs launched by managed extensions or registered SDK, RPC, JSON, print, interactive, tmux, workflow, schedule, gate, and custom integrations. Runs linked to an open WebUI terminal stay in that terminal’s group; other registered runs appear under **External agents**. Each row shows its launch source and lifecycle, and only offers output or controls that its owner supports.
67
+ When session history is still loading, the main window shows **Loading agent output…** with a small inline spinner. Existing transcript content and controls remain available; no popup interrupts your work.
68
+
69
+ Tracked skills appear as compact tags above the composer. Select a named tag to open its skill file; when space is limited, select the **+X** tag to expand the remaining selectable tags upward.
70
+
71
+ Open **Subagents** to follow agent runs launched by managed extensions or registered SDK, RPC, JSON, print, interactive, tmux, workflow, schedule, gate, and custom integrations. Runs linked to an open WebUI terminal stay in that terminal’s group; other registered runs appear under **External agents**. Each agent row shows its launch source and lifecycle, and only offers output or controls that its owner supports. A `pi-subagents` workflow appears as a collapsible **Workflow** header with its model-powered agents nested inside, rather than as another agent row. Starting or restarting the server reconnects active runs without reopening stale, lost, or already-finished rows from an earlier server run.
68
72
 
69
73
  Independent Pi processes do not appear automatically. Start them through `pi-webui agent run`, attach a persisted session with `pi-webui agent attach`, or use a cooperating registration adapter. See [TECHNICAL.md](TECHNICAL.md#subagent-observability) for supported commands and limitations.
70
74
 
75
+ When agents exchange direct Intercom messages or use native subagent-supervisor coordination, one compact tag per conversation appears beneath the composer. Up to eight tags share one row; denser groups wrap into a compact grid instead of creating a horizontal scrollbar. Long names shorten with an ellipsis, while the full name remains available to assistive technology and on hover. Select a tag to open a read-only chat view showing the two agent names or IDs and their messages. Generic Intercom transport calls and received Intercom records stay out of the main agent-output transcript, while attachments, tool output, and reasoning remain excluded from the chat view.
76
+
71
77
  Useful shortcuts:
72
78
 
73
79
  - `Ctrl/Cmd+K` opens the command palette.
@@ -111,7 +117,7 @@ Browse, search, save, or create project directories and open them in the active
111
117
 
112
118
  **Optional feature needed:** None — the Files panel is included in Pi Web UI core.
113
119
 
114
- Browse and search the files of the active project, open them in the viewer, and use the row menu for file actions. In a Git repository, files and folders that Git ignores stay listed and fully usable, but appear greyed out so generated output such as `node_modules` or build folders is easy to tell apart. Point at a greyed row to see the “Ignored by Git” hint in its tooltip.
120
+ Browse and search the files of the active project, open them in the viewer, and use the row menu for file actions. The viewer edits text, previews Markdown, and displays PNG, JPEG, GIF, WebP, and AVIF images read-only. In a Git repository, files and folders that Git ignores stay listed and fully usable, but appear greyed out so generated output such as `node_modules` or build folders is easy to tell apart. Point at a greyed row to see the “Ignored by Git” hint in its tooltip.
115
121
 
116
122
  #### Queue manager
117
123
 
@@ -129,7 +135,7 @@ Review follow-ups, steering messages, user-bash work, and prompt lists while a t
129
135
 
130
136
  **Optional feature needed:** None — included in Pi Web UI core.
131
137
 
132
- Choose the supported reasoning effort before sending the next prompt.
138
+ Choose the supported reasoning effort before sending the next prompt. Local models that return tagged `<think>…</think>` reasoning keep that content in the Thinking card, including literal tag examples inside the reasoning.
133
139
 
134
140
  #### Scoped models
135
141
 
@@ -145,7 +151,7 @@ Search available models and control project or global model scope and cycling or
145
151
 
146
152
  **Optional feature needed:** None — the browser tools setup is included in Pi Web UI core.
147
153
 
148
- Enable tools for the current session or save the allowlist inherited by future sessions.
154
+ Enable tools for the current session, save a global default, or configure an exact model profile. Selecting that model automatically applies its tool profile unless the session has its own tool selection.
149
155
 
150
156
  #### Skills setup
151
157
 
@@ -153,7 +159,7 @@ Enable tools for the current session or save the allowlist inherited by future s
153
159
 
154
160
  **Optional feature needed:** None — the browser skills setup is included in Pi Web UI core.
155
161
 
156
- Find installed skills and manage session-specific or global activation.
162
+ 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.
157
163
 
158
164
  ### Project automation and Git
159
165
 
@@ -225,7 +231,7 @@ Explore token, cost, cache, model, session, and daily usage through the optional
225
231
 
226
232
  ## Optional features
227
233
 
228
- Open **Optional features** in the side panel to discover Web UI-aware companions. Configurable companions expose separate **Enable/Disable** and **Setup** actions, so configuration remains available without forcing a feature on.
234
+ Open **Optional features** in the side panel to discover Web UI-aware companions. Configurable companions expose separate **Enable/Disable** and **Setup** actions, so configuration remains available without forcing a feature on. The loaded **TUI Skills command** and **TUI Tools command** rows provide **Setup** buttons for the browser-native Skills Setup and Tools Setup dialogs.
229
235
 
230
236
  Popular additions include:
231
237
 
package/bin/pi-webui.mjs CHANGED
@@ -25,6 +25,8 @@ import { resolveCodexUsageAuth } from "../lib/codex-usage-auth.mjs";
25
25
  import { AgentRunIndex, canonicalAgentRunId, normalizeAgentInstance } from "../lib/agent-run-protocol.mjs";
26
26
  import { AgentRunRegistry } from "../lib/agent-run-registry.mjs";
27
27
  import { resolveScopedModelsFromPatterns } from "../lib/scoped-models.mjs";
28
+ import { projectIntercomConversations } from "../lib/intercom-conversations.mjs";
29
+ import { filterIntercomTranscriptMessages } from "../lib/intercom-transcript-filter.mjs";
28
30
  import {
29
31
  readSessionSummaryPreferences,
30
32
  supportedSessionSummaryThinkingLevels,
@@ -90,6 +92,12 @@ import {
90
92
  writeGitWorkflowPreferences,
91
93
  writeWebuiSettings,
92
94
  } from "../lib/git-workflow-preferences.mjs";
95
+ import {
96
+ exactModelProfile,
97
+ preserveUnavailableResourceNames,
98
+ resolveResourceSelection,
99
+ setExactModelProfile,
100
+ } from "../lib/resource-selection.mjs";
93
101
  import {
94
102
  UI_LAYOUT_REQUEST_MAX_BYTES,
95
103
  mergeUiLayout,
@@ -241,6 +249,14 @@ const RECOVERY_TITLE = "Anthropic compatibility recovery";
241
249
  const SKILL_FILE_BODY_LIMIT_BYTES = 2 * 1024 * 1024;
242
250
  const FILE_VIEWER_MAX_BYTES = 2 * 1024 * 1024;
243
251
  const FILE_VIEWER_BODY_LIMIT_BYTES = FILE_VIEWER_MAX_BYTES + 64 * 1024;
252
+ const FILE_VIEWER_IMAGE_MIME_TYPES_BY_EXTENSION = Object.freeze({
253
+ ".png": "image/png",
254
+ ".jpg": "image/jpeg",
255
+ ".jpeg": "image/jpeg",
256
+ ".gif": "image/gif",
257
+ ".webp": "image/webp",
258
+ ".avif": "image/avif",
259
+ });
244
260
  const FILE_TREE_MAX_ENTRIES = 1200;
245
261
  const FILE_TREE_ENTRY_STAT_CONCURRENCY = 32;
246
262
  const FILE_SEARCH_MAX_RESULTS = 200;
@@ -9206,6 +9222,17 @@ function dismissAgentRunProjection(instance, now = Date.now()) {
9206
9222
  dismissedAgentRunProjectionKeys.set(key, now);
9207
9223
  pruneDismissedAgentRunProjections(now);
9208
9224
  }
9225
+
9226
+ const startupSuppressedAgentRunProjectionKeys = new Set();
9227
+ try {
9228
+ const startupRegistrySnapshot = await agentRunRegistry.readRecords();
9229
+ for (const record of startupRegistrySnapshot.records) {
9230
+ if (!agentRunIsActive(record.instance)) startupSuppressedAgentRunProjectionKeys.add(agentRunProjectionKey(record.instance));
9231
+ }
9232
+ } catch {
9233
+ // Registry startup is best-effort; normal reconciliation reports later availability errors.
9234
+ }
9235
+
9209
9236
  const recoveryEndpointToken = String(process.env.PI_WEBUI_RECOVERY_TOKEN || "").trim() || `${randomUUID()}${randomUUID()}`;
9210
9237
  const recoveryEndpointTokens = new Set([recoveryEndpointToken]);
9211
9238
 
@@ -10020,6 +10047,10 @@ function normalizeWebuiSubagentFleet(value) {
10020
10047
  return { version: 1, totalActive, omitted };
10021
10048
  }
10022
10049
 
10050
+ function agentRunIsActive(value) {
10051
+ return ["queued", "running"].includes(value?.status);
10052
+ }
10053
+
10023
10054
  function normalizeWebuiSubagentPayload(value) {
10024
10055
  if (!value || typeof value !== "object" || value.version !== 1) return null;
10025
10056
  const runs = [];
@@ -10150,21 +10181,46 @@ function normalizeWebuiAgentRunPayload(value) {
10150
10181
  };
10151
10182
  }
10152
10183
 
10184
+ function filterStartupInactiveRows(tab, payload, { rowsKey, stateKey }) {
10185
+ if (!payload) return payload;
10186
+ const rows = Array.isArray(payload[rowsKey]) ? payload[rowsKey] : [];
10187
+ const seenKey = `${stateKey}Seen`;
10188
+ const suppressedKey = `${stateKey}Suppressed`;
10189
+ const suppressed = tab[suppressedKey] instanceof Set ? tab[suppressedKey] : new Set();
10190
+ if (tab[seenKey] !== true) {
10191
+ for (const row of rows) if (!agentRunIsActive(row)) suppressed.add(row.instanceId || row.id);
10192
+ tab[seenKey] = true;
10193
+ tab[suppressedKey] = suppressed;
10194
+ }
10195
+ const visibleRows = rows.filter((row) => {
10196
+ const id = row.instanceId || row.id;
10197
+ if (!suppressed.has(id)) return true;
10198
+ if (!agentRunIsActive(row)) return false;
10199
+ suppressed.delete(id);
10200
+ return true;
10201
+ });
10202
+ return { ...payload, [rowsKey]: visibleRows };
10203
+ }
10204
+
10153
10205
  function rememberWebuiSubagentsStatusEvent(tab, event) {
10154
10206
  if (event?.type !== "extension_ui_request" || event.method !== "setStatus") return false;
10155
10207
  const statusText = String(event.statusText || "");
10156
10208
  if (event.statusKey === WEBUI_SUBAGENTS_V2_STATUS_KEY) {
10157
10209
  if (!statusText) { tab.webuiAgentRuns = null; return true; }
10158
10210
  if (!statusText.startsWith(WEBUI_SUBAGENTS_V2_PAYLOAD_PREFIX)) return true;
10159
- try { tab.webuiAgentRuns = normalizeWebuiAgentRunPayload(JSON.parse(statusText.slice(WEBUI_SUBAGENTS_V2_PAYLOAD_PREFIX.length))); }
10160
- catch { tab.webuiAgentRuns = null; }
10211
+ try {
10212
+ const payload = normalizeWebuiAgentRunPayload(JSON.parse(statusText.slice(WEBUI_SUBAGENTS_V2_PAYLOAD_PREFIX.length)));
10213
+ tab.webuiAgentRuns = filterStartupInactiveRows(tab, payload, { rowsKey: "instances", stateKey: "webuiAgentRunStartup" });
10214
+ } catch { tab.webuiAgentRuns = null; }
10161
10215
  return true;
10162
10216
  }
10163
10217
  if (event.statusKey !== WEBUI_SUBAGENTS_STATUS_KEY) return false;
10164
10218
  if (!statusText) { tab.webuiSubagents = null; return true; }
10165
10219
  if (!statusText.startsWith(WEBUI_SUBAGENTS_PAYLOAD_PREFIX)) return true;
10166
- try { tab.webuiSubagents = normalizeWebuiSubagentPayload(JSON.parse(statusText.slice(WEBUI_SUBAGENTS_PAYLOAD_PREFIX.length))); }
10167
- catch { tab.webuiSubagents = null; }
10220
+ try {
10221
+ const payload = normalizeWebuiSubagentPayload(JSON.parse(statusText.slice(WEBUI_SUBAGENTS_PAYLOAD_PREFIX.length)));
10222
+ tab.webuiSubagents = filterStartupInactiveRows(tab, payload, { rowsKey: "runs", stateKey: "webuiSubagentStartup" });
10223
+ } catch { tab.webuiSubagents = null; }
10168
10224
  return true;
10169
10225
  }
10170
10226
 
@@ -11286,12 +11342,18 @@ async function webuiSubagentsData({ includeSelections = false } = {}) {
11286
11342
  }
11287
11343
  registrySnapshot = await agentRunRegistry.readRecords({ now: reconcileNow });
11288
11344
  } catch { diagnostics.push({ code: "registry-unavailable" }); }
11345
+ const visibleRegistryRecords = [];
11289
11346
  for (const record of registrySnapshot.records) {
11290
11347
  const key = agentRunProjectionKey(record.instance);
11348
+ if (startupSuppressedAgentRunProjectionKeys.has(key)) {
11349
+ if (!agentRunIsActive(record.instance)) continue;
11350
+ startupSuppressedAgentRunProjectionKeys.delete(key);
11351
+ }
11291
11352
  if (dismissedAgentRunProjectionKeys.has(key)) {
11292
11353
  if (agentRunProjectionCanBeDismissed(record.instance)) continue;
11293
11354
  dismissedAgentRunProjectionKeys.delete(key);
11294
11355
  }
11356
+ visibleRegistryRecords.push(record);
11295
11357
  index.upsert(record.instance, { producerId: record.producerId });
11296
11358
  if (!selections.has(key) || record.instance.outputRef.kind === "session-jsonl") selections.set(key, { kind: "registry", instance: record.instance, record });
11297
11359
  }
@@ -11328,7 +11390,7 @@ async function webuiSubagentsData({ includeSelections = false } = {}) {
11328
11390
  };
11329
11391
  const fleet = tabSummaries.reduce((summary, tab) => ({ version: 1, totalActive: Math.min(Number.MAX_SAFE_INTEGER, summary.totalActive + Number(tab.fleet?.totalActive || 0)), omitted: Math.min(Number.MAX_SAFE_INTEGER, summary.omitted + Number(tab.fleet?.omitted || 0)) }), { version: 1, totalActive: 0, omitted: 0 });
11330
11392
  const overview = {
11331
- version: 2, updatedAt: Date.now(), available: tabSummaries.some((tab) => tab.available) || registrySnapshot.records.length > 0,
11393
+ version: 2, updatedAt: Date.now(), available: tabSummaries.some((tab) => tab.available) || visibleRegistryRecords.length > 0,
11332
11394
  groups, counts, diagnostics: diagnostics.slice(-WEBUI_AGENT_RUN_DIAGNOSTIC_LIMIT), fleet,
11333
11395
  totalRuns: counts.totalRuns, totalAgents: counts.totalAgents,
11334
11396
  runningRuns: groups.reduce((count, group) => count + group.runs.filter((run) => run.status === "running").length, 0),
@@ -11474,6 +11536,8 @@ function normalizeWebuiSubagentOutput(value, selection) {
11474
11536
  recentTools,
11475
11537
  recentOutput,
11476
11538
  transcript,
11539
+ unavailable: rawAgent.unavailable === true || undefined,
11540
+ unavailableReason: rawAgent.unavailable === true ? normalizeWebuiSubagentText(rawAgent.unavailableReason, 1000) || "Live output is unavailable for this agent." : undefined,
11477
11541
  error: normalizeWebuiSubagentText(rawAgent.error, 1000) || undefined,
11478
11542
  },
11479
11543
  };
@@ -12532,7 +12596,7 @@ async function safeRpcResponse(tab, command, timeoutMs = REQUEST_TIMEOUT_MS) {
12532
12596
  if (command?.type === "get_messages" && Array.isArray(response?.data?.messages)) {
12533
12597
  response.data = {
12534
12598
  ...response.data,
12535
- messages: filterSessionSummaryTranscriptMessages(tab.thinkingStreamRecovery.applyToMessages(response.data.messages)),
12599
+ messages: filterSessionSummaryTranscriptMessages(filterIntercomTranscriptMessages(tab.thinkingStreamRecovery.applyToMessages(response.data.messages))),
12536
12600
  };
12537
12601
  }
12538
12602
  return response;
@@ -12612,10 +12676,20 @@ async function sendWebuiHelperCommand(tab, action, payload = {}, timeoutMs = WEB
12612
12676
 
12613
12677
  function requireResourceScope(value) {
12614
12678
  const scope = String(value || "session").trim().toLowerCase();
12615
- if (scope !== "session" && scope !== "global") throw makeHttpError(400, "Resource scope must be session or global");
12679
+ if (scope !== "session" && scope !== "global" && scope !== "model") throw makeHttpError(400, "Resource scope must be session, global, or model");
12616
12680
  return scope;
12617
12681
  }
12618
12682
 
12683
+ function requireResourceModelIdentity(source, models) {
12684
+ const provider = String(source?.provider || "").trim();
12685
+ const modelId = String(source?.modelId || "").trim();
12686
+ if (!provider || !modelId) throw makeHttpError(400, "Model resource scope requires an exact provider and modelId");
12687
+ if (!(models || []).some((model) => model?.provider === provider && model?.id === modelId)) {
12688
+ throw makeHttpError(400, `Unknown authenticated model for resource profile: ${provider}/${modelId}`);
12689
+ }
12690
+ return { provider, modelId };
12691
+ }
12692
+
12619
12693
  function selectedResourceNames(body, enabledKey, disabledKey, resources, label) {
12620
12694
  const allNames = new Set((resources || []).map((resource) => String(resource.name || "").trim()).filter(Boolean));
12621
12695
  if (Array.isArray(body?.[enabledKey])) {
@@ -12628,12 +12702,6 @@ function selectedResourceNames(body, enabledKey, disabledKey, resources, label)
12628
12702
  throw makeHttpError(400, `${label} update requires ${enabledKey} or ${disabledKey}`);
12629
12703
  }
12630
12704
 
12631
- function preserveUnavailableGlobalNames(selectedNames, resources, previousNames) {
12632
- if (!Array.isArray(previousNames)) return selectedNames;
12633
- const available = new Set((resources || []).map((resource) => resource.name));
12634
- return [...new Set([...selectedNames, ...previousNames.filter((name) => !available.has(name))])];
12635
- }
12636
-
12637
12705
  function globalResourcePayload(key, resources, configuredNames) {
12638
12706
  const configured = Array.isArray(configuredNames);
12639
12707
  const enabled = new Set(configured ? configuredNames : resources.filter((resource) => resource.enabled !== false).map((resource) => resource.name));
@@ -12644,10 +12712,73 @@ function globalResourcePayload(key, resources, configuredNames) {
12644
12712
  };
12645
12713
  }
12646
12714
 
12647
- async function getToolConfigData(tab, requestedScope = "session") {
12715
+ async function modelResourcePayload(tab, key, resources, identity, models) {
12716
+ const selectionKey = key === "tools" ? "enabledTools" : "enabledSkills";
12717
+ const defaults = (await readWebuiSettings()).resourceDefaults;
12718
+ const profile = exactModelProfile(defaults, identity.provider, identity.modelId);
12719
+ const configuredNames = profile?.[key]?.[selectionKey];
12720
+ const configured = Array.isArray(configuredNames);
12721
+ const resolved = resolveResourceSelection(defaults, key, identity.provider, identity.modelId, null);
12722
+ const enabledNames = configured
12723
+ ? configuredNames
12724
+ : resolved.names !== null
12725
+ ? resolved.names
12726
+ : resources.filter((resource) => resource.enabled !== false).map((resource) => resource.name);
12727
+ const enabled = new Set(enabledNames);
12728
+ return {
12729
+ scope: "model",
12730
+ provider: identity.provider,
12731
+ modelId: identity.modelId,
12732
+ configured,
12733
+ source: configured ? "model" : resolved.source,
12734
+ models: (models || []).map((model) => ({ provider: model.provider, id: model.id, name: model.name || model.id })),
12735
+ [key]: resources.map((resource) => ({ ...resource, enabled: enabled.has(resource.name) })),
12736
+ };
12737
+ }
12738
+
12739
+ async function recomputeResourceRuntime(tab) {
12740
+ return sendWebuiHelperCommand(tab, "resources-recompute");
12741
+ }
12742
+
12743
+ async function setModelResourceProfile(tab, key, resources, body) {
12744
+ const selectionKey = key === "tools" ? "enabledTools" : "enabledSkills";
12745
+ const label = key === "tools" ? "Tool" : "Skill";
12746
+ const enabledKey = `enabled${label}s`;
12747
+ const disabledKey = `disabled${label}s`;
12748
+ const models = await availableGitWorkflowModels(tab);
12749
+ const identity = requireResourceModelIdentity(body, models);
12750
+ if (body?.inherit === true) {
12751
+ await updateWebuiSettings((current) => ({
12752
+ resourceDefaults: {
12753
+ modelProfiles: setExactModelProfile(current.resourceDefaults, identity.provider, identity.modelId, key, null),
12754
+ },
12755
+ }));
12756
+ const refreshed = await recomputeResourceRuntime(tab);
12757
+ return modelResourcePayload(tab, key, refreshed?.[key]?.[key] || resources, identity, models);
12758
+ }
12759
+ const selectedNames = selectedResourceNames(body, enabledKey, disabledKey, resources, label);
12760
+ await updateWebuiSettings((current) => {
12761
+ const previousNames = exactModelProfile(current.resourceDefaults, identity.provider, identity.modelId)?.[key]?.[selectionKey];
12762
+ const enabledNames = preserveUnavailableResourceNames(previousNames, resources.map((resource) => resource.name), selectedNames);
12763
+ return {
12764
+ resourceDefaults: {
12765
+ modelProfiles: setExactModelProfile(current.resourceDefaults, identity.provider, identity.modelId, key, enabledNames),
12766
+ },
12767
+ };
12768
+ });
12769
+ const refreshed = await recomputeResourceRuntime(tab);
12770
+ return modelResourcePayload(tab, key, refreshed?.[key]?.[key] || resources, identity, models);
12771
+ }
12772
+
12773
+ async function getToolConfigData(tab, requestedScope = "session", searchParams) {
12648
12774
  const scope = requireResourceScope(requestedScope);
12649
12775
  const runtime = await sendWebuiHelperCommand(tab, "tools-state");
12650
12776
  if (scope === "session") return { ...runtime, scope };
12777
+ if (scope === "model") {
12778
+ const models = await availableGitWorkflowModels(tab);
12779
+ const identity = requireResourceModelIdentity({ provider: searchParams?.get("provider"), modelId: searchParams?.get("modelId") }, models);
12780
+ return modelResourcePayload(tab, "tools", runtime.tools || [], identity, models);
12781
+ }
12651
12782
  const defaults = (await readWebuiSettings()).resourceDefaults.tools.enabledTools;
12652
12783
  return globalResourcePayload("tools", runtime.tools || [], defaults);
12653
12784
  }
@@ -12846,26 +12977,44 @@ async function setToolConfigData(tab, body) {
12846
12977
  const scope = requireResourceScope(body?.scope);
12847
12978
  if (scope === "session") {
12848
12979
  return {
12849
- ...(await sendWebuiHelperCommand(tab, "tools-set", {
12850
- enabledTools: Array.isArray(body.enabledTools) ? body.enabledTools : undefined,
12851
- disabledTools: Array.isArray(body.disabledTools) ? body.disabledTools : undefined,
12852
- })),
12980
+ ...(await sendWebuiHelperCommand(tab, "tools-set", body?.inherit === true
12981
+ ? { mode: "inherit" }
12982
+ : {
12983
+ enabledTools: Array.isArray(body.enabledTools) ? body.enabledTools : undefined,
12984
+ disabledTools: Array.isArray(body.disabledTools) ? body.disabledTools : undefined,
12985
+ })),
12853
12986
  scope,
12854
12987
  };
12855
12988
  }
12856
12989
 
12857
12990
  const runtime = await sendWebuiHelperCommand(tab, "tools-state");
12858
- const currentSettings = await readWebuiSettings();
12991
+ if (scope === "model") return setModelResourceProfile(tab, "tools", runtime.tools || [], body);
12992
+ if (body?.inherit === true) {
12993
+ await updateWebuiSettings(() => ({ resourceDefaults: { tools: { enabledTools: null } } }));
12994
+ const refreshed = await recomputeResourceRuntime(tab);
12995
+ return globalResourcePayload("tools", refreshed?.tools?.tools || runtime.tools || [], null);
12996
+ }
12859
12997
  const selectedTools = selectedResourceNames(body, "enabledTools", "disabledTools", runtime.tools, "Tool");
12860
- const enabledTools = preserveUnavailableGlobalNames(selectedTools, runtime.tools, currentSettings.resourceDefaults.tools.enabledTools);
12861
- await writeWebuiSettings({ resourceDefaults: { tools: { enabledTools } } });
12862
- return globalResourcePayload("tools", runtime.tools || [], enabledTools);
12998
+ const settings = await updateWebuiSettings((current) => ({
12999
+ resourceDefaults: {
13000
+ tools: {
13001
+ enabledTools: preserveUnavailableResourceNames(current.resourceDefaults?.tools?.enabledTools, (runtime.tools || []).map((tool) => tool.name), selectedTools),
13002
+ },
13003
+ },
13004
+ }));
13005
+ const refreshed = await recomputeResourceRuntime(tab);
13006
+ return globalResourcePayload("tools", refreshed?.tools?.tools || runtime.tools || [], settings.resourceDefaults.tools.enabledTools);
12863
13007
  }
12864
13008
 
12865
- async function getSkillConfigData(tab, requestedScope = "session") {
13009
+ async function getSkillConfigData(tab, requestedScope = "session", searchParams) {
12866
13010
  const scope = requireResourceScope(requestedScope);
12867
13011
  const runtime = await getSkillConfigDataFromRuntime(tab);
12868
13012
  if (scope === "session") return { ...runtime, scope };
13013
+ if (scope === "model") {
13014
+ const models = await availableGitWorkflowModels(tab);
13015
+ const identity = requireResourceModelIdentity({ provider: searchParams?.get("provider"), modelId: searchParams?.get("modelId") }, models);
13016
+ return modelResourcePayload(tab, "skills", runtime.skills || [], identity, models);
13017
+ }
12869
13018
  const defaults = (await readWebuiSettings()).resourceDefaults.skills.enabledSkills;
12870
13019
  return globalResourcePayload("skills", runtime.skills || [], defaults);
12871
13020
  }
@@ -12878,20 +13027,33 @@ async function setSkillConfigData(tab, body) {
12878
13027
  const scope = requireResourceScope(body?.scope);
12879
13028
  if (scope === "session") {
12880
13029
  return {
12881
- ...(await sendWebuiHelperCommand(tab, "skills-set", {
12882
- enabledSkills: Array.isArray(body.enabledSkills) ? body.enabledSkills : undefined,
12883
- disabledSkills: Array.isArray(body.disabledSkills) ? body.disabledSkills : undefined,
12884
- })),
13030
+ ...(await sendWebuiHelperCommand(tab, "skills-set", body?.inherit === true
13031
+ ? { mode: "inherit" }
13032
+ : {
13033
+ enabledSkills: Array.isArray(body.enabledSkills) ? body.enabledSkills : undefined,
13034
+ disabledSkills: Array.isArray(body.disabledSkills) ? body.disabledSkills : undefined,
13035
+ })),
12885
13036
  scope,
12886
13037
  };
12887
13038
  }
12888
13039
 
12889
13040
  const runtime = await getSkillConfigDataFromRuntime(tab);
12890
- const currentSettings = await readWebuiSettings();
13041
+ if (scope === "model") return setModelResourceProfile(tab, "skills", runtime.skills || [], body);
13042
+ if (body?.inherit === true) {
13043
+ await updateWebuiSettings(() => ({ resourceDefaults: { skills: { enabledSkills: null } } }));
13044
+ const refreshed = await recomputeResourceRuntime(tab);
13045
+ return globalResourcePayload("skills", refreshed?.skills?.skills || runtime.skills || [], null);
13046
+ }
12891
13047
  const selectedSkills = selectedResourceNames(body, "enabledSkills", "disabledSkills", runtime.skills, "Skill");
12892
- const enabledSkills = preserveUnavailableGlobalNames(selectedSkills, runtime.skills, currentSettings.resourceDefaults.skills.enabledSkills);
12893
- await writeWebuiSettings({ resourceDefaults: { skills: { enabledSkills } } });
12894
- return globalResourcePayload("skills", runtime.skills || [], enabledSkills);
13048
+ const settings = await updateWebuiSettings((current) => ({
13049
+ resourceDefaults: {
13050
+ skills: {
13051
+ enabledSkills: preserveUnavailableResourceNames(current.resourceDefaults?.skills?.enabledSkills, (runtime.skills || []).map((skill) => skill.name), selectedSkills),
13052
+ },
13053
+ },
13054
+ }));
13055
+ const refreshed = await recomputeResourceRuntime(tab);
13056
+ return globalResourcePayload("skills", refreshed?.skills?.skills || runtime.skills || [], settings.resourceDefaults.skills.enabledSkills);
12895
13057
  }
12896
13058
 
12897
13059
  function settingsManagerForTab(tab) {
@@ -13624,6 +13786,10 @@ function fileViewerLanguage(filePath) {
13624
13786
  return "text";
13625
13787
  }
13626
13788
 
13789
+ function fileViewerImageMimeType(filePath) {
13790
+ return FILE_VIEWER_IMAGE_MIME_TYPES_BY_EXTENSION[path.extname(String(filePath || "")).toLowerCase()] || "";
13791
+ }
13792
+
13627
13793
  function fileTreeEntryType(dirent, info) {
13628
13794
  if (info?.isDirectory?.() || dirent?.isDirectory?.()) return "directory";
13629
13795
  if (info?.isFile?.() || dirent?.isFile?.()) return "file";
@@ -13792,7 +13958,7 @@ async function getFileSearchData(tab, rawQuery = "") {
13792
13958
  }
13793
13959
 
13794
13960
  function assertTextFileBuffer(buffer) {
13795
- if (isLikelyBinaryBuffer(buffer)) throw makeHttpError(415, "File appears to be binary; only text files can be opened in WebUI");
13961
+ if (isLikelyBinaryBuffer(buffer)) throw makeHttpError(415, "File appears to be binary; only text files and supported raster images can be opened in WebUI");
13796
13962
  }
13797
13963
 
13798
13964
  async function getFileContentData(tab, requestedPath = "") {
@@ -13800,17 +13966,21 @@ async function getFileContentData(tab, requestedPath = "") {
13800
13966
  if (!resolved.info?.isFile()) throw makeHttpError(400, "Path is not a regular file");
13801
13967
  if (resolved.info.size > FILE_VIEWER_MAX_BYTES) throw makeHttpError(413, `File is too large to open in WebUI (limit ${formatBytes(FILE_VIEWER_MAX_BYTES)})`);
13802
13968
  const buffer = await readFile(resolved.targetPath);
13803
- assertTextFileBuffer(buffer);
13804
- return {
13969
+ const extension = path.extname(resolved.targetPath).toLowerCase();
13970
+ const imageMimeType = fileViewerImageMimeType(resolved.targetPath);
13971
+ const shared = {
13805
13972
  root: resolved.root,
13806
13973
  path: resolved.relative,
13807
13974
  name: path.basename(resolved.targetPath),
13808
- content: buffer.toString("utf8"),
13809
13975
  size: resolved.info.size,
13810
13976
  mtimeMs: resolved.info.mtimeMs,
13811
- extension: path.extname(resolved.targetPath).toLowerCase(),
13812
- language: fileViewerLanguage(resolved.targetPath),
13977
+ extension,
13813
13978
  };
13979
+ if (imageMimeType) {
13980
+ return { ...shared, kind: "image", mimeType: imageMimeType, data: buffer.toString("base64") };
13981
+ }
13982
+ assertTextFileBuffer(buffer);
13983
+ return { ...shared, kind: "text", content: buffer.toString("utf8"), language: fileViewerLanguage(resolved.targetPath) };
13814
13984
  }
13815
13985
 
13816
13986
  function aurReviewReportPathSegments(value = "") {
@@ -14141,6 +14311,45 @@ async function getSessionSelectorData(tab, scope = "current") {
14141
14311
  };
14142
14312
  }
14143
14313
 
14314
+ function requestedIntercomConversationId(url) {
14315
+ const value = String(url.searchParams.get("conversation") || "").trim();
14316
+ if (!value) return "";
14317
+ if (!/^conv_[A-Za-z0-9_-]{24}$/.test(value)) throw makeHttpError(400, "conversation must be an opaque Intercom conversation ID");
14318
+ return value;
14319
+ }
14320
+
14321
+ async function getIntercomConversationsData(tab, conversationId = "") {
14322
+ const state = await currentSessionState(tab).catch(() => tab.lastState || {});
14323
+ const sessionFile = sessionFileFromState(state) || tabRestorableSessionFile(tab);
14324
+ const projectionOptions = {
14325
+ conversationId,
14326
+ localSessionId: normalizedRestoreString(state.sessionId, 240) || "local",
14327
+ localName: normalizedRestoreString(state.sessionName, 160) || tab.title || "Local agent",
14328
+ };
14329
+ if (options.noSession || !sessionFile) {
14330
+ const empty = projectIntercomConversations([], projectionOptions);
14331
+ if (conversationId) throw makeHttpError(404, "Intercom conversation not found");
14332
+ return empty;
14333
+ }
14334
+
14335
+ requireAllowedSessionPath(sessionFile);
14336
+ const sessionInfo = await stat(sessionFile).catch(() => null);
14337
+ if (!sessionInfo?.isFile()) throw makeHttpError(404, "Persisted session is unavailable");
14338
+
14339
+ let manager;
14340
+ try {
14341
+ manager = SessionManager.open(sessionFile, configuredSessionDir(), tab.cwd);
14342
+ } catch {
14343
+ throw makeHttpError(400, "Persisted session could not be read");
14344
+ }
14345
+ const data = projectIntercomConversations(manager.getBranch(), {
14346
+ ...projectionOptions,
14347
+ localSessionId: normalizedRestoreString(manager.getSessionId(), 240) || projectionOptions.localSessionId,
14348
+ });
14349
+ if (conversationId && !data.conversation) throw makeHttpError(404, "Intercom conversation not found");
14350
+ return data;
14351
+ }
14352
+
14144
14353
  function extractSessionTextContent(content) {
14145
14354
  if (typeof content === "string") return content;
14146
14355
  if (!Array.isArray(content)) return "";
@@ -14269,6 +14478,7 @@ function sessionTreeEntryLabel(entry) {
14269
14478
  function sessionTreeEntryText(entry) {
14270
14479
  if (!entry || typeof entry !== "object") return "";
14271
14480
  if (entry.type === "message") return extractSessionTextContent(entry.message?.content);
14481
+ if (entry.type === "custom_message" && entry.customType === "intercom_message") return "Intercom message";
14272
14482
  if (entry.type === "custom_message") return extractSessionTextContent(entry.content);
14273
14483
  if (entry.type === "branch_summary") return entry.summary || "branch summary";
14274
14484
  if (entry.type === "compaction") return entry.summary || "compaction summary";
@@ -16336,6 +16546,13 @@ const server = createServer(async (req, res) => {
16336
16546
  return;
16337
16547
  }
16338
16548
 
16549
+ if (url.pathname === "/api/intercom/conversations" && req.method === "GET") {
16550
+ if (!requestedTabId(req, url)) throw makeHttpError(400, "tab is required");
16551
+ const tab = getRequestedTab(req, url);
16552
+ sendJson(res, 200, { ok: true, data: await getIntercomConversationsData(tab, requestedIntercomConversationId(url)) }, { "cache-control": "private, no-store" });
16553
+ return;
16554
+ }
16555
+
16339
16556
  if (url.pathname === "/api/sessions" && req.method === "GET") {
16340
16557
  const tab = getRequestedTab(req, url);
16341
16558
  sendJson(res, 200, { ok: true, data: await getSessionSelectorData(tab, url.searchParams.get("scope") || "current") });
@@ -16540,7 +16757,7 @@ const server = createServer(async (req, res) => {
16540
16757
 
16541
16758
  if (url.pathname === "/api/tools" && req.method === "GET") {
16542
16759
  const tab = getRequestedTab(req, url);
16543
- sendJson(res, 200, { ok: true, data: await getToolConfigData(tab, url.searchParams.get("scope")) });
16760
+ sendJson(res, 200, { ok: true, data: await getToolConfigData(tab, url.searchParams.get("scope"), url.searchParams) });
16544
16761
  return;
16545
16762
  }
16546
16763
 
@@ -16554,7 +16771,7 @@ const server = createServer(async (req, res) => {
16554
16771
 
16555
16772
  if (url.pathname === "/api/skills" && req.method === "GET") {
16556
16773
  const tab = getRequestedTab(req, url);
16557
- sendJson(res, 200, { ok: true, data: await getSkillConfigData(tab, url.searchParams.get("scope")) });
16774
+ sendJson(res, 200, { ok: true, data: await getSkillConfigData(tab, url.searchParams.get("scope"), url.searchParams) });
16558
16775
  return;
16559
16776
  }
16560
16777