@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/public/app.js CHANGED
@@ -9,8 +9,9 @@ import { buildIssuePayload, createIssueWizardCatalog, createIssueWizardState, ge
9
9
  import { createIssueBotClient, readIssueBotRuntimeConfig } from "./issue-bot-client.mjs";
10
10
  import { MOBILE_SHELL_STORAGE_KEY, TABLET_SHELL_STORAGE_KEY, createMobileShellState, isMobileShellV2Enabled, mobileNavigationTargetFromSearch, normalizeMobileNavigationTarget, reduceMobileShellState, resolveMobileShellFeatureMode, resolveTabletShellFeatureMode } from "./mobile-shell-state.mjs";
11
11
  import { createTranscriptRenderer } from "./transcript-renderer.mjs";
12
- import { classifyTranscriptStreamEvent, createStreamOutputController } from "./stream-output-controller.mjs";
12
+ import { classifyTranscriptStreamEvent, createStreamOutputController, reconcileTranscriptThinkingSnapshot } from "./stream-output-controller.mjs";
13
13
  import { installMiddleButtonDragScroll } from "./middle-button-drag-scroll.mjs";
14
+ import { tokenizeCode } from "./syntax-highlight.mjs";
14
15
  import { PI_THEME_EXPORT_FIELDS, THEME_TOKEN_GROUPS, canonicalizeTheme, serializeTheme, themeColorToRgb, validateTheme } from "./theme-contract.mjs";
15
16
  import {
16
17
  SAMPLING_PARAMETER_CATALOG,
@@ -57,6 +58,8 @@ const elements = {
57
58
  contextMeterBar: $("#contextMeterBar"),
58
59
  serverOfflinePanel: $("#serverOfflinePanel"),
59
60
  serverRestartPanel: $("#serverRestartPanel"),
61
+ serverRestartKicker: $("#serverRestartKicker"),
62
+ serverRestartTitle: $("#serverRestartTitle"),
60
63
  serverRestartMessage: $("#serverRestartMessage"),
61
64
  updateNotification: $("#updateNotification"),
62
65
  updateNotificationTitle: $("#updateNotificationTitle"),
@@ -94,6 +97,7 @@ const elements = {
94
97
  subagentCancelSubmitButton: $("#subagentCancelSubmitButton"),
95
98
  stickyUserPromptButton: $("#stickyUserPromptButton"),
96
99
  chat: $("#chat"),
100
+ mainOutputLoading: $("#mainOutputLoading"),
97
101
  runIndicatorHost: $("#runIndicatorHost"),
98
102
  chatSearchBar: $("#chatSearchBar"),
99
103
  chatSearchInput: $("#chatSearchInput"),
@@ -127,6 +131,13 @@ const elements = {
127
131
  busyPromptBehaviorTag: $("#busyPromptBehaviorTag"),
128
132
  busyPromptBehaviorMenu: $("#busyPromptBehaviorMenu"),
129
133
  sessionSkillTags: $("#sessionSkillTags"),
134
+ intercomConversationTags: $("#intercomConversationTags"),
135
+ intercomConversationDialog: $("#intercomConversationDialog"),
136
+ intercomConversationTitle: $("#intercomConversationTitle"),
137
+ intercomConversationParticipants: $("#intercomConversationParticipants"),
138
+ intercomConversationTranscript: $("#intercomConversationTranscript"),
139
+ intercomConversationStatus: $("#intercomConversationStatus"),
140
+ intercomConversationCloseButton: $("#intercomConversationCloseButton"),
130
141
  featureCategoryTag: $("#featureCategoryTag"),
131
142
  featureDecisionDialog: $("#featureDecisionDialog"),
132
143
  featureDecisionDialogOutput: $("#featureDecisionDialogOutput"),
@@ -189,6 +200,8 @@ const elements = {
189
200
  optionsWorkflowSetupButton: $("#optionsWorkflowSetupButton"),
190
201
  optionsSafetyGuardSetupButton: $("#optionsSafetyGuardSetupButton"),
191
202
  optionsGitWorkflowSetupButton: $("#optionsGitWorkflowSetupButton"),
203
+ optionsToolsSetupButton: $("#optionsToolsSetupButton"),
204
+ optionsSkillsSetupButton: $("#optionsSkillsSetupButton"),
192
205
  optionsExportButton: $("#optionsExportButton"),
193
206
  optionsForkButton: $("#optionsForkButton"),
194
207
  optionsTreeButton: $("#optionsTreeButton"),
@@ -321,6 +334,8 @@ const elements = {
321
334
  fileViewerEditor: $("#fileViewerEditor"),
322
335
  fileViewerSearchOverlay: $("#fileViewerSearchOverlay"),
323
336
  fileViewerPreview: $("#fileViewerPreview"),
337
+ fileViewerImage: $("#fileViewerImage"),
338
+ fileViewerImageElement: $("#fileViewerImageElement"),
324
339
  fileViewerChanges: $("#fileViewerChanges"),
325
340
  fileViewerStatus: $("#fileViewerStatus"),
326
341
  fileViewerSearchBar: $("#fileViewerSearchBar"),
@@ -572,6 +587,12 @@ let tabWorkspaceCache = new Map();
572
587
  let tabs = [];
573
588
  let activeTabId = null;
574
589
  let activeTabGeneration = 0;
590
+ const intercomConversationSummariesByTab = new Map();
591
+ let intercomSummaryRequestSerial = 0;
592
+ let intercomSummaryRefreshTimer = null;
593
+ let intercomDetailRequestSerial = 0;
594
+ let intercomDetailRefreshTimer = null;
595
+ let intercomConversationDialogState = null;
575
596
  let tabDrafts = new Map();
576
597
  let tabAttachments = new Map();
577
598
  let activeTextAttachmentEditor = null;
@@ -722,9 +743,17 @@ const streamOutputController = createStreamOutputController({
722
743
  isOwnerCurrent: (owner) => owner === transcriptStreamOwner(),
723
744
  applyTextUpdate: (event) => handleMessageUpdate(event),
724
745
  applyThinkingUpdate: (event) => handleMessageUpdate(event),
725
- applyToolCallUpdate: (event) => handleMessageUpdate(event),
746
+ applyToolCallUpdate: (event) => {
747
+ if (isIntercomToolCallUpdate(event)) {
748
+ streamToolCallSeen = true;
749
+ suppressStreamingAssistantTextBeforeToolCall();
750
+ resetStreamingToolCallState({ remove: true });
751
+ return;
752
+ }
753
+ handleMessageUpdate(event);
754
+ },
726
755
  applyToolExecutionUpdate: (event) => {
727
- if (!compactOutputActive()) applyTranscriptToolExecutionUpdate(event);
756
+ if (!compactOutputActive() && !isIntercomTransportToolName(event?.toolName)) applyTranscriptToolExecutionUpdate(event);
728
757
  },
729
758
  applyStreamError: (event) => handleMessageUpdate(event),
730
759
  applyFollowScroll: () => {
@@ -773,6 +802,9 @@ let runIndicatorActivity = "Waiting for output or action…";
773
802
  let refreshMessagesTimer = null;
774
803
  let refreshStateTimer = null;
775
804
  let refreshFooterTimer = null;
805
+ const mainOutputLoadingRequests = new Set();
806
+ let mainOutputLoadingRevealTimer = null;
807
+ const MAIN_OUTPUT_LOADING_REVEAL_DELAY_MS = 120;
776
808
  let refreshTabsTimer = null;
777
809
  let tabsRenderFrame = null;
778
810
  let foregroundReconcileTimer = null;
@@ -925,6 +957,7 @@ let subagentsClearingFinished = false;
925
957
  let subagentAutoClearEnabled = false;
926
958
  let refreshSubagentsTimer = null;
927
959
  const dismissedSubagentGateKeys = new Set();
960
+ const collapsedSubagentWorkflowRunKeys = new Set();
928
961
  let subagentOverlaySelection = null;
929
962
  let subagentOverlayData = null;
930
963
  let subagentOverlayError = "";
@@ -1189,6 +1222,7 @@ const WORKFLOW_WIDGET_PAYLOAD_PREFIX = "WORKFLOW_WEBUI_PAYLOAD ";
1189
1222
  const WORKFLOW_SUBPROCESS_PAYLOAD_TYPE = "firstpick.pi-extension-workflows.subprocess";
1190
1223
  const WORKFLOW_SUBPROCESS_PAYLOAD_VERSION = 1;
1191
1224
  const WORKFLOW_INSPECTOR_WIDGET_KEY = "workflow:rpc";
1225
+ const SUBAGENT_ASYNC_WIDGET_KEY = "subagent-async";
1192
1226
  const WORKFLOW_INSPECTOR_PAYLOAD_PREFIX = "WORKFLOW_RPC_PAYLOAD ";
1193
1227
  const WORKFLOW_INSPECTOR_PAYLOAD_TYPE = "firstpick.pi-extension-workflows.inspector";
1194
1228
  const WORKFLOW_INSPECTOR_PAYLOAD_VERSION = 1;
@@ -2552,6 +2586,7 @@ const OPTIONAL_FEATURES = [
2552
2586
  packageName: "@firstpick/pi-extension-setup-skills",
2553
2587
  capabilityLabel: "RPC /skills from setup-skills extension",
2554
2588
  description: "Terminal-native skill setup command alongside WebUI-native /skills toggles.",
2589
+ setup: "skills",
2555
2590
  },
2556
2591
  {
2557
2592
  id: "todoProgressWidget",
@@ -2566,6 +2601,7 @@ const OPTIONAL_FEATURES = [
2566
2601
  packageName: "@firstpick/pi-extension-tools",
2567
2602
  capabilityLabel: "RPC /tools from tools extension",
2568
2603
  description: "Terminal-native active-tool manager alongside WebUI-native /tools toggles.",
2604
+ setup: "tools",
2569
2605
  },
2570
2606
  {
2571
2607
  id: "remoteWebui",
@@ -2581,7 +2617,6 @@ const OPTIONAL_FEATURES = [
2581
2617
  capabilityLabel: "questionnaire tool in /tools",
2582
2618
  description: "Native TUI and WebUI single- or multi-select question series with Other answers and resumable clarification.",
2583
2619
  manageWith: "tools",
2584
- setup: "tools",
2585
2620
  },
2586
2621
  {
2587
2622
  id: "naturalConversation",
@@ -5728,7 +5763,7 @@ function bindTerminalTabDragAndDrop(element, { sourceTabId = "", target = null }
5728
5763
  element.draggable = true;
5729
5764
  element.dataset.dragTabId = sourceTabId;
5730
5765
  element.addEventListener("dragstart", (event) => {
5731
- if (event.target?.closest?.(".terminal-tab-close, .terminal-tab-actions, .terminal-tab-group-add")) {
5766
+ if (event.target?.closest?.(".terminal-tab-close, .terminal-tab-actions, .terminal-tab-cwd-add, .terminal-tab-group-add")) {
5732
5767
  event.preventDefault();
5733
5768
  return;
5734
5769
  }
@@ -6010,13 +6045,35 @@ function skillKindsLabel(entry) {
6010
6045
 
6011
6046
  let sessionSkillTagLayoutFrame = 0;
6012
6047
  let sessionSkillTagResizeObserver = null;
6048
+ let sessionSkillOverflowOpen = false;
6049
+
6050
+ function setSessionSkillOverflowOpen(open, { focusMenu = false, restoreFocus = false } = {}) {
6051
+ const container = elements.sessionSkillTags;
6052
+ const overflow = container?.querySelector("button.composer-skill-tag.overflow");
6053
+ const menu = container?.querySelector(".composer-skill-overflow-menu");
6054
+ if (!container || !overflow || !menu) {
6055
+ sessionSkillOverflowOpen = false;
6056
+ return;
6057
+ }
6058
+
6059
+ const availableItems = [...menu.querySelectorAll("button:not([hidden])")];
6060
+ const expanded = Boolean(open && !overflow.hidden && availableItems.length);
6061
+ sessionSkillOverflowOpen = expanded;
6062
+ container.classList.toggle("overflow-open", expanded);
6063
+ overflow.setAttribute("aria-expanded", expanded ? "true" : "false");
6064
+ menu.hidden = !expanded;
6065
+
6066
+ if (expanded && focusMenu) availableItems[0]?.focus();
6067
+ else if (!expanded && restoreFocus) overflow.focus();
6068
+ }
6013
6069
 
6014
6070
  function fitSessionSkillTags() {
6015
6071
  const container = elements.sessionSkillTags;
6016
6072
  if (!container || container.hidden) return;
6017
- const tags = [...container.querySelectorAll("button.composer-skill-tag")];
6018
- const overflow = container.querySelector(".composer-skill-tag.overflow");
6019
- if (!tags.length || !overflow) return;
6073
+ const tags = [...container.querySelectorAll(":scope > button.composer-skill-tag:not(.overflow)")];
6074
+ const overflow = container.querySelector("button.composer-skill-tag.overflow");
6075
+ const menuItems = [...container.querySelectorAll(".composer-skill-overflow-menu-item")];
6076
+ if (!tags.length || !overflow || menuItems.length !== tags.length) return;
6020
6077
 
6021
6078
  const availableWidth = container.clientWidth;
6022
6079
  if (availableWidth <= 0) return;
@@ -6048,11 +6105,17 @@ function fitSessionSkillTags() {
6048
6105
  }
6049
6106
 
6050
6107
  tags.forEach((tag, index) => { tag.hidden = index >= visibleCount; });
6108
+ menuItems.forEach((item, index) => { item.hidden = index < visibleCount; });
6051
6109
  const hiddenCount = tags.length - visibleCount;
6052
6110
  overflow.hidden = hiddenCount === 0;
6053
6111
  if (hiddenCount) {
6112
+ const label = `Show ${hiddenCount} more tracked skill${hiddenCount === 1 ? "" : "s"}`;
6054
6113
  overflow.textContent = `+${hiddenCount}`;
6055
- overflow.title = `${hiddenCount} more tracked skill${hiddenCount === 1 ? "" : "s"}.`;
6114
+ overflow.title = `${label}.`;
6115
+ overflow.setAttribute("aria-label", label);
6116
+ if (sessionSkillOverflowOpen) setSessionSkillOverflowOpen(true);
6117
+ } else {
6118
+ setSessionSkillOverflowOpen(false);
6056
6119
  }
6057
6120
  }
6058
6121
 
@@ -6074,12 +6137,28 @@ function installSessionSkillTagResizeHandling() {
6074
6137
  } else {
6075
6138
  window.addEventListener("resize", scheduleSessionSkillTagLayout, { passive: true });
6076
6139
  }
6140
+ container.addEventListener("keydown", (event) => {
6141
+ if (event.key !== "Escape" || !sessionSkillOverflowOpen) return;
6142
+ event.preventDefault();
6143
+ event.stopPropagation();
6144
+ setSessionSkillOverflowOpen(false, { restoreFocus: true });
6145
+ });
6146
+ container.addEventListener("focusout", () => {
6147
+ queueMicrotask(() => {
6148
+ if (sessionSkillOverflowOpen && !container.contains(document.activeElement)) setSessionSkillOverflowOpen(false);
6149
+ });
6150
+ });
6151
+ document.addEventListener("pointerdown", (event) => {
6152
+ if (sessionSkillOverflowOpen && !container.contains(event.target)) setSessionSkillOverflowOpen(false);
6153
+ });
6077
6154
  }
6078
6155
 
6079
6156
  function renderSessionSkillTags(tabId = activeTabId) {
6080
6157
  const container = elements.sessionSkillTags;
6081
6158
  if (!container) return;
6082
6159
  const entries = sortedSkillUsageEntries(tabId).filter((entry) => entry.kinds.has("read"));
6160
+ sessionSkillOverflowOpen = false;
6161
+ container.classList.remove("overflow-open");
6083
6162
  container.replaceChildren();
6084
6163
  if (!entries.length) {
6085
6164
  container.hidden = true;
@@ -6096,13 +6175,370 @@ function renderSessionSkillTags(tabId = activeTabId) {
6096
6175
  tag.addEventListener("click", () => openSkillEditor(entry));
6097
6176
  container.append(tag);
6098
6177
  }
6099
- const overflow = make("span", "composer-skill-tag overflow", `+${entries.length}`);
6178
+ const overflow = make("button", "composer-skill-tag overflow", `+${entries.length}`);
6179
+ overflow.type = "button";
6100
6180
  overflow.hidden = true;
6181
+ overflow.setAttribute("aria-haspopup", "dialog");
6182
+ overflow.setAttribute("aria-expanded", "false");
6183
+ overflow.setAttribute("aria-controls", "sessionSkillOverflowMenu");
6184
+ overflow.addEventListener("click", () => {
6185
+ const opening = !sessionSkillOverflowOpen;
6186
+ setSessionSkillOverflowOpen(opening, { focusMenu: opening });
6187
+ });
6101
6188
  container.append(overflow);
6189
+
6190
+ const menu = make("div", "composer-skill-overflow-menu");
6191
+ menu.id = "sessionSkillOverflowMenu";
6192
+ menu.hidden = true;
6193
+ menu.setAttribute("role", "dialog");
6194
+ menu.setAttribute("aria-label", "More tracked skills");
6195
+ for (const entry of entries) {
6196
+ const item = make("button", "composer-skill-tag read composer-skill-overflow-menu-item", entry.name);
6197
+ item.type = "button";
6198
+ item.dataset.skillName = entry.name;
6199
+ item.dataset.skillPath = skillPathForEntry(entry);
6200
+ item.title = `Open and edit skill ${entry.name} (${skillKindsLabel(entry)}) tracked in this tab/session.`;
6201
+ item.setAttribute("aria-label", `Open skill ${entry.name}`);
6202
+ item.addEventListener("click", () => {
6203
+ setSessionSkillOverflowOpen(false);
6204
+ openSkillEditor(entry);
6205
+ });
6206
+ menu.append(item);
6207
+ }
6208
+ container.append(menu);
6102
6209
  container.hidden = false;
6103
6210
  scheduleSessionSkillTagLayout();
6104
6211
  }
6105
6212
 
6213
+ const INTERCOM_CONVERSATION_ID_PATTERN = /^conv_[A-Za-z0-9_-]{24}$/;
6214
+ const INTERCOM_MESSAGE_ID_PATTERN = /^msg_[A-Za-z0-9_-]{24}$/;
6215
+ const INTERCOM_DETAIL_REFRESH_MS = 5_000;
6216
+ const intercomMessageRenderSignatures = new WeakMap();
6217
+
6218
+ function intercomBoundedString(value, maxLength = 240) {
6219
+ if (typeof value !== "string") return "";
6220
+ return value.trim().slice(0, maxLength);
6221
+ }
6222
+
6223
+ function normalizeIntercomParticipant(value, fallback) {
6224
+ const participant = value && typeof value === "object" && !Array.isArray(value) ? value : {};
6225
+ const id = intercomBoundedString(participant.id, 240);
6226
+ const name = intercomBoundedString(participant.name, 160);
6227
+ return { id: id || null, name: name || id || fallback };
6228
+ }
6229
+
6230
+ function intercomParticipantLabel(participant, fallback = "Agent") {
6231
+ const normalized = normalizeIntercomParticipant(participant, fallback);
6232
+ return normalized.id && normalized.id !== normalized.name ? `${normalized.name} (${normalized.id})` : normalized.name;
6233
+ }
6234
+
6235
+ function normalizeIntercomConversationSummary(value) {
6236
+ if (!value || typeof value !== "object" || !INTERCOM_CONVERSATION_ID_PATTERN.test(String(value.id || ""))) return null;
6237
+ const participants = value.participants && typeof value.participants === "object" ? value.participants : {};
6238
+ const messageCount = Number(value.messageCount);
6239
+ return {
6240
+ id: String(value.id),
6241
+ participants: {
6242
+ local: normalizeIntercomParticipant(participants.local, "Local agent"),
6243
+ peer: normalizeIntercomParticipant(participants.peer, "Peer agent"),
6244
+ },
6245
+ messageCount: Number.isSafeInteger(messageCount) && messageCount >= 0 ? messageCount : 0,
6246
+ lastMessageAt: typeof value.lastMessageAt === "string" ? value.lastMessageAt : null,
6247
+ truncatedBefore: value.truncatedBefore === true,
6248
+ };
6249
+ }
6250
+
6251
+ function normalizeIntercomConversationDetail(value) {
6252
+ const summary = normalizeIntercomConversationSummary(value);
6253
+ if (!summary) return null;
6254
+ const messages = [];
6255
+ const seenMessageIds = new Set();
6256
+ for (const candidate of Array.isArray(value.messages) ? value.messages.slice(-200) : []) {
6257
+ const id = String(candidate?.id || "");
6258
+ if (!candidate || typeof candidate !== "object" || !INTERCOM_MESSAGE_ID_PATTERN.test(id) || seenMessageIds.has(id)
6259
+ || !["local", "peer"].includes(candidate.direction) || typeof candidate.text !== "string") continue;
6260
+ seenMessageIds.add(id);
6261
+ const timestamp = typeof candidate.timestamp === "string" && Number.isFinite(Date.parse(candidate.timestamp)) ? candidate.timestamp : null;
6262
+ messages.push({
6263
+ id,
6264
+ direction: candidate.direction,
6265
+ text: candidate.text.slice(0, 65_536),
6266
+ timestamp,
6267
+ truncatedText: candidate.truncatedText === true,
6268
+ });
6269
+ }
6270
+ return { ...summary, messages };
6271
+ }
6272
+
6273
+ function intercomConversationLabel(conversation) {
6274
+ const local = intercomParticipantLabel(conversation?.participants?.local, "Local agent");
6275
+ const peer = intercomParticipantLabel(conversation?.participants?.peer, "Peer agent");
6276
+ return `${local} ↔ ${peer}`;
6277
+ }
6278
+
6279
+ function intercomConversationSummarySignature(conversations) {
6280
+ return JSON.stringify((conversations || []).map((conversation) => [
6281
+ conversation.id,
6282
+ intercomConversationLabel(conversation),
6283
+ conversation.messageCount,
6284
+ conversation.lastMessageAt,
6285
+ conversation.truncatedBefore,
6286
+ ]));
6287
+ }
6288
+
6289
+ function renderIntercomConversationTags(tabId = activeTabId) {
6290
+ const container = elements.intercomConversationTags;
6291
+ if (!container) return;
6292
+ const conversations = intercomConversationSummariesByTab.get(tabId) || [];
6293
+ const existingTags = new Map([...container.querySelectorAll(".composer-intercom-tag[data-intercom-conversation-id]")]
6294
+ .map((tag) => [tag.dataset.intercomConversationId, tag]));
6295
+ const orderedTags = [];
6296
+ const seenConversationIds = new Set();
6297
+ for (const conversation of conversations) {
6298
+ if (seenConversationIds.has(conversation.id)) continue;
6299
+ seenConversationIds.add(conversation.id);
6300
+ const label = intercomConversationLabel(conversation);
6301
+ let tag = existingTags.get(conversation.id);
6302
+ if (tag) existingTags.delete(conversation.id);
6303
+ else {
6304
+ tag = make("button", "composer-intercom-tag");
6305
+ tag.type = "button";
6306
+ tag.dataset.intercomConversationId = conversation.id;
6307
+ tag.setAttribute("aria-haspopup", "dialog");
6308
+ tag.setAttribute("aria-controls", "intercomConversationDialog");
6309
+ tag.addEventListener("click", () => openIntercomConversation(tag.dataset.intercomConversationId));
6310
+ }
6311
+ tag.setAttribute("aria-label", `Open agent conversation ${label}`);
6312
+ tag.title = `${label} · ${conversation.messageCount} message${conversation.messageCount === 1 ? "" : "s"}`;
6313
+ const visualSignature = JSON.stringify([label, conversation.messageCount]);
6314
+ if (tag.dataset.intercomVisualSignature !== visualSignature) {
6315
+ const children = [make("span", "composer-intercom-tag-icon", "↔"), make("span", "composer-intercom-tag-label", label)];
6316
+ if (conversation.messageCount > 0) children.push(make("span", "composer-intercom-tag-count", String(conversation.messageCount)));
6317
+ tag.replaceChildren(...children);
6318
+ tag.dataset.intercomVisualSignature = visualSignature;
6319
+ }
6320
+ orderedTags.push(tag);
6321
+ }
6322
+ container.classList.toggle("dense", orderedTags.length > 8);
6323
+ for (const staleTag of existingTags.values()) staleTag.remove();
6324
+ const currentTags = [...container.querySelectorAll(":scope > .composer-intercom-tag")];
6325
+ if (currentTags.length !== orderedTags.length || orderedTags.some((tag, index) => currentTags[index] !== tag)) {
6326
+ for (const tag of orderedTags) container.append(tag);
6327
+ }
6328
+ container.hidden = orderedTags.length === 0;
6329
+ }
6330
+
6331
+ async function refreshIntercomConversationSummaries(tabContext = activeTabContext()) {
6332
+ if (!tabContext.tabId) return;
6333
+ const requestSerial = ++intercomSummaryRequestSerial;
6334
+ const response = await api("/api/intercom/conversations", { tabId: tabContext.tabId });
6335
+ if (requestSerial !== intercomSummaryRequestSerial || !isCurrentTabContext(tabContext)) return;
6336
+ const seenConversationIds = new Set();
6337
+ const conversations = [];
6338
+ for (const value of Array.isArray(response.data?.conversations) ? response.data.conversations : []) {
6339
+ const conversation = normalizeIntercomConversationSummary(value);
6340
+ if (!conversation || seenConversationIds.has(conversation.id)) continue;
6341
+ seenConversationIds.add(conversation.id);
6342
+ conversations.push(conversation);
6343
+ }
6344
+ const previous = intercomConversationSummariesByTab.get(tabContext.tabId) || [];
6345
+ intercomConversationSummariesByTab.set(tabContext.tabId, conversations);
6346
+ if (intercomConversationSummarySignature(previous) !== intercomConversationSummarySignature(conversations) && !elements.intercomConversationDialog?.open) {
6347
+ renderIntercomConversationTags(tabContext.tabId);
6348
+ }
6349
+ if (intercomConversationDialogState?.tabId === tabContext.tabId && !seenConversationIds.has(intercomConversationDialogState.conversationId)) {
6350
+ closeIntercomConversationDialog({ restoreFocus: false });
6351
+ }
6352
+ }
6353
+
6354
+ function scheduleIntercomConversationRefresh(tabContext = activeTabContext(), delayMs = 180) {
6355
+ clearTimeout(intercomSummaryRefreshTimer);
6356
+ const scheduledContext = { ...tabContext };
6357
+ intercomSummaryRefreshTimer = setTimeout(() => {
6358
+ intercomSummaryRefreshTimer = null;
6359
+ if (!isCurrentTabContext(scheduledContext)) return;
6360
+ refreshIntercomConversationSummaries(scheduledContext).catch((error) => {
6361
+ if (isCurrentTabContext(scheduledContext)) addEvent(`agent conversation refresh failed: ${error.message || String(error)}`, "warn");
6362
+ });
6363
+ }, delayMs);
6364
+ }
6365
+
6366
+ function setIntercomConversationStatus(message = "", level = "") {
6367
+ const status = elements.intercomConversationStatus;
6368
+ if (!status) return;
6369
+ status.textContent = message;
6370
+ status.classList.toggle("error", level === "error");
6371
+ status.classList.toggle("warn", level === "warn");
6372
+ }
6373
+
6374
+ function formatIntercomMessageTime(value) {
6375
+ const timestamp = Date.parse(value || "");
6376
+ if (!Number.isFinite(timestamp)) return "";
6377
+ return new Date(timestamp).toLocaleString([], { dateStyle: "medium", timeStyle: "short" });
6378
+ }
6379
+
6380
+ function renderIntercomConversationMessage(article, message, conversation) {
6381
+ const participant = message.direction === "local" ? conversation.participants.local : conversation.participants.peer;
6382
+ const senderLabel = intercomParticipantLabel(participant, message.direction === "local" ? "Local agent" : "Peer agent");
6383
+ const formattedTime = formatIntercomMessageTime(message.timestamp);
6384
+ const signature = JSON.stringify([message.direction, senderLabel, message.text, message.timestamp, message.truncatedText]);
6385
+ if (intercomMessageRenderSignatures.get(article) === signature) return;
6386
+
6387
+ article.className = `intercom-conversation-message ${message.direction}`;
6388
+ article.dataset.intercomMessageId = message.id;
6389
+ article.setAttribute("aria-label", `${senderLabel} message`);
6390
+ const header = make("header", "intercom-conversation-message-header");
6391
+ header.append(make("strong", "intercom-conversation-message-sender", senderLabel));
6392
+ if (formattedTime) {
6393
+ const time = make("time", "intercom-conversation-message-time", formattedTime);
6394
+ time.dateTime = message.timestamp;
6395
+ header.append(time);
6396
+ }
6397
+ const text = make("p", "intercom-conversation-message-text");
6398
+ text.textContent = message.text;
6399
+ const children = [header, text];
6400
+ if (message.truncatedText) children.push(make("span", "intercom-conversation-truncated", "Message truncated"));
6401
+ article.replaceChildren(...children);
6402
+ intercomMessageRenderSignatures.set(article, signature);
6403
+ }
6404
+
6405
+ function renderIntercomConversationDetail(conversation) {
6406
+ const transcript = elements.intercomConversationTranscript;
6407
+ if (!transcript || !conversation) return;
6408
+ const state = intercomConversationDialogState;
6409
+ const signature = JSON.stringify([
6410
+ conversation.id,
6411
+ conversation.truncatedBefore,
6412
+ intercomConversationLabel(conversation),
6413
+ conversation.messages.map((message) => [message.id, message.direction, message.text, message.timestamp, message.truncatedText]),
6414
+ ]);
6415
+ if (state?.detailSignature === signature) return;
6416
+ if (state) state.detailSignature = signature;
6417
+
6418
+ const existingArticles = new Map([...transcript.querySelectorAll(":scope > .intercom-conversation-message[data-intercom-message-id]")]
6419
+ .map((article) => [article.dataset.intercomMessageId, article]));
6420
+ const shouldFollow = !existingArticles.size || transcript.scrollHeight - transcript.scrollTop - transcript.clientHeight < 80;
6421
+ const previousScrollTop = transcript.scrollTop;
6422
+ const anchor = shouldFollow ? null : [...existingArticles.values()]
6423
+ .find((article) => article.offsetTop + article.offsetHeight > transcript.scrollTop);
6424
+ const anchorOffset = anchor ? anchor.getBoundingClientRect().top - transcript.getBoundingClientRect().top : 0;
6425
+ const orderedArticles = [];
6426
+
6427
+ for (const message of conversation.messages) {
6428
+ let article = existingArticles.get(message.id);
6429
+ if (article) existingArticles.delete(message.id);
6430
+ else article = make("article", `intercom-conversation-message ${message.direction}`);
6431
+ renderIntercomConversationMessage(article, message, conversation);
6432
+ orderedArticles.push(article);
6433
+ }
6434
+ for (const staleArticle of existingArticles.values()) staleArticle.remove();
6435
+ transcript.querySelector(":scope > .intercom-conversation-empty")?.remove();
6436
+
6437
+ let cursor = transcript.firstElementChild;
6438
+ for (const article of orderedArticles) {
6439
+ if (article === cursor) cursor = cursor.nextElementSibling;
6440
+ else transcript.insertBefore(article, cursor);
6441
+ }
6442
+ if (!orderedArticles.length) transcript.append(make("p", "intercom-conversation-empty", "No messages are available in this conversation."));
6443
+
6444
+ requestAnimationFrame(() => {
6445
+ if (state !== intercomConversationDialogState) return;
6446
+ if (shouldFollow) transcript.scrollTop = transcript.scrollHeight;
6447
+ else if (anchor?.isConnected) {
6448
+ const currentAnchorOffset = anchor.getBoundingClientRect().top - transcript.getBoundingClientRect().top;
6449
+ transcript.scrollTop += currentAnchorOffset - anchorOffset;
6450
+ }
6451
+ else transcript.scrollTop = previousScrollTop;
6452
+ });
6453
+ }
6454
+
6455
+ function updateIntercomSummaryFromDetail(conversation) {
6456
+ const state = intercomConversationDialogState;
6457
+ if (!state || !conversation) return;
6458
+ const summaries = intercomConversationSummariesByTab.get(state.tabId) || [];
6459
+ const index = summaries.findIndex((summary) => summary.id === conversation.id);
6460
+ if (index < 0) return;
6461
+ const next = [...summaries];
6462
+ next[index] = { ...next[index], ...normalizeIntercomConversationSummary(conversation) };
6463
+ intercomConversationSummariesByTab.set(state.tabId, next);
6464
+ }
6465
+
6466
+ function scheduleIntercomConversationDetailRefresh() {
6467
+ clearTimeout(intercomDetailRefreshTimer);
6468
+ intercomDetailRefreshTimer = null;
6469
+ const state = intercomConversationDialogState;
6470
+ if (!state || !elements.intercomConversationDialog?.open) return;
6471
+ intercomDetailRefreshTimer = setTimeout(() => {
6472
+ intercomDetailRefreshTimer = null;
6473
+ refreshIntercomConversationDetail({ announceLoading: false });
6474
+ }, INTERCOM_DETAIL_REFRESH_MS);
6475
+ }
6476
+
6477
+ async function refreshIntercomConversationDetail({ announceLoading = false } = {}) {
6478
+ const state = intercomConversationDialogState;
6479
+ if (!state || !elements.intercomConversationDialog?.open) return;
6480
+ const requestSerial = ++intercomDetailRequestSerial;
6481
+ if (announceLoading) setIntercomConversationStatus("Loading agent messages…");
6482
+ try {
6483
+ const path = `/api/intercom/conversations?conversation=${encodeURIComponent(state.conversationId)}`;
6484
+ const response = await api(path, { tabId: state.tabId });
6485
+ if (requestSerial !== intercomDetailRequestSerial || state !== intercomConversationDialogState || !isCurrentTabContext(state)) return;
6486
+ const conversation = normalizeIntercomConversationDetail(response.data?.conversation);
6487
+ if (!conversation || conversation.id !== state.conversationId) throw new Error("Agent conversation is unavailable.");
6488
+ elements.intercomConversationTitle.textContent = intercomParticipantLabel(conversation.participants.peer, "Agent conversation");
6489
+ elements.intercomConversationParticipants.textContent = intercomConversationLabel(conversation);
6490
+ renderIntercomConversationDetail(conversation);
6491
+ updateIntercomSummaryFromDetail(conversation);
6492
+ const notices = [];
6493
+ if (conversation.truncatedBefore) notices.push("Earlier messages are unavailable.");
6494
+ if (conversation.messages.some((message) => message.truncatedText)) notices.push("One or more messages were truncated.");
6495
+ setIntercomConversationStatus(notices.join(" "), notices.length ? "warn" : "");
6496
+ } catch (error) {
6497
+ if (requestSerial === intercomDetailRequestSerial && state === intercomConversationDialogState && isCurrentTabContext(state)) {
6498
+ setIntercomConversationStatus(error.message || String(error), "error");
6499
+ }
6500
+ } finally {
6501
+ if (requestSerial === intercomDetailRequestSerial && state === intercomConversationDialogState) scheduleIntercomConversationDetailRefresh();
6502
+ }
6503
+ }
6504
+
6505
+ function openIntercomConversation(conversationId) {
6506
+ if (!activeTabId || !INTERCOM_CONVERSATION_ID_PATTERN.test(String(conversationId || "")) || !elements.intercomConversationDialog) return;
6507
+ const summary = (intercomConversationSummariesByTab.get(activeTabId) || []).find((conversation) => conversation.id === conversationId);
6508
+ if (!summary) return;
6509
+ intercomDetailRequestSerial += 1;
6510
+ clearTimeout(intercomDetailRefreshTimer);
6511
+ intercomConversationDialogState = { ...activeTabContext(), conversationId, detailSignature: "" };
6512
+ elements.intercomConversationTitle.textContent = intercomParticipantLabel(summary.participants.peer, "Agent conversation");
6513
+ elements.intercomConversationParticipants.textContent = intercomConversationLabel(summary);
6514
+ elements.intercomConversationTranscript.replaceChildren();
6515
+ setIntercomConversationStatus("Loading agent messages…");
6516
+ if (!elements.intercomConversationDialog.open) elements.intercomConversationDialog.showModal();
6517
+ queueMicrotask(() => elements.intercomConversationCloseButton?.focus({ preventScroll: true }));
6518
+ refreshIntercomConversationDetail({ announceLoading: false });
6519
+ }
6520
+
6521
+ function resetIntercomConversationDialog() {
6522
+ intercomDetailRequestSerial += 1;
6523
+ clearTimeout(intercomDetailRefreshTimer);
6524
+ intercomDetailRefreshTimer = null;
6525
+ intercomConversationDialogState = null;
6526
+ elements.intercomConversationTranscript?.replaceChildren();
6527
+ if (elements.intercomConversationParticipants) elements.intercomConversationParticipants.textContent = "";
6528
+ setIntercomConversationStatus("");
6529
+ renderIntercomConversationTags(activeTabId);
6530
+ }
6531
+
6532
+ function closeIntercomConversationDialog({ restoreFocus = true } = {}) {
6533
+ const dialog = elements.intercomConversationDialog;
6534
+ if (!dialog?.open) {
6535
+ resetIntercomConversationDialog();
6536
+ return;
6537
+ }
6538
+ if (!restoreFocus) modalSurfaceState.delete(dialog);
6539
+ dialog.close();
6540
+ }
6541
+
6106
6542
  function normalizeFeatureCategory(value) {
6107
6543
  return value === "lightweight-feature" || value === "complex-feature" ? value : "";
6108
6544
  }
@@ -7363,10 +7799,16 @@ function renderServerOfflinePanel() {
7363
7799
  if (elements.serverOfflineSlashCommand) elements.serverOfflineSlashCommand.textContent = serverStartSlashCommandText();
7364
7800
  }
7365
7801
 
7366
- function setServerRestartOverlay(active, message = "Waiting for the server to come back…") {
7802
+ function setServerRestartOverlay(active, message = "Waiting for the server to come back…", { phase = "restarting" } = {}) {
7367
7803
  serverRestartInProgress = !!active;
7804
+ const updating = phase === "updating";
7368
7805
  document.body.classList.toggle("server-restarting", serverRestartInProgress);
7369
- if (elements.serverRestartPanel) elements.serverRestartPanel.hidden = !serverRestartInProgress;
7806
+ if (elements.serverRestartPanel) {
7807
+ elements.serverRestartPanel.hidden = !serverRestartInProgress;
7808
+ elements.serverRestartPanel.dataset.phase = updating ? "updating" : "restarting";
7809
+ }
7810
+ if (elements.serverRestartKicker) elements.serverRestartKicker.textContent = updating ? "Updating" : "Restarting";
7811
+ if (elements.serverRestartTitle) elements.serverRestartTitle.textContent = updating ? "Applying exact update" : "Restarting Pi Web UI server";
7370
7812
  if (elements.serverRestartMessage) elements.serverRestartMessage.textContent = message;
7371
7813
  if (serverRestartInProgress) hideUpdateNotification();
7372
7814
  if (serverRestartInProgress && elements.serverOfflinePanel) elements.serverOfflinePanel.hidden = true;
@@ -8189,7 +8631,8 @@ function componentUpdateButtonState(target) {
8189
8631
  const pkg = latestUpdateStatus?.[target] || {};
8190
8632
  if (job?.state === "running") return { disabled: true, label: "Updating…" };
8191
8633
  if (job && job.canStart === false) return { disabled: true, label: `Update ${label}` };
8192
- if (componentUpdateStartInProgress || updateRequestInProgress || latestUpdateStatus?.updateInProgress || anyComponentUpdateRunning()) {
8634
+ if (componentUpdateStartInProgress) return { disabled: true, label: "Starting…" };
8635
+ if (updateRequestInProgress || latestUpdateStatus?.updateInProgress || anyComponentUpdateRunning()) {
8193
8636
  return { disabled: true, label: `Update ${label}` };
8194
8637
  }
8195
8638
  if (job?.state === "failed") return { disabled: false, label: `Retry ${label} update` };
@@ -8279,6 +8722,7 @@ async function startComponentUpdate(target) {
8279
8722
  if (!confirmed) return;
8280
8723
  componentUpdateStartInProgress = true;
8281
8724
  renderComponentUpdateDialogs();
8725
+ setServerRestartOverlay(true, `Starting exact ${label} update…`, { phase: "updating" });
8282
8726
  try {
8283
8727
  const response = await api("/api/update/apply", { method: "POST", body: { transactionId: plan.transactionId, planDigest: plan.digest }, scoped: false });
8284
8728
  const acceptedState = ["applying", "verifying", "activating"].includes(response?.data?.state)
@@ -8298,6 +8742,7 @@ async function startComponentUpdate(target) {
8298
8742
  if (error?.statusCode === 409) await refreshUpdateStatus({ notify: false }).catch(() => {});
8299
8743
  } finally {
8300
8744
  componentUpdateStartInProgress = false;
8745
+ setServerRestartOverlay(false);
8301
8746
  renderComponentUpdateIndicators();
8302
8747
  renderComponentUpdateDialogs();
8303
8748
  syncComponentUpdatePolling();
@@ -8372,7 +8817,7 @@ async function runPiUpdateAndRestart({ all = false } = {}) {
8372
8817
  hideUpdateNotification();
8373
8818
  setServerActionBusy("Updating…");
8374
8819
  setServerActionStatus(progressMessage, "warn");
8375
- if (plannedRestart) setServerRestartOverlay(true, progressMessage);
8820
+ setServerRestartOverlay(true, progressMessage, { phase: "updating" });
8376
8821
  try {
8377
8822
  const applyData = (await api("/api/update/apply", { method: "POST", body: { transactionId: plan.transactionId, planDigest: plan.digest }, scoped: false }))?.data || null;
8378
8823
  if (applyData?.state !== "activating") {
@@ -10467,6 +10912,15 @@ function applyTheme(theme, { persist = false, announce = false } = {}) {
10467
10912
  "--background-glow-pink": colorWithAlpha(pink, isLight ? 0.16 : 0.34, pink),
10468
10913
  "--background-glow-blue": colorWithAlpha(accent, isLight ? 0.15 : 0.32, accent),
10469
10914
  "--background-glow-teal": colorWithAlpha(accent2, isLight ? 0.12 : 0.20, accent2),
10915
+ "--syntax-comment": themeColor(theme, "syntaxComment", muted),
10916
+ "--syntax-keyword": themeColor(theme, "syntaxKeyword", mauve),
10917
+ "--syntax-function": themeColor(theme, "syntaxFunction", accent),
10918
+ "--syntax-variable": themeColor(theme, "syntaxVariable", text),
10919
+ "--syntax-string": themeColor(theme, "syntaxString", green),
10920
+ "--syntax-number": themeColor(theme, "syntaxNumber", peach),
10921
+ "--syntax-type": themeColor(theme, "syntaxType", yellow),
10922
+ "--syntax-operator": themeColor(theme, "syntaxOperator", accent2),
10923
+ "--syntax-punctuation": themeColor(theme, "syntaxPunctuation", muted),
10470
10924
  "--theme-background-image": themeExportCssValue(theme, "backgroundImage", "none", LOCAL_BACKGROUND_IMAGE_PATTERN),
10471
10925
  "--theme-background-overlay": themeExportCssValue(theme, "backgroundOverlay", "linear-gradient(180deg, rgba(17, 17, 27, 0), rgba(17, 17, 27, 0))", BACKGROUND_OVERLAY_PATTERN),
10472
10926
  "--theme-background-size": themeExportCssValue(theme, "backgroundSize", "cover", SAFE_BACKGROUND_TOKEN_PATTERN),
@@ -11202,11 +11656,17 @@ function setActiveTabId(tabId, { remember = false } = {}) {
11202
11656
  const nextTabId = tabId || null;
11203
11657
  if (nextTabId !== activeTabId) {
11204
11658
  activeTabGeneration += 1;
11659
+ intercomSummaryRequestSerial += 1;
11660
+ clearTimeout(intercomSummaryRefreshTimer);
11661
+ intercomSummaryRefreshTimer = null;
11662
+ closeIntercomConversationDialog({ restoreFocus: false });
11205
11663
  closeFeatureDecisionDialog({ restoreFocus: false });
11206
11664
  closeSessionSummaryOverlay({ restoreFocus: false });
11207
11665
  }
11208
11666
  activeTabId = nextTabId;
11667
+ renderMainOutputLoading();
11209
11668
  bindGitWorkflowToActiveTab();
11669
+ renderIntercomConversationTags(nextTabId);
11210
11670
  renderFeatureCategoryTag(nextTabId);
11211
11671
  renderSessionSummaryControls();
11212
11672
  if (remember) rememberActiveTab();
@@ -13400,12 +13860,22 @@ async function openFileTreeEntryInWebui(entry = fileContextMenuState?.entry) {
13400
13860
  await openFileInViewer(path);
13401
13861
  }
13402
13862
 
13403
- // Changes mode only exists for Git-originated opens; every other viewer keeps
13404
- // the original Source/Markdown-Preview behavior.
13863
+ const FILE_VIEWER_IMAGE_MIME_TYPES = new Set(["image/png", "image/jpeg", "image/gif", "image/webp", "image/avif"]);
13864
+
13865
+ function fileViewerImageDataUrl(data = {}) {
13866
+ const mimeType = String(data.mimeType || "").toLowerCase();
13867
+ const encoded = String(data.data || "");
13868
+ if (!FILE_VIEWER_IMAGE_MIME_TYPES.has(mimeType) || !encoded) return "";
13869
+ return `data:${mimeType};base64,${encoded}`;
13870
+ }
13871
+
13872
+ // Changes mode only exists for Git-originated opens. Image previews are
13873
+ // read-only, while text keeps the original Source/Markdown-Preview behavior.
13405
13874
  function resolveFileViewerMode(viewer) {
13406
13875
  if (!viewer) return "source";
13407
13876
  const hasChanges = !!viewer.gitChanges;
13408
- if (viewer.mode === "changes") return hasChanges ? "changes" : "source";
13877
+ if (viewer.mode === "changes") return hasChanges ? "changes" : viewer.kind === "image" ? "image" : "source";
13878
+ if (viewer.kind === "image") return "image";
13409
13879
  if (viewer.sourceAvailable === false) return hasChanges ? "changes" : "source";
13410
13880
  return viewer.mode === "preview" && viewer.language === "markdown" ? "preview" : "source";
13411
13881
  }
@@ -13444,6 +13914,7 @@ function updateFileViewerUi() {
13444
13914
  const viewer = activeFileViewer;
13445
13915
  captureFileViewerEditorContinuity(viewer);
13446
13916
  const isMarkdown = viewer.language === "markdown";
13917
+ const isImage = viewer.kind === "image";
13447
13918
  const hasChanges = !!viewer.gitChanges;
13448
13919
  const sourceAvailable = viewer.sourceAvailable !== false;
13449
13920
  const mode = resolveFileViewerMode(viewer);
@@ -13451,7 +13922,9 @@ function updateFileViewerUi() {
13451
13922
  if (elements.fileViewerTitle) elements.fileViewerTitle.textContent = viewer.name || fileDisplayName(viewer.path);
13452
13923
  if (elements.fileViewerMeta) {
13453
13924
  const lineCount = textLineCount(viewer.content || "");
13454
- const sourceMeta = sourceAvailable ? [formatBytes(viewer.size), `${lineCount} ${lineCount === 1 ? "line" : "lines"}`] : ["source unavailable"];
13925
+ const sourceMeta = isImage
13926
+ ? [formatBytes(viewer.size), viewer.mimeType]
13927
+ : sourceAvailable ? [formatBytes(viewer.size), `${lineCount} ${lineCount === 1 ? "line" : "lines"}`] : ["source unavailable"];
13455
13928
  elements.fileViewerMeta.textContent = [viewer.path, ...sourceMeta].filter(Boolean).join(" · ");
13456
13929
  }
13457
13930
  if (elements.fileViewerChangesModeButton) {
@@ -13467,10 +13940,10 @@ function updateFileViewerUi() {
13467
13940
  elements.fileViewerSourceModeButton.classList.toggle("active", mode === "source");
13468
13941
  }
13469
13942
  if (elements.fileViewerPreviewModeButton) {
13470
- elements.fileViewerPreviewModeButton.hidden = !isMarkdown;
13471
- elements.fileViewerPreviewModeButton.disabled = !isMarkdown || !sourceAvailable;
13472
- elements.fileViewerPreviewModeButton.setAttribute("aria-pressed", mode === "preview" ? "true" : "false");
13473
- elements.fileViewerPreviewModeButton.classList.toggle("active", mode === "preview");
13943
+ elements.fileViewerPreviewModeButton.hidden = !isMarkdown && !isImage;
13944
+ elements.fileViewerPreviewModeButton.disabled = (!isMarkdown || !sourceAvailable) && !isImage;
13945
+ elements.fileViewerPreviewModeButton.setAttribute("aria-pressed", ["preview", "image"].includes(mode) ? "true" : "false");
13946
+ elements.fileViewerPreviewModeButton.classList.toggle("active", ["preview", "image"].includes(mode));
13474
13947
  }
13475
13948
  if (elements.fileViewerEditor) {
13476
13949
  elements.fileViewerEditor.hidden = mode !== "source";
@@ -13482,6 +13955,17 @@ function updateFileViewerUi() {
13482
13955
  if (elements.fileViewerPreview) {
13483
13956
  elements.fileViewerPreview.hidden = mode !== "preview";
13484
13957
  if (mode === "preview") renderMarkdown(elements.fileViewerPreview, viewer.content || "");
13958
+ else elements.fileViewerPreview.replaceChildren();
13959
+ }
13960
+ if (elements.fileViewerImage) elements.fileViewerImage.hidden = mode !== "image";
13961
+ if (elements.fileViewerImageElement) {
13962
+ if (isImage) {
13963
+ if (elements.fileViewerImageElement.src !== viewer.imageUrl) elements.fileViewerImageElement.src = viewer.imageUrl;
13964
+ elements.fileViewerImageElement.alt = `Preview of ${viewer.name || fileDisplayName(viewer.path)}`;
13965
+ } else {
13966
+ elements.fileViewerImageElement.removeAttribute("src");
13967
+ elements.fileViewerImageElement.alt = "";
13968
+ }
13485
13969
  }
13486
13970
  if (elements.fileViewerChanges) {
13487
13971
  elements.fileViewerChanges.hidden = mode !== "changes";
@@ -13494,6 +13978,10 @@ function updateFileViewerUi() {
13494
13978
  elements.fileViewerOpenDefaultButton.dataset.path = viewerPath;
13495
13979
  elements.fileViewerOpenDefaultButton.disabled = viewer.readOnly === true || !viewerPath;
13496
13980
  }
13981
+ if (isImage) {
13982
+ clearFileViewerSelection();
13983
+ closeFileViewerSearch({ restoreFocus: false });
13984
+ }
13497
13985
  renderFileViewerSelectionBar();
13498
13986
  if (elements.fileViewerSearchBar && !elements.fileViewerSearchBar.hidden) {
13499
13987
  fileViewerSearchIndex = -1;
@@ -13509,6 +13997,7 @@ function fileViewerSearchQueryText() {
13509
13997
 
13510
13998
  function fileViewerSearchSurface() {
13511
13999
  const mode = resolveFileViewerMode(activeFileViewer);
14000
+ if (mode === "image") return null;
13512
14001
  if (mode === "preview") return elements.fileViewerPreview;
13513
14002
  if (mode === "changes") return elements.fileViewerChanges;
13514
14003
  return elements.fileViewerEditor;
@@ -13672,7 +14161,7 @@ function stepFileViewerSearch(step) {
13672
14161
  }
13673
14162
 
13674
14163
  function openFileViewerSearch() {
13675
- if (!activeFileViewer || !elements.fileViewerSearchBar) return;
14164
+ if (!activeFileViewer || activeFileViewer.kind === "image" || !elements.fileViewerSearchBar) return;
13676
14165
  closeChatSearch();
13677
14166
  const editor = fileViewerSearchSurface() === elements.fileViewerEditor ? elements.fileViewerEditor : null;
13678
14167
  const selectedText = editor && editor.selectionEnd > editor.selectionStart
@@ -13700,7 +14189,8 @@ function closeFileViewerSearch({ restoreFocus = true } = {}) {
13700
14189
  updateFileViewerSearchCount();
13701
14190
  if (!restoreFocus) return;
13702
14191
  const mode = resolveFileViewerMode(activeFileViewer);
13703
- if (mode === "preview") elements.fileViewerPreview?.focus({ preventScroll: true });
14192
+ if (mode === "image") elements.fileViewerImage?.focus({ preventScroll: true });
14193
+ else if (mode === "preview") elements.fileViewerPreview?.focus({ preventScroll: true });
13704
14194
  else if (mode === "changes") elements.fileViewerChanges?.focus({ preventScroll: true });
13705
14195
  else elements.fileViewerEditor?.focus({ preventScroll: true });
13706
14196
  }
@@ -13953,6 +14443,11 @@ function resetFileViewerUi() {
13953
14443
  elements.fileViewerEditor.readOnly = false;
13954
14444
  }
13955
14445
  if (elements.fileViewerPreview) elements.fileViewerPreview.replaceChildren();
14446
+ if (elements.fileViewerImage) elements.fileViewerImage.hidden = true;
14447
+ if (elements.fileViewerImageElement) {
14448
+ elements.fileViewerImageElement.removeAttribute("src");
14449
+ elements.fileViewerImageElement.alt = "";
14450
+ }
13956
14451
  if (elements.fileViewerChanges) {
13957
14452
  elements.fileViewerChanges.hidden = true;
13958
14453
  elements.fileViewerChanges.replaceChildren();
@@ -14043,25 +14538,31 @@ async function openFileInViewer(path = "", { gitCategory = "", gitPath = "" } =
14043
14538
  if (!isCurrentTabContext(tabContext) || openRequestSerial !== fileViewerOpenRequestSerial) return;
14044
14539
  const data = response.data || {};
14045
14540
  const gitChanges = changesRequest ? gitFileChangesPlaceholder(category, changesPath, changesRequestSerial) : null;
14541
+ const kind = data.kind === "image" ? "image" : "text";
14542
+ const imageUrl = kind === "image" ? fileViewerImageDataUrl(data) : "";
14543
+ if (kind === "image" && !imageUrl) throw new Error("Image preview data is invalid or unsupported");
14046
14544
  activeFileViewer = {
14047
14545
  path: normalizeFileTreePath(data.path || normalized),
14048
14546
  name: data.name || fileDisplayName(normalized),
14049
- content: String(data.content || ""),
14547
+ content: kind === "text" ? String(data.content || "") : "",
14050
14548
  size: Number(data.size) || 0,
14051
14549
  mtimeMs: Number(data.mtimeMs) || 0,
14052
14550
  extension: data.extension || "",
14053
- language: data.language || "text",
14054
- mode: gitChanges ? "changes" : data.language === "markdown" ? "preview" : "source",
14551
+ language: kind === "text" ? data.language || "text" : "image",
14552
+ kind,
14553
+ mimeType: kind === "image" ? String(data.mimeType || "") : "",
14554
+ imageUrl,
14555
+ mode: gitChanges ? "changes" : kind === "image" ? "image" : data.language === "markdown" ? "preview" : "source",
14055
14556
  dirty: false,
14056
- readOnly: false,
14057
- sourceAvailable: true,
14557
+ readOnly: kind === "image",
14558
+ sourceAvailable: kind === "text",
14058
14559
  gitChanges,
14059
14560
  };
14060
14561
  if (elements.fileViewerEditor) elements.fileViewerEditor.value = activeFileViewer.content;
14061
14562
  clearFileViewerSelection();
14062
14563
  cacheActiveFileViewerForTab();
14063
14564
  updateFileViewerUi();
14064
- setFileViewerStatus("Opened in WebUI.", "success");
14565
+ setFileViewerStatus(kind === "image" ? "Image opened in WebUI (read-only)." : "Opened in WebUI.", "success");
14065
14566
  if (changesRequest) void applyGitFileChangesSnapshot(changesRequest, tabContext, activeFileViewer.path, changesRequestSerial);
14066
14567
  } catch (error) {
14067
14568
  const message = error.message || String(error);
@@ -15637,7 +16138,25 @@ function appendTerminalTabContent(button, { title, indicator, meta, count = null
15637
16138
  button.append(titleRow, make("span", "terminal-tab-meta", meta));
15638
16139
  }
15639
16140
 
15640
- function renderTerminalTab(tab) {
16141
+ function createTerminalTabCwdAddMenu(tab) {
16142
+ const cwdTitle = tabGroupTitle(tab?.cwd, "working directory");
16143
+ const menu = make("div", "terminal-tab-cwd-add-menu");
16144
+ menu.setAttribute("role", "group");
16145
+ menu.setAttribute("aria-label", `Actions for ${cwdTitle}`);
16146
+ const add = make("button", "terminal-tab-group-add terminal-tab-cwd-add", "+ Tab");
16147
+ add.type = "button";
16148
+ add.draggable = false;
16149
+ const addTooltip = `Add tab in ${cwdTitle}`;
16150
+ applyStyledTooltip(add, addTooltip, { ariaLabel: addTooltip, targetKey: `terminal-tab:${tab.id}:add` });
16151
+ add.addEventListener("click", (event) => {
16152
+ event.stopPropagation();
16153
+ void createTerminalTab(tab.cwd || currentDirectoryForNewTab(), { triggerButton: add });
16154
+ });
16155
+ menu.append(add);
16156
+ return menu;
16157
+ }
16158
+
16159
+ function renderTerminalTab(tab, { showCwdAdd = false } = {}) {
15641
16160
  const isActive = tab.id === activeTabId && !activeSubagentTerminalId;
15642
16161
  const indicator = tabIndicator(tab);
15643
16162
  const appRunnerRun = tabAppRunnerRunningRun(tab);
@@ -15646,7 +16165,7 @@ function renderTerminalTab(tab) {
15646
16165
  const conversationLabel = conversationModeActive ? `, natural conversation ${tabConversationMode(tab).uiState || "listening"}` : "";
15647
16166
  const workflowModeActive = tabWorkflowModeActive(tab);
15648
16167
  const workflowCount = workflowRunningCountForTab(tab.id);
15649
- const wrapper = make("div", `terminal-tab activity-${indicator.state}${isActive ? " active" : ""}${tab.running ? "" : " stopped"}${appRunnerRun ? " app-runner-running" : ""}${conversationModeActive ? " conversation-mode-running" : ""}${workflowModeActive ? " workflow-mode-running" : ""}${workflowCount ? " workflow-run-running" : ""}`);
16168
+ const wrapper = make("div", `terminal-tab${showCwdAdd ? " terminal-tab-cwd-add-host" : ""} activity-${indicator.state}${isActive ? " active" : ""}${tab.running ? "" : " stopped"}${appRunnerRun ? " app-runner-running" : ""}${conversationModeActive ? " conversation-mode-running" : ""}${workflowModeActive ? " workflow-mode-running" : ""}${workflowCount ? " workflow-run-running" : ""}`);
15650
16169
  wrapper.dataset.tabId = tab.id;
15651
16170
  bindTerminalTabDragAndDrop(wrapper, { sourceTabId: tab.id, target: { type: "tab", tabId: tab.id } });
15652
16171
  const button = make("button", "terminal-tab-button");
@@ -15659,6 +16178,7 @@ function renderTerminalTab(tab) {
15659
16178
  appendTerminalTabContent(button, { title: tab.title, indicator, meta: terminalTabMeta(tab, indicator), appRunnerRun, conversationModeActive, workflowModeActive, workflowCount });
15660
16179
  button.addEventListener("click", () => switchTab(tab.id));
15661
16180
  wrapper.append(button, createTerminalTabActions(tab));
16181
+ if (showCwdAdd) wrapper.append(createTerminalTabCwdAddMenu(tab));
15662
16182
 
15663
16183
  if (tabs.length > 1) {
15664
16184
  const close = make("button", "terminal-tab-close", "×");
@@ -15918,6 +16438,7 @@ function terminalTabControlKey(node) {
15918
16438
  if (node.classList.contains("terminal-tab-close")) return `terminal-tab:${tabId}:close`;
15919
16439
  if (node.classList.contains("terminal-tab-split-button")) return `terminal-tab:${tabId}:split`;
15920
16440
  if (node.classList.contains("terminal-tab-summary-button")) return `terminal-tab:${tabId}:summary`;
16441
+ if (node.classList.contains("terminal-tab-cwd-add")) return `terminal-tab:${tabId}:add`;
15921
16442
  if (node.classList.contains("terminal-tab-button")) return `terminal-tab:${tabId}:switch`;
15922
16443
  }
15923
16444
  const groupKey = node?.closest?.("[data-group-key]")?.dataset?.groupKey;
@@ -15956,7 +16477,8 @@ function renderTabs() {
15956
16477
  if (shouldRenderTerminalTabGroup(group, groups.length)) {
15957
16478
  elements.tabBar.append(renderTerminalTabGroup(group, groups.length));
15958
16479
  } else {
15959
- for (const tab of group.tabs) elements.tabBar.append(renderTerminalTab(tab));
16480
+ const showCwdAdd = groups.length > 1 && group.tabs.length === 1 && Boolean(group.cwd);
16481
+ for (const tab of group.tabs) elements.tabBar.append(renderTerminalTab(tab, { showCwdAdd }));
15960
16482
  }
15961
16483
  }
15962
16484
  for (const group of subagentGroups) {
@@ -16067,6 +16589,9 @@ async function refreshTabs({ selectStored = false } = {}) {
16067
16589
  tabs = nextTabs;
16068
16590
  syncTabMetadata(tabs);
16069
16591
  const liveParentTabIds = new Set(tabs.map((tab) => tab.id));
16592
+ for (const tabId of intercomConversationSummariesByTab.keys()) {
16593
+ if (!liveParentTabIds.has(tabId)) intercomConversationSummariesByTab.delete(tabId);
16594
+ }
16070
16595
  for (const view of [...subagentTerminalViews.values()]) {
16071
16596
  if (!liveParentTabIds.has(view.parentTabId)) removeSubagentTerminalViewsForParent(view.parentTabId);
16072
16597
  }
@@ -23223,6 +23748,64 @@ function subagentAgentStatus(run = {}, agent = null) {
23223
23748
  return SUBAGENT_LIFECYCLE_STATES.has(status) ? status : status === "pending" ? "queued" : "running";
23224
23749
  }
23225
23750
 
23751
+ function subagentIsWorkflowController(run = {}, agent = {}) {
23752
+ if (String(agent?.name || "").trim().toLowerCase() !== "workflow") return false;
23753
+ if (String(agent?.model || "").trim() || String(agent?.thinking || "").trim()) return false;
23754
+ const launcher = String(agent?.launcher || run?.launcher || "").trim();
23755
+ const legacyProvisional = run?.source === "foreground" && /(?:^|:)workflow$/i.test(String(agent?.id || ""));
23756
+ return launcher === "pi-subagents" || legacyProvisional;
23757
+ }
23758
+
23759
+ function subagentWorkflowController(run = {}) {
23760
+ return (Array.isArray(run?.agents) ? run.agents : []).find((agent) => subagentIsWorkflowController(run, agent)) || null;
23761
+ }
23762
+
23763
+ function subagentRunAgents(run = {}) {
23764
+ const controller = subagentWorkflowController(run);
23765
+ return (Array.isArray(run?.agents) ? run.agents : []).filter((agent) => agent !== controller);
23766
+ }
23767
+
23768
+ function subagentRunAgentCounts(runs = []) {
23769
+ return (Array.isArray(runs) ? runs : []).reduce((counts, run) => {
23770
+ for (const agent of subagentRunAgents(run)) {
23771
+ counts.total += 1;
23772
+ const status = subagentAgentStatus(run, agent);
23773
+ if (status === "running") counts.running += 1;
23774
+ if (status === "stale") counts.stale += 1;
23775
+ }
23776
+ return counts;
23777
+ }, { total: 0, running: 0, stale: 0 });
23778
+ }
23779
+
23780
+ function subagentRunPresentations(runs = []) {
23781
+ const presentations = [];
23782
+ let recoveredWorkflow = null;
23783
+ for (const run of Array.isArray(runs) ? runs : []) {
23784
+ const controller = subagentWorkflowController(run);
23785
+ const agents = subagentRunAgents(run).map((agent) => ({ run, agent }));
23786
+ if (controller) {
23787
+ const presentation = { run, controller, agents };
23788
+ presentations.push(presentation);
23789
+ const launcher = String(controller?.launcher || run?.launcher || "").trim();
23790
+ recoveredWorkflow = run?.source === "recovered" && launcher === "pi-subagents" ? presentation : null;
23791
+ continue;
23792
+ }
23793
+ const launcher = String(run?.launcher || "").trim();
23794
+ if (recoveredWorkflow && run?.source === "recovered" && launcher === "pi-subagents" && agents.length) {
23795
+ recoveredWorkflow.agents.push(...agents);
23796
+ continue;
23797
+ }
23798
+ recoveredWorkflow = null;
23799
+ presentations.push({ run, controller: null, agents });
23800
+ }
23801
+ return presentations;
23802
+ }
23803
+
23804
+ function subagentWorkflowPresentationStatus(run = {}, agents = []) {
23805
+ const statuses = [subagentAgentStatus(run), ...(Array.isArray(agents) ? agents : []).map((entry) => subagentAgentStatus(entry.run, entry.agent))];
23806
+ return ["running", "queued", "stale", "lost", "failed", "cancelled", "done"].find((status) => statuses.includes(status)) || "running";
23807
+ }
23808
+
23226
23809
  function subagentCapabilities(run = {}, agent = null) {
23227
23810
  const agentCapabilities = agent?.capabilities && typeof agent.capabilities === "object" ? agent.capabilities : null;
23228
23811
  const runCapabilities = run?.capabilities && typeof run.capabilities === "object" ? run.capabilities : null;
@@ -23238,6 +23821,7 @@ function subagentOverviewGroups(data = latestSubagents) {
23238
23821
  const legacy = legacyTabs.get(group.tabId) || {};
23239
23822
  const gates = visibleSubagentGates({ ...legacy, gates: group.gates || legacy.gates || [] }, dismissedSubagentGateKeys, now);
23240
23823
  const runs = Array.isArray(group.runs) ? group.runs : [];
23824
+ const agentCounts = subagentRunAgentCounts(runs);
23241
23825
  return {
23242
23826
  ...legacy,
23243
23827
  ...group,
@@ -23251,15 +23835,27 @@ function subagentOverviewGroups(data = latestSubagents) {
23251
23835
  gates,
23252
23836
  gateCount: gates.length,
23253
23837
  displayRuns: runs,
23254
- agentCount: runs.reduce((count, run) => count + (Array.isArray(run.agents) ? run.agents.length : 0), 0),
23255
- runningAgents: runs.reduce((count, run) => count + (Array.isArray(run.agents) ? run.agents.filter((agent) => subagentAgentStatus(run, agent) === "running").length : 0), 0),
23256
- staleAgents: runs.reduce((count, run) => count + (Array.isArray(run.agents) ? run.agents.filter((agent) => subagentAgentStatus(run, agent) === "stale").length : 0), 0),
23838
+ agentCount: agentCounts.total,
23839
+ runningAgents: agentCounts.running,
23840
+ staleAgents: agentCounts.stale,
23257
23841
  };
23258
23842
  });
23259
23843
  }
23260
23844
  return (Array.isArray(data?.tabs) ? data.tabs : []).map((tab) => {
23261
23845
  const gates = visibleSubagentGates(tab, dismissedSubagentGateKeys, now);
23262
- return { ...tab, groupId: `tab:${tab.tabId}`, groupKind: "tab", gates, gateCount: gates.length, displayRuns: ungatedSubagentRuns(tab) };
23846
+ const displayRuns = ungatedSubagentRuns(tab);
23847
+ const agentCounts = subagentRunAgentCounts(displayRuns);
23848
+ return {
23849
+ ...tab,
23850
+ groupId: `tab:${tab.tabId}`,
23851
+ groupKind: "tab",
23852
+ gates,
23853
+ gateCount: gates.length,
23854
+ displayRuns,
23855
+ agentCount: agentCounts.total,
23856
+ runningAgents: agentCounts.running,
23857
+ staleAgents: agentCounts.stale,
23858
+ };
23263
23859
  });
23264
23860
  }
23265
23861
 
@@ -23384,7 +23980,7 @@ function subagentCancelTargetLabel(selection = subagentCancelSelection) {
23384
23980
 
23385
23981
  function openSubagentCancelDialog(tab, run, agent = null) {
23386
23982
  if (!tab?.groupId || !run?.id || !subagentRunCanCancel(run, agent) || !elements.subagentCancelDialog) return;
23387
- const agentCount = Array.isArray(run.agents) ? run.agents.length : 0;
23983
+ const agentCount = subagentRunAgents(run).length;
23388
23984
  subagentCancelSelection = {
23389
23985
  groupId: tab.groupId,
23390
23986
  tabId: tab.tabId,
@@ -24210,7 +24806,7 @@ function materializeRetainedSubagentTerminalViews() {
24210
24806
  subagentTerminalRestoredParentTabs.add(restoreKey);
24211
24807
  for (const run of tab.displayRuns) {
24212
24808
  if (["queued", "running", "stale"].includes(subagentAgentStatus(run)) || run?.source === "workflow") continue;
24213
- for (const agent of Array.isArray(run.agents) ? run.agents : []) {
24809
+ for (const agent of subagentRunAgents(run)) {
24214
24810
  const id = subagentTerminalViewId(tab, run, agent);
24215
24811
  if (subagentTerminalViews.has(id)) continue;
24216
24812
  if (ensureSubagentTerminalView(tab, run, agent)) materialized = true;
@@ -24351,6 +24947,40 @@ function openSubagentOutput(tab, run, agent) {
24351
24947
  return subagentOpenMode === "tab" ? openSubagentTerminal(tab, run, agent) : openSubagentOverlay(tab, run, agent);
24352
24948
  }
24353
24949
 
24950
+ function subagentWorkflowRunKey(tab, run) {
24951
+ return `${tab?.groupId || tab?.tabId || ""}:${run?.id || ""}`;
24952
+ }
24953
+
24954
+ function renderSubagentWorkflow(tab, run, controller, agents) {
24955
+ const status = subagentWorkflowPresentationStatus(run, agents);
24956
+ const key = subagentWorkflowRunKey(tab, run);
24957
+ const details = make("details", `subagent-workflow state-${status}`);
24958
+ details.open = !collapsedSubagentWorkflowRunKeys.has(key);
24959
+ details.addEventListener("toggle", () => {
24960
+ if (details.open) collapsedSubagentWorkflowRunKeys.delete(key);
24961
+ else collapsedSubagentWorkflowRunKeys.add(key);
24962
+ });
24963
+
24964
+ const summary = make("summary", "subagent-workflow-header");
24965
+ summary.dataset.subagentContinuityKey = `workflow:${tab?.tabId || ""}:${run?.id || ""}`;
24966
+ summary.setAttribute("aria-label", `Workflow ${status}, ${agents.length} ${agents.length === 1 ? "agent" : "agents"}`);
24967
+ const dot = make("span", `subagent-state-dot ${status}`);
24968
+ dot.setAttribute("aria-hidden", "true");
24969
+ const identity = make("span", "subagent-agent-identity");
24970
+ identity.append(
24971
+ make("strong", "subagent-workflow-name", "Workflow"),
24972
+ make("span", "subagent-source-badge", subagentLauncherLabel(controller?.launcher || run?.launcher)),
24973
+ make("span", "subagent-agent-inline-meta", `· ${status} · ${agents.length} ${agents.length === 1 ? "agent" : "agents"}`),
24974
+ );
24975
+ summary.append(dot, identity);
24976
+
24977
+ const children = make("div", "subagent-workflow-agents");
24978
+ for (const entry of agents) children.append(renderSubagentAgent(tab, entry.run, entry.agent));
24979
+ if (!children.childElementCount) children.append(make("div", "subagents-empty", "Waiting for workflow agents…"));
24980
+ details.append(summary, children);
24981
+ return details;
24982
+ }
24983
+
24354
24984
  function renderSubagentAgent(tab, run, agent) {
24355
24985
  const status = subagentAgentStatus(run, agent);
24356
24986
  const running = ["queued", "running"].includes(status);
@@ -24385,15 +25015,18 @@ function renderSubagentAgent(tab, run, agent) {
24385
25015
  return row;
24386
25016
  }
24387
25017
 
24388
- function renderSubagentRun(tab, run) {
25018
+ function renderSubagentRun(tab, run, workflowAgents = null) {
24389
25019
  const running = subagentRunIsRunning(run);
24390
25020
  const card = make("section", `subagent-run ${running ? "running" : run?.status || "done"}`);
24391
- const agents = (Array.isArray(run?.agents) ? run.agents : [])
25021
+ const controller = subagentWorkflowController(run);
25022
+ const agents = subagentRunAgents(run)
24392
25023
  .slice()
24393
25024
  .sort((a, b) => Number(a.index || 0) - Number(b.index || 0) || String(a.name || "").localeCompare(String(b.name || "")));
24394
- card.setAttribute("aria-label", `Subagent run with ${agents.length} ${agents.length === 1 ? "agent" : "agents"}`);
25025
+ const presentedAgents = controller && Array.isArray(workflowAgents) ? workflowAgents : agents.map((agent) => ({ run, agent }));
25026
+ card.setAttribute("aria-label", `${controller ? "Workflow" : "Subagent"} run with ${presentedAgents.length} ${presentedAgents.length === 1 ? "agent" : "agents"}`);
24395
25027
  const list = make("div", "subagent-run-agents");
24396
- for (const agent of agents) list.append(renderSubagentAgent(tab, run, agent));
25028
+ if (controller) list.append(renderSubagentWorkflow(tab, run, controller, presentedAgents));
25029
+ else for (const agent of agents) list.append(renderSubagentAgent(tab, run, agent));
24397
25030
  if (!list.childElementCount) list.append(make("div", "subagents-empty", "No agents were captured."));
24398
25031
  card.append(list);
24399
25032
 
@@ -24523,11 +25156,12 @@ function renderSubagentTabGroup(tab) {
24523
25156
  const runs = (Array.isArray(tab.displayRuns) ? tab.displayRuns : ungatedSubagentRuns(tab))
24524
25157
  .slice()
24525
25158
  .sort((a, b) => Number(a.startedAt || 0) - Number(b.startedAt || 0) || String(a.id || "").localeCompare(String(b.id || "")));
24526
- const runningAgents = Number(tab.runningAgents || 0);
24527
- const staleAgents = Number(tab.staleAgents || 0);
25159
+ const agentCounts = subagentRunAgentCounts(runs);
25160
+ const runningAgents = agentCounts.running;
25161
+ const staleAgents = agentCounts.stale;
24528
25162
  const retainedRuns = runs.filter((run) => !["queued", "running", "stale"].includes(subagentAgentStatus(run))).length;
24529
25163
  const countLabel = [
24530
- `${tab.agentCount || 0} total`,
25164
+ `${agentCounts.total} total`,
24531
25165
  runningAgents ? `${runningAgents} running` : "",
24532
25166
  staleAgents ? `${staleAgents} stale` : "",
24533
25167
  retainedRuns ? `${retainedRuns} retained` : "",
@@ -24538,7 +25172,7 @@ function renderSubagentTabGroup(tab) {
24538
25172
  group.append(header);
24539
25173
 
24540
25174
  const list = make("div", "subagent-agent-list");
24541
- for (const run of runs) list.append(renderSubagentRun(tab, run));
25175
+ for (const presentation of subagentRunPresentations(runs)) list.append(renderSubagentRun(tab, presentation.run, presentation.agents));
24542
25176
  for (const gate of (Array.isArray(tab.gates) ? tab.gates : []).slice().sort((a, b) => Number(a.startedAt || 0) - Number(b.startedAt || 0))) {
24543
25177
  list.append(renderSubagentGate(tab, gate));
24544
25178
  }
@@ -24559,9 +25193,9 @@ function renderSubagents() {
24559
25193
  const restoreFocus = () => restoreScopedControlContinuity(box, continuityContextKey, focusSnapshot, (key) => [...box.querySelectorAll("[data-subagent-continuity-key]")].find((node) => subagentPanelControlKey(node) === key));
24560
25194
  const activeTabs = subagentTabsWithRunningAgents();
24561
25195
  const finishedRuns = finishedSubagentRunSelections();
24562
- const totalAgents = Number(latestSubagents?.counts?.totalAgents ?? latestSubagents?.totalAgents ?? activeTabs.reduce((count, tab) => count + Number(tab.agentCount || 0), 0));
24563
- const runningAgents = Number(latestSubagents?.counts?.runningAgents ?? latestSubagents?.runningAgents ?? activeTabs.reduce((count, tab) => count + Number(tab.runningAgents || 0), 0));
24564
- const staleAgents = Number(latestSubagents?.counts?.staleAgents ?? activeTabs.reduce((count, tab) => count + Number(tab.staleAgents || 0), 0));
25196
+ const totalAgents = activeTabs.reduce((count, tab) => count + Number(tab.agentCount || 0), 0);
25197
+ const runningAgents = activeTabs.reduce((count, tab) => count + Number(tab.runningAgents || 0), 0);
25198
+ const staleAgents = activeTabs.reduce((count, tab) => count + Number(tab.staleAgents || 0), 0);
24565
25199
  const totalRuns = activeTabs.reduce((count, tab) => count + tab.displayRuns.length, 0);
24566
25200
  const runningRuns = activeTabs.reduce((count, tab) => count + tab.displayRuns.filter((run) => run?.status === "running").length, 0);
24567
25201
  const retainedRuns = Math.max(0, totalRuns - runningRuns);
@@ -29793,6 +30427,11 @@ function renderWidgets() {
29793
30427
  if (btwWidget) elements.widgetArea.append(btwWidget);
29794
30428
 
29795
30429
  for (const [key, value] of widgets) {
30430
+ // pi-subagents publishes this machine-readable status for native TUI
30431
+ // consumers. The dedicated Subagents UI already consumes the equivalent
30432
+ // structured RPC state, so exposing the raw payload here duplicates state
30433
+ // and leaks an internal protocol record into the main conversation surface.
30434
+ if (key === SUBAGENT_ASYNC_WIDGET_KEY) continue;
29796
30435
  const widgetFeatureId = optionalFeatureWidgetFeatureId(key);
29797
30436
  if (widgetFeatureId && !isOptionalFeatureEnabled(widgetFeatureId)) continue;
29798
30437
  if (widgetFeatureId === "workflows" && workflowOverlayIsMinimized()) continue;
@@ -33249,6 +33888,22 @@ function appendMarkdownMermaidBlock(parent, code) {
33249
33888
  queueMicrotask(() => renderMermaidDiagram(diagram, status, source));
33250
33889
  }
33251
33890
 
33891
+ // Fenced code is rendered from the pure tokenizer as text nodes and span
33892
+ // textContent only. Source never reaches innerHTML, concatenated token text
33893
+ // reproduces the source exactly, and unknown/oversized blocks fall back to one
33894
+ // plain token so copy, selection, and transcript search stay unchanged.
33895
+ function appendMarkdownCodeTokens(codeNode, source, language) {
33896
+ const tokens = tokenizeCode(source, normalizedMarkdownLanguage(language));
33897
+ if (!tokens.length) {
33898
+ codeNode.textContent = source;
33899
+ return;
33900
+ }
33901
+ for (const { type, text } of tokens) {
33902
+ if (type === "plain") codeNode.append(document.createTextNode(text));
33903
+ else codeNode.append(make("span", `syntax-token syntax-${type}`, text));
33904
+ }
33905
+ }
33906
+
33252
33907
  function appendMarkdownCodeBlock(parent, code, language = "", { closed = true } = {}) {
33253
33908
  if (closed && isMermaidLanguage(language)) {
33254
33909
  appendMarkdownMermaidBlock(parent, code);
@@ -33258,7 +33913,7 @@ function appendMarkdownCodeBlock(parent, code, language = "", { closed = true }
33258
33913
  if (language) wrapper.append(make("div", "markdown-code-language", language));
33259
33914
  const pre = make("pre", "code-block markdown-code");
33260
33915
  const codeNode = make("code", language ? `language-${language.replace(/[^a-z0-9_-]/gi, "")}` : "");
33261
- codeNode.textContent = String(code || "").replace(/\n+$/g, "");
33916
+ appendMarkdownCodeTokens(codeNode, String(code || "").replace(/\n+$/g, ""), language);
33262
33917
  pre.append(codeNode);
33263
33918
  wrapper.append(pre);
33264
33919
  attachMarkdownCodeCopyButton(wrapper);
@@ -33883,11 +34538,28 @@ function joinedThinkingFormatParts(parts) {
33883
34538
  function thinkingFormatOpenMatch(text) {
33884
34539
  const value = String(text || "");
33885
34540
  const think = THINKING_FORMAT_OPEN_TAG_REGEX.exec(value);
33886
- if (think) return { raw: think[0], closeRegex: THINKING_FORMAT_CLOSE_TAG_REGEX, closeTag: "</think>" };
34541
+ if (think) return { kind: "think", raw: think[0], closeRegex: THINKING_FORMAT_CLOSE_TAG_REGEX, closeTag: "</think>" };
33887
34542
  const channel = CHANNEL_THINKING_FORMAT_OPEN_TAG_REGEX.exec(value);
33888
34543
  if (!channel) return null;
33889
34544
  const name = channel[1];
33890
- return { raw: channel[0], closeRegex: new RegExp(`<${escapeRegExp(name)}\\|>`, "i"), closeTag: `<${name}|>` };
34545
+ return { kind: "channel", raw: channel[0], closeRegex: new RegExp(`<${escapeRegExp(name)}\\|>`, "i"), closeTag: `<${name}|>` };
34546
+ }
34547
+
34548
+ function thinkingFormatCloseMatch(text, open) {
34549
+ const value = String(text || "");
34550
+ if (open?.kind !== "think") return open?.closeRegex?.exec(value) || null;
34551
+ const tokens = /<think\b[^>]*>|<\/think\s*>/gi;
34552
+ let depth = 1;
34553
+ let match = null;
34554
+ while ((match = tokens.exec(value))) {
34555
+ if (/^<\s*\/think/i.test(match[0])) {
34556
+ depth -= 1;
34557
+ if (depth === 0) return match;
34558
+ } else {
34559
+ depth += 1;
34560
+ }
34561
+ }
34562
+ return null;
33891
34563
  }
33892
34564
 
33893
34565
  function splitThinkingFormatText(text, { streaming = false } = {}) {
@@ -33903,7 +34575,7 @@ function splitThinkingFormatText(text, { streaming = false } = {}) {
33903
34575
  let open = thinkingFormatOpenMatch(rest);
33904
34576
  while (open) {
33905
34577
  const afterOpen = rest.slice(open.raw.length);
33906
- const close = open.closeRegex.exec(afterOpen);
34578
+ const close = thinkingFormatCloseMatch(afterOpen, open);
33907
34579
  if (!close) {
33908
34580
  thinkingParts.push(streaming ? stripPartialThinkingFormatClose(afterOpen, open.closeTag) : afterOpen);
33909
34581
  return { hasThinkingFormat: true, thinkingText: joinedThinkingFormatParts(thinkingParts), finalText: "", complete: false };
@@ -33945,6 +34617,17 @@ function assistantToolCallName(part) {
33945
34617
  return String(part?.name || part?.toolName || part?.toolCall?.name || "unknown");
33946
34618
  }
33947
34619
 
34620
+ function isIntercomTransportToolName(value) {
34621
+ return String(value || "").trim().toLowerCase() === "intercom";
34622
+ }
34623
+
34624
+ function isIntercomToolCallUpdate(event) {
34625
+ const update = event?.assistantMessageEvent || {};
34626
+ const part = assistantToolCallPartFromUpdate(event, update);
34627
+ const rawName = update.name || update.toolName || update.toolCall?.name || (part ? assistantToolCallName(part) : "");
34628
+ return isIntercomTransportToolName(rawName);
34629
+ }
34630
+
33948
34631
  function assistantToolCallArguments(part) {
33949
34632
  return part?.arguments || part?.args || part?.input || part?.toolCall?.arguments || {};
33950
34633
  }
@@ -38049,9 +38732,9 @@ function optionalFeatureStatus(featureId) {
38049
38732
  label: "Disabled",
38050
38733
  className: "disabled",
38051
38734
  detail: `Tool access is disabled for the active Pi session${versionSuffix}`,
38052
- hint: "Enable it here for this session, or use Setup to manage session and global tool defaults.",
38735
+ hint: "Enable it here for this session.",
38053
38736
  };
38054
- if (detected && managedWithTools) return { label: "Enabled", className: "enabled", detail: doneDetail || `Tool access is enabled for the active Pi session${versionSuffix}`, hint: "Use Setup to manage session and global tool defaults.", command: installState?.command || "" };
38737
+ if (detected && managedWithTools) return { label: "Enabled", className: "enabled", detail: doneDetail || `Tool access is enabled for the active Pi session${versionSuffix}`, command: installState?.command || "" };
38055
38738
  if (detected && !disabled) return { label: "Enabled", className: "enabled", detail: doneDetail || `Detected and enabled in Web UI${versionSuffix}`, command: installState?.command || "" };
38056
38739
  if (detected && disabled) return { label: "Disabled", className: "disabled", detail: `Detected, but disabled in Web UI${versionSuffix}` };
38057
38740
  if (packageStatus?.locallyConfigured) return { label: "Available locally", className: "installed", detail: doneDetail || `Enabled as a top-level Pi resource; reload this tab if the capability is not detected yet${versionSuffix}` };
@@ -38212,6 +38895,7 @@ function optionalFeatureSetupAvailable(feature) {
38212
38895
  case "git-workflow": return hasAvailableCommand("git-workflow-setup");
38213
38896
  case "workflows": return hasLoadedRpcCommand("workflow-setup");
38214
38897
  case "safety-guard": return hasAvailableCommand("safety-guard-setup");
38898
+ case "skills": return hasLoadedRpcCommand("skills");
38215
38899
  case "tools": return feature.manageWith !== "tools" || isOptionalFeatureDetected(feature.id);
38216
38900
  default: return false;
38217
38901
  }
@@ -38222,6 +38906,7 @@ function openOptionalFeatureSetup(feature) {
38222
38906
  case "git-workflow": return openNativeGitWorkflowSetupDialog();
38223
38907
  case "workflows": return openNativeWorkflowSetupDialog();
38224
38908
  case "safety-guard": return openNativeSafetyGuardSetupDialog();
38909
+ case "skills": return openNativeSkillsSelector();
38225
38910
  case "tools": return openNativeToolsSelector();
38226
38911
  default: return undefined;
38227
38912
  }
@@ -38432,6 +39117,8 @@ function renderOptionalFeatureControls() {
38432
39117
  const hasNativeCommandMenu = isOptionalFeatureEnabled("tuiSkillsCommand") || isOptionalFeatureEnabled("tuiToolsCommand");
38433
39118
  elements.nativeSkillsButton.hidden = !isOptionalFeatureEnabled("tuiSkillsCommand");
38434
39119
  elements.nativeToolsButton.hidden = !isOptionalFeatureEnabled("tuiToolsCommand");
39120
+ if (elements.optionsSkillsSetupButton) elements.optionsSkillsSetupButton.hidden = !isOptionalFeatureEnabled("tuiSkillsCommand");
39121
+ if (elements.optionsToolsSetupButton) elements.optionsToolsSetupButton.hidden = !isOptionalFeatureEnabled("tuiToolsCommand");
38435
39122
  const nativeCommandMenuContainer = elements.nativeCommandMenuButton.parentElement;
38436
39123
  if (nativeCommandMenuContainer) nativeCommandMenuContainer.hidden = !hasNativeCommandMenu;
38437
39124
  elements.nativeCommandMenuButton.hidden = !hasNativeCommandMenu;
@@ -39247,6 +39934,7 @@ function renderNativeSelectorItems(items, { emptyText = "No choices.", onSelect,
39247
39934
  const button = make("button", `native-selector-item${item.id === activeId ? " active" : ""}`);
39248
39935
  button.type = "button";
39249
39936
  button.disabled = item.disabled === true;
39937
+ if (typeof item.pressed === "boolean") button.setAttribute("aria-pressed", String(item.pressed));
39250
39938
  button.addEventListener("click", () => onSelect?.(item));
39251
39939
  const title = make("span", "native-selector-title");
39252
39940
  if (numbered) title.append(make("span", "native-selector-index", `${index + 1}.`));
@@ -40965,6 +41653,7 @@ function renderNativeResourceToggles(resources, { savingName, filter = "all", on
40965
41653
  meta: nativeResourceSourceLabel(resource),
40966
41654
  badge: resource.enabled === false ? "disabled" : "enabled",
40967
41655
  badgeClass: resource.enabled === false ? "disabled native-selector-badge-disabled" : "enabled native-selector-badge-enabled",
41656
+ pressed: resource.enabled !== false,
40968
41657
  tags: resourceTag ? [resourceTag] : [],
40969
41658
  disabled: Boolean(savingName),
40970
41659
  resource,
@@ -40978,7 +41667,7 @@ function renderNativeResourceToggles(resources, { savingName, filter = "all", on
40978
41667
  elements.nativeCommandBody.prepend(make("div", "native-resource-summary muted", `${counts.total} total · ${counts.enabled} enabled · ${counts.disabled} disabled · showing ${filterLabel}`));
40979
41668
  }
40980
41669
 
40981
- function renderNativeResourceFilterActions(filter, setFilter, render) {
41670
+ function renderNativeResourceFilterActions(filter, setFilter, render, extraActions = []) {
40982
41671
  elements.nativeCommandActions.replaceChildren();
40983
41672
  for (const option of [
40984
41673
  { value: "all", label: "All" },
@@ -40990,40 +41679,79 @@ function renderNativeResourceFilterActions(filter, setFilter, render) {
40990
41679
  render();
40991
41680
  }, filter === option.value ? "primary" : undefined);
40992
41681
  }
41682
+ for (const action of extraActions) {
41683
+ const button = addNativeCommandAction(action.label, action.handler);
41684
+ button.disabled = !!action.disabled;
41685
+ }
40993
41686
  addNativeCommandAction("Cancel", closeNativeCommandDialog);
40994
41687
  }
40995
41688
 
40996
41689
  function nativeResourceScopeControl(scope, { configured = false, saving = false, onChange } = {}) {
40997
- const global = scope === "global";
40998
- const hint = global
40999
- ? configured
41690
+ const hints = {
41691
+ session: "Applies immediately and persists only on the current session branch.",
41692
+ global: configured
41000
41693
  ? "Saved as the default for future sessions. Existing session-specific choices are unchanged."
41001
- : "No global default is saved yet. The current session is shown as the starting point."
41002
- : "Applies immediately and persists only on the current session branch.";
41694
+ : "No global default is saved yet. The current session is shown as the starting point.",
41695
+ model: configured
41696
+ ? "Saved for this exact model. Sessions without their own choice apply it whenever this model is selected."
41697
+ : "No default is saved for this exact model yet. The inherited selection is shown as the starting point.",
41698
+ };
41699
+ const badges = {
41700
+ session: { label: "This session", tone: "now" },
41701
+ global: { label: "Global", tone: "startup" },
41702
+ model: { label: "Exact model", tone: "startup" },
41703
+ };
41003
41704
  const control = nativeSettingSelect("Apply changes to", scope, [
41004
41705
  { value: "session", label: "Session only" },
41005
41706
  { value: "global", label: "Global default" },
41006
- ], hint, global ? { label: "Global", tone: "startup" } : { label: "This session", tone: "now" });
41707
+ { value: "model", label: "Model default" },
41708
+ ], hints[scope] || hints.session, badges[scope] || badges.session);
41007
41709
  control.field.classList.add("native-resource-scope");
41008
41710
  control.select.disabled = !!saving;
41009
41711
  control.select.addEventListener("change", () => onChange?.(control.select.value));
41010
41712
  return control.field;
41011
41713
  }
41012
41714
 
41715
+ function nativeResourceModelControl(models, modelIndex, { saving = false, onChange } = {}) {
41716
+ const options = models.map((model, index) => ({
41717
+ value: String(index),
41718
+ label: `${model.provider}/${model.id}${model.name && model.name !== model.id ? ` — ${model.name}` : ""}`,
41719
+ }));
41720
+ const control = nativeSettingSelect("Model default for", String(modelIndex), options, "Chooses which exact model profile to edit. The active session model is not changed.", { label: "Exact model", tone: "startup" });
41721
+ control.field.classList.add("native-resource-model");
41722
+ control.select.disabled = !!saving;
41723
+ control.select.addEventListener("change", () => onChange?.(Number(control.select.value)));
41724
+ return control.field;
41725
+ }
41726
+
41727
+ async function loadNativeResourceModels() {
41728
+ const response = await nativeCommandApi("/api/models");
41729
+ return (Array.isArray(response.data?.models) ? response.data.models : [])
41730
+ .filter((model) => model?.provider && model?.id)
41731
+ .sort((left, right) => `${left.provider}/${left.id}`.localeCompare(`${right.provider}/${right.id}`));
41732
+ }
41733
+
41013
41734
  async function openNativeToolsSelector() {
41014
- openNativeCommandDialog({ title: "Tools Setup", message: "Enable or disable tool access for this session or save a default for future sessions.", searchPlaceholder: "Filter tools…" });
41735
+ openNativeCommandDialog({ title: "Tools Setup", message: "Enable or disable tool access for this session, or save a global or exact-model default.", searchPlaceholder: "Filter tools…" });
41015
41736
  let tools = [];
41016
41737
  let savingName = "";
41017
41738
  let filter = "all";
41018
41739
  let scope = "session";
41019
41740
  let configured = false;
41741
+ let models = [];
41742
+ let modelIndex = 0;
41743
+
41744
+ const modelQuery = () => scope === "model" && models[modelIndex]
41745
+ ? `&provider=${encodeURIComponent(models[modelIndex].provider)}&modelId=${encodeURIComponent(models[modelIndex].id)}`
41746
+ : "";
41020
41747
 
41021
41748
  const load = async () => {
41022
- renderNativeLoading(`Loading ${scope === "global" ? "global tool defaults" : "session tools"}…`);
41749
+ renderNativeLoading(`Loading ${scope === "global" ? "global tool defaults" : scope === "model" ? "model tool defaults" : "session tools"}…`);
41023
41750
  try {
41024
- const response = await nativeCommandApi(`/api/tools?scope=${encodeURIComponent(scope)}`);
41751
+ const response = await nativeCommandApi(`/api/tools?scope=${encodeURIComponent(scope)}${modelQuery()}`);
41025
41752
  tools = Array.isArray(response.data?.tools) ? response.data.tools : [];
41026
41753
  configured = response.data?.configured === true;
41754
+ if (scope === "model" && Array.isArray(response.data?.models)) models = response.data.models;
41027
41755
  render();
41028
41756
  } catch (error) {
41029
41757
  setNativeCommandError(error.message || String(error));
@@ -41031,6 +41759,51 @@ async function openNativeToolsSelector() {
41031
41759
  }
41032
41760
  };
41033
41761
 
41762
+ const applyModelScope = async () => {
41763
+ if (!models.length) {
41764
+ try {
41765
+ models = await loadNativeResourceModels();
41766
+ } catch (error) {
41767
+ setNativeCommandError(error.message || String(error));
41768
+ return false;
41769
+ }
41770
+ }
41771
+ if (!models.length) {
41772
+ setNativeCommandError("No authenticated Pi models are available for a model default.");
41773
+ return false;
41774
+ }
41775
+ modelIndex = Math.min(Math.max(modelIndex, 0), models.length - 1);
41776
+ return true;
41777
+ };
41778
+
41779
+ const inheritSelection = async () => {
41780
+ if (savingName) return;
41781
+ savingName = "inherit";
41782
+ setNativeCommandError("");
41783
+ render();
41784
+ try {
41785
+ const body = { scope, inherit: true };
41786
+ if (scope === "model" && models[modelIndex]) {
41787
+ body.provider = models[modelIndex].provider;
41788
+ body.modelId = models[modelIndex].id;
41789
+ }
41790
+ const response = await nativeCommandApi("/api/tools", { method: "POST", body });
41791
+ tools = Array.isArray(response.data?.tools) ? response.data.tools : [];
41792
+ configured = response.data?.configured === true;
41793
+ const content = scope === "model"
41794
+ ? `Tool default for ${body.provider}/${body.modelId} cleared. It now inherits the global or Pi runtime default.`
41795
+ : scope === "global"
41796
+ ? "Global tool default cleared. Unpinned active tools now follow the Pi runtime default; pinned tools are unchanged."
41797
+ : "Tools for this session now follow the inherited model, global, or Pi runtime defaults.";
41798
+ addTransientMessage({ role: "native", title: "/tools", content, level: "info" });
41799
+ } catch (error) {
41800
+ setNativeCommandError(error.message || String(error));
41801
+ } finally {
41802
+ savingName = "";
41803
+ render();
41804
+ }
41805
+ };
41806
+
41034
41807
  const render = () => {
41035
41808
  renderNativeResourceToggles(tools, {
41036
41809
  savingName,
@@ -41045,13 +41818,20 @@ async function openNativeToolsSelector() {
41045
41818
  setNativeCommandError("");
41046
41819
  render();
41047
41820
  try {
41048
- const response = await nativeCommandApi("/api/tools", { method: "POST", body: { enabledTools: [...enabledTools], scope } });
41821
+ const body = { enabledTools: [...enabledTools], scope };
41822
+ if (scope === "model" && models[modelIndex]) {
41823
+ body.provider = models[modelIndex].provider;
41824
+ body.modelId = models[modelIndex].id;
41825
+ }
41826
+ const response = await nativeCommandApi("/api/tools", { method: "POST", body });
41049
41827
  tools = Array.isArray(response.data?.tools) ? response.data.tools : [];
41050
41828
  configured = response.data?.configured === true;
41051
41829
  const enabled = enabledTools.has(tool.name);
41052
- const content = scope === "global"
41053
- ? `Global default for tool ${tool.name} ${enabled ? "enabled" : "disabled"}. Future sessions inherit it; this session is unchanged.`
41054
- : `Tool ${tool.name} ${enabled ? "enabled" : "disabled"} for this session.`;
41830
+ const content = scope === "model"
41831
+ ? `Model default for tool ${tool.name} ${enabled ? "enabled" : "disabled"} (${body.provider}/${body.modelId}). Unpinned active tools update immediately when this model is active; pinned tools are unchanged.`
41832
+ : scope === "global"
41833
+ ? `Global default for tool ${tool.name} ${enabled ? "enabled" : "disabled"}. Unpinned active tools update immediately; pinned tools are unchanged.`
41834
+ : `Tool ${tool.name} ${enabled ? "enabled" : "disabled"} for this session.`;
41055
41835
  addTransientMessage({ role: "native", title: "/tools", content, level: "info" });
41056
41836
  } catch (error) {
41057
41837
  setNativeCommandError(error.message || String(error));
@@ -41061,16 +41841,32 @@ async function openNativeToolsSelector() {
41061
41841
  }
41062
41842
  },
41063
41843
  });
41844
+ if (scope === "model" && models.length) {
41845
+ elements.nativeCommandBody.prepend(nativeResourceModelControl(models, modelIndex, {
41846
+ saving: !!savingName,
41847
+ onChange: async (nextIndex) => {
41848
+ if (nextIndex === modelIndex || savingName || !models[nextIndex]) return;
41849
+ modelIndex = nextIndex;
41850
+ await load();
41851
+ },
41852
+ }));
41853
+ }
41064
41854
  elements.nativeCommandBody.prepend(nativeResourceScopeControl(scope, {
41065
41855
  configured,
41066
41856
  saving: !!savingName,
41067
41857
  onChange: async (nextScope) => {
41068
41858
  if (nextScope === scope || savingName) return;
41859
+ if (nextScope === "model" && !(await applyModelScope())) {
41860
+ render();
41861
+ return;
41862
+ }
41069
41863
  scope = nextScope;
41070
41864
  await load();
41071
41865
  },
41072
41866
  }));
41073
- renderNativeResourceFilterActions(filter, (value) => { filter = value; }, render);
41867
+ renderNativeResourceFilterActions(filter, (value) => { filter = value; }, render, [
41868
+ { label: "Use inherited defaults", handler: inheritSelection, disabled: !!savingName },
41869
+ ]);
41074
41870
  };
41075
41871
 
41076
41872
  elements.nativeCommandSearch.oninput = render;
@@ -41078,19 +41874,26 @@ async function openNativeToolsSelector() {
41078
41874
  }
41079
41875
 
41080
41876
  async function openNativeSkillsSelector() {
41081
- openNativeCommandDialog({ title: "Skills Setup", message: "Enable or disable skill invocation for this session or save a default for future sessions.", searchPlaceholder: "Filter skills…" });
41877
+ openNativeCommandDialog({ title: "Skills Setup", message: "Enable or disable skill invocation for this session, or save a global or exact-model default.", searchPlaceholder: "Filter skills…" });
41082
41878
  let skills = [];
41083
41879
  let savingName = "";
41084
41880
  let filter = "all";
41085
41881
  let scope = "session";
41086
41882
  let configured = false;
41883
+ let models = [];
41884
+ let modelIndex = 0;
41885
+
41886
+ const modelQuery = () => scope === "model" && models[modelIndex]
41887
+ ? `&provider=${encodeURIComponent(models[modelIndex].provider)}&modelId=${encodeURIComponent(models[modelIndex].id)}`
41888
+ : "";
41087
41889
 
41088
41890
  const load = async () => {
41089
- renderNativeLoading(`Loading ${scope === "global" ? "global skill defaults" : "session skills"}…`);
41891
+ renderNativeLoading(`Loading ${scope === "global" ? "global skill defaults" : scope === "model" ? "model skill defaults" : "session skills"}…`);
41090
41892
  try {
41091
- const response = await nativeCommandApi(`/api/skills?scope=${encodeURIComponent(scope)}`);
41893
+ const response = await nativeCommandApi(`/api/skills?scope=${encodeURIComponent(scope)}${modelQuery()}`);
41092
41894
  skills = Array.isArray(response.data?.skills) ? response.data.skills : [];
41093
41895
  configured = response.data?.configured === true;
41896
+ if (scope === "model" && Array.isArray(response.data?.models)) models = response.data.models;
41094
41897
  render();
41095
41898
  } catch (error) {
41096
41899
  setNativeCommandError(error.message || String(error));
@@ -41098,6 +41901,52 @@ async function openNativeSkillsSelector() {
41098
41901
  }
41099
41902
  };
41100
41903
 
41904
+ const applyModelScope = async () => {
41905
+ if (!models.length) {
41906
+ try {
41907
+ models = await loadNativeResourceModels();
41908
+ } catch (error) {
41909
+ setNativeCommandError(error.message || String(error));
41910
+ return false;
41911
+ }
41912
+ }
41913
+ if (!models.length) {
41914
+ setNativeCommandError("No authenticated Pi models are available for a model default.");
41915
+ return false;
41916
+ }
41917
+ modelIndex = Math.min(Math.max(modelIndex, 0), models.length - 1);
41918
+ return true;
41919
+ };
41920
+
41921
+ const inheritSelection = async () => {
41922
+ if (savingName) return;
41923
+ savingName = "inherit";
41924
+ setNativeCommandError("");
41925
+ render();
41926
+ try {
41927
+ const body = { scope, inherit: true };
41928
+ if (scope === "model" && models[modelIndex]) {
41929
+ body.provider = models[modelIndex].provider;
41930
+ body.modelId = models[modelIndex].id;
41931
+ }
41932
+ const response = await nativeCommandApi("/api/skills", { method: "POST", body });
41933
+ skills = Array.isArray(response.data?.skills) ? response.data.skills : [];
41934
+ configured = response.data?.configured === true;
41935
+ const content = scope === "model"
41936
+ ? `Skill default for ${body.provider}/${body.modelId} cleared. It now inherits the global or Pi runtime default.`
41937
+ : scope === "global"
41938
+ ? "Global skill default cleared. Unpinned active skills now follow the Pi runtime default; pinned skills are unchanged."
41939
+ : "Skills for this session now follow the inherited model, global, or Pi runtime defaults.";
41940
+ addTransientMessage({ role: "native", title: "/skills", content, level: "info" });
41941
+ if (scope === "session") refreshCommands(activeTabContext()).catch((error) => addEvent(error.message || String(error), "error"));
41942
+ } catch (error) {
41943
+ setNativeCommandError(error.message || String(error));
41944
+ } finally {
41945
+ savingName = "";
41946
+ render();
41947
+ }
41948
+ };
41949
+
41101
41950
  const render = () => {
41102
41951
  renderNativeResourceToggles(skills, {
41103
41952
  savingName,
@@ -41111,13 +41960,20 @@ async function openNativeSkillsSelector() {
41111
41960
  setNativeCommandError("");
41112
41961
  render();
41113
41962
  try {
41114
- const response = await nativeCommandApi("/api/skills", { method: "POST", body: { enabledSkills: [...enabledSkills], scope } });
41963
+ const body = { enabledSkills: [...enabledSkills], scope };
41964
+ if (scope === "model" && models[modelIndex]) {
41965
+ body.provider = models[modelIndex].provider;
41966
+ body.modelId = models[modelIndex].id;
41967
+ }
41968
+ const response = await nativeCommandApi("/api/skills", { method: "POST", body });
41115
41969
  skills = Array.isArray(response.data?.skills) ? response.data.skills : [];
41116
41970
  configured = response.data?.configured === true;
41117
41971
  const enabled = enabledSkills.has(skill.name);
41118
- const content = scope === "global"
41119
- ? `Global default for skill ${skill.name} ${enabled ? "enabled" : "disabled"}. Future sessions inherit it; this session is unchanged.`
41120
- : `Skill ${skill.name} ${enabled ? "enabled" : "disabled"} for this session.`;
41972
+ const content = scope === "model"
41973
+ ? `Model default for skill ${skill.name} ${enabled ? "enabled" : "disabled"} (${body.provider}/${body.modelId}). Unpinned active skills update immediately when this model is active; pinned skills are unchanged.`
41974
+ : scope === "global"
41975
+ ? `Global default for skill ${skill.name} ${enabled ? "enabled" : "disabled"}. Unpinned active skills update immediately; pinned skills are unchanged.`
41976
+ : `Skill ${skill.name} ${enabled ? "enabled" : "disabled"} for this session.`;
41121
41977
  addTransientMessage({ role: "native", title: "/skills", content, level: "info" });
41122
41978
  if (scope === "session") refreshCommands(activeTabContext()).catch((error) => addEvent(error.message || String(error), "error"));
41123
41979
  } catch (error) {
@@ -41128,16 +41984,32 @@ async function openNativeSkillsSelector() {
41128
41984
  }
41129
41985
  },
41130
41986
  });
41987
+ if (scope === "model" && models.length) {
41988
+ elements.nativeCommandBody.prepend(nativeResourceModelControl(models, modelIndex, {
41989
+ saving: !!savingName,
41990
+ onChange: async (nextIndex) => {
41991
+ if (nextIndex === modelIndex || savingName || !models[nextIndex]) return;
41992
+ modelIndex = nextIndex;
41993
+ await load();
41994
+ },
41995
+ }));
41996
+ }
41131
41997
  elements.nativeCommandBody.prepend(nativeResourceScopeControl(scope, {
41132
41998
  configured,
41133
41999
  saving: !!savingName,
41134
42000
  onChange: async (nextScope) => {
41135
42001
  if (nextScope === scope || savingName) return;
42002
+ if (nextScope === "model" && !(await applyModelScope())) {
42003
+ render();
42004
+ return;
42005
+ }
41136
42006
  scope = nextScope;
41137
42007
  await load();
41138
42008
  },
41139
42009
  }));
41140
- renderNativeResourceFilterActions(filter, (value) => { filter = value; }, render);
42010
+ renderNativeResourceFilterActions(filter, (value) => { filter = value; }, render, [
42011
+ { label: "Use inherited defaults", handler: inheritSelection, disabled: !!savingName },
42012
+ ]);
41141
42013
  };
41142
42014
 
41143
42015
  elements.nativeCommandSearch.oninput = render;
@@ -41950,8 +42822,11 @@ function streamingThinkingTextFallback(event) {
41950
42822
  return assistantThinkingTextFromMessage(assistantStreamingMessage(event), { streaming: true });
41951
42823
  }
41952
42824
 
41953
- function setStreamThinkingRawText(text) {
41954
- const thinking = visibleThinkingText(text);
42825
+ function setStreamThinkingRawText(text, { reconcile = false } = {}) {
42826
+ const snapshot = visibleThinkingText(text);
42827
+ const thinking = reconcile
42828
+ ? reconcileTranscriptThinkingSnapshot(streamThinkingRawText, snapshot)
42829
+ : snapshot;
41955
42830
  if (thinking === streamThinkingRawText) return false;
41956
42831
  streamThinkingRawText = thinking;
41957
42832
  return true;
@@ -41976,10 +42851,10 @@ function syncStreamingThinkingFromUpdate(event, update, { placeholder = "" } = {
41976
42851
  return streamThinkingRawText ? setStreamingThinkingText(streamThinkingRawText || placeholder) : false;
41977
42852
  }
41978
42853
  if (update.type === "thinking_end") {
41979
- if (delta) setStreamThinkingRawText(delta);
42854
+ if (delta) setStreamThinkingRawText(delta, { reconcile: true });
41980
42855
  else {
41981
42856
  const fallback = streamingThinkingTextFallback(event);
41982
- if (fallback !== null) setStreamThinkingRawText(fallback);
42857
+ if (fallback !== null) setStreamThinkingRawText(fallback, { reconcile: true });
41983
42858
  }
41984
42859
  return setStreamingThinkingText(streamThinkingRawText || placeholder);
41985
42860
  }
@@ -42310,45 +43185,86 @@ function mergeMessagesDelta(previous, data) {
42310
43185
  return previous.slice(0, since).concat(data.messages);
42311
43186
  }
42312
43187
 
42313
- async function refreshMessages(tabContext = activeTabContext(), { authoritative = false } = {}) {
42314
- if (!tabContext.tabId) return;
42315
- const previousMessages = latestMessages;
42316
- const sessionKey = resolveMessagesSessionKey(tabContext.tabId);
42317
- let nextMessages = null;
42318
- if (!authoritative && previousMessages.length > 1 && sessionKey === latestMessagesSessionKey) {
42319
- // Delta fetch with a one-message overlap: the last known message is
42320
- // re-requested so retroactive changes are detected via mergeMessagesDelta.
42321
- const response = await api(`/api/messages?since=${previousMessages.length - 1}`, { tabId: tabContext.tabId });
42322
- if (!isCurrentTabContext(tabContext)) return;
42323
- nextMessages = mergeMessagesDelta(previousMessages, response.data);
43188
+ function mainOutputLoadingRequestIsCurrent(request) {
43189
+ return !!request?.tabContext && isCurrentTabContext(request.tabContext);
43190
+ }
43191
+
43192
+ function renderMainOutputLoading({ reveal = false } = {}) {
43193
+ const active = [...mainOutputLoadingRequests].some(mainOutputLoadingRequestIsCurrent);
43194
+ elements.chat?.setAttribute("aria-busy", active ? "true" : "false");
43195
+ clearTimeout(mainOutputLoadingRevealTimer);
43196
+ mainOutputLoadingRevealTimer = null;
43197
+ if (!elements.mainOutputLoading) return;
43198
+ if (!active) {
43199
+ elements.mainOutputLoading.hidden = true;
43200
+ return;
42324
43201
  }
42325
- if (!nextMessages) {
42326
- const response = await api("/api/messages", { tabId: tabContext.tabId });
42327
- if (!isCurrentTabContext(tabContext)) return;
42328
- nextMessages = response.data?.messages || [];
43202
+ if (reveal) {
43203
+ elements.mainOutputLoading.hidden = false;
43204
+ return;
42329
43205
  }
42330
- latestMessages = nextMessages;
42331
- latestMessagesSessionKey = sessionKey;
42332
- cacheMessagesForTab(tabContext.tabId, latestMessages, latestMessagesSessionKey);
42333
- const selectionSnapshot = captureChatTextSelection();
42334
- const preserveCompactStream = compactLiveStreamRenderActive();
42335
- const preserveNormalStream = !preserveCompactStream && liveStreamRenderActive();
42336
- if (!preserveCompactStream && !preserveNormalStream) {
42337
- const adoptedOutput = adoptLiveAssistantBubble(latestMessages);
42338
- resetStreamBubble({ preserveCompact: adoptedOutput === "compact" });
43206
+ mainOutputLoadingRevealTimer = setTimeout(() => {
43207
+ mainOutputLoadingRevealTimer = null;
43208
+ if ([...mainOutputLoadingRequests].some(mainOutputLoadingRequestIsCurrent)) elements.mainOutputLoading.hidden = false;
43209
+ }, MAIN_OUTPUT_LOADING_REVEAL_DELAY_MS);
43210
+ }
43211
+
43212
+ function beginMainOutputLoading(tabContext) {
43213
+ const request = { tabContext: { ...tabContext } };
43214
+ mainOutputLoadingRequests.add(request);
43215
+ renderMainOutputLoading();
43216
+ return request;
43217
+ }
43218
+
43219
+ function finishMainOutputLoading(request) {
43220
+ mainOutputLoadingRequests.delete(request);
43221
+ renderMainOutputLoading();
43222
+ }
43223
+
43224
+ async function refreshMessages(tabContext = activeTabContext(), { authoritative = false } = {}) {
43225
+ if (!tabContext.tabId) return;
43226
+ const loadingRequest = beginMainOutputLoading(tabContext);
43227
+ try {
43228
+ const previousMessages = latestMessages;
43229
+ const sessionKey = resolveMessagesSessionKey(tabContext.tabId);
43230
+ let nextMessages = null;
43231
+ if (!authoritative && previousMessages.length > 1 && sessionKey === latestMessagesSessionKey) {
43232
+ // Delta fetch with a one-message overlap: the last known message is
43233
+ // re-requested so retroactive changes are detected via mergeMessagesDelta.
43234
+ const response = await api(`/api/messages?since=${previousMessages.length - 1}`, { tabId: tabContext.tabId });
43235
+ if (!isCurrentTabContext(tabContext)) return;
43236
+ nextMessages = mergeMessagesDelta(previousMessages, response.data);
43237
+ }
43238
+ if (!nextMessages) {
43239
+ const response = await api("/api/messages", { tabId: tabContext.tabId });
43240
+ if (!isCurrentTabContext(tabContext)) return;
43241
+ nextMessages = response.data?.messages || [];
43242
+ }
43243
+ latestMessages = nextMessages;
43244
+ latestMessagesSessionKey = sessionKey;
43245
+ cacheMessagesForTab(tabContext.tabId, latestMessages, latestMessagesSessionKey);
43246
+ const selectionSnapshot = captureChatTextSelection();
43247
+ const preserveCompactStream = compactLiveStreamRenderActive();
43248
+ const preserveNormalStream = !preserveCompactStream && liveStreamRenderActive();
43249
+ if (!preserveCompactStream && !preserveNormalStream) {
43250
+ const adoptedOutput = adoptLiveAssistantBubble(latestMessages);
43251
+ resetStreamBubble({ preserveCompact: adoptedOutput === "compact" });
43252
+ }
43253
+ renderMessages(latestMessages);
43254
+ if (preserveCompactStream) restoreCompactLiveOutputAfterChatRebuild();
43255
+ else if (preserveNormalStream) restoreStreamRenderAfterChatRebuild();
43256
+ restoreChatTextSelection(selectionSnapshot);
43257
+ markTabOutputSeen();
43258
+ // Authoritative content just landed: derive the todo-progress record once
43259
+ // here instead of from raw token cadence, and let the coalesced semantic
43260
+ // reconciler own the footer/widget chrome that message data can change.
43261
+ // syncLiveTodoProgressWidgetFromText owns the frame-coalesced widget render
43262
+ // and only fires when the parsed checklist value actually changed.
43263
+ reconcileTodoProgressFromMessages(latestMessages, tabContext.tabId);
43264
+ scheduleSemanticReconcile({ footer: true }, tabContext);
43265
+ } finally {
43266
+ finishMainOutputLoading(loadingRequest);
42339
43267
  }
42340
- renderMessages(latestMessages);
42341
- if (preserveCompactStream) restoreCompactLiveOutputAfterChatRebuild();
42342
- else if (preserveNormalStream) restoreStreamRenderAfterChatRebuild();
42343
- restoreChatTextSelection(selectionSnapshot);
42344
- markTabOutputSeen();
42345
- // Authoritative content just landed: derive the todo-progress record once
42346
- // here instead of from raw token cadence, and let the coalesced semantic
42347
- // reconciler own the footer/widget chrome that message data can change.
42348
- // syncLiveTodoProgressWidgetFromText owns the frame-coalesced widget render
42349
- // and only fires when the parsed checklist value actually changed.
42350
- reconcileTodoProgressFromMessages(latestMessages, tabContext.tabId);
42351
- scheduleSemanticReconcile({ footer: true }, tabContext);
42352
43268
  }
42353
43269
 
42354
43270
  async function refreshModels(tabContext = activeTabContext()) {
@@ -43354,6 +44270,7 @@ async function refreshAll(tabContext = activeTabContext()) {
43354
44270
  const results = await Promise.allSettled([
43355
44271
  refreshState(tabContext),
43356
44272
  refreshMessages(tabContext),
44273
+ refreshIntercomConversationSummaries(tabContext),
43357
44274
  ...supplementalRefreshRequests(tabContext),
43358
44275
  ]);
43359
44276
  if (!isCurrentTabContext(tabContext)) return;
@@ -44107,6 +45024,11 @@ function handleExtensionUiRequest(request) {
44107
45024
  case "setWidget": {
44108
45025
  const widgetKey = request.widgetKey || request.id;
44109
45026
  const requestTabId = request.tabId || activeTabId;
45027
+ if (widgetKey === SUBAGENT_ASYNC_WIDGET_KEY) {
45028
+ const changed = setWidgetForTab(requestTabId, widgetKey, { ...request, widgetLines: undefined });
45029
+ if (changed && requestTabId === activeTabId) renderWidgets();
45030
+ return;
45031
+ }
44110
45032
  if (widgetKey === WORKFLOW_MODE_RPC_WIDGET_KEY) {
44111
45033
  const modeState = workflowModeStateFromRpcPayload(request.widgetLines);
44112
45034
  if (modeState) updateWorkflowModeForTab(requestTabId, modeState, { render: requestTabId === activeTabId });
@@ -44719,6 +45641,7 @@ function handleEvent(event) {
44719
45641
  return;
44720
45642
  }
44721
45643
  const tabContext = activeTabContext(event.tabId || activeTabId);
45644
+ if (["webui_connected", "agent_end", "message_end", "tool_execution_end"].includes(event.type)) scheduleIntercomConversationRefresh(tabContext);
44722
45645
  switch (event.type) {
44723
45646
  case "webui_connected": {
44724
45647
  const connectedTabId = event.tabId || activeTabId;
@@ -44942,6 +45865,11 @@ function handleEvent(event) {
44942
45865
  case "tool_execution_start":
44943
45866
  streamToolCallSeen = true;
44944
45867
  if (voiceConversationActiveFor(event.tabId || activeTabId)) voiceConversation.setAssistantActivity({ toolRunning: true });
45868
+ if (isIntercomTransportToolName(event.toolName)) {
45869
+ resetStreamingToolCallState({ remove: true });
45870
+ setRunIndicatorActivity("Agent is coordinating with another agent…");
45871
+ break;
45872
+ }
44945
45873
  if (compactOutputActive()) {
44946
45874
  compactLiveScheduler.flushNow();
44947
45875
  renderCompactToolShell(event);
@@ -44955,6 +45883,12 @@ function handleEvent(event) {
44955
45883
  break;
44956
45884
  case "tool_execution_end": {
44957
45885
  if (voiceConversationActiveFor(event.tabId || activeTabId)) voiceConversation.setAssistantActivity({ toolRunning: false });
45886
+ if (isIntercomTransportToolName(event.toolName)) {
45887
+ resetStreamingToolCallState({ remove: true });
45888
+ setRunIndicatorActivity("Agent coordination finished; waiting for the next step…");
45889
+ scheduleSemanticReconcile({ messages: true, footerData: true }, tabContext);
45890
+ break;
45891
+ }
44958
45892
  const imagePayloadError = toolImagePayloadError(event);
44959
45893
  if (imagePayloadError) surfaceRuntimeDiagnostic("Tool image payload error", imagePayloadError);
44960
45894
  if (compactOutputActive()) {
@@ -45093,6 +46027,7 @@ function connectEvents(tabContext = activeTabContext(), { requestedMode = "auto"
45093
46027
  source.onopen = () => {
45094
46028
  if (eventSource !== source || !isCurrentTabContext(tabContext)) return;
45095
46029
  if (!eventStreamPausedForBackground) refreshOptionalFeaturePackageStatuses().catch(() => {});
46030
+ scheduleIntercomConversationRefresh(tabContext, 0);
45096
46031
  };
45097
46032
  source.onmessage = (message) => {
45098
46033
  if (eventSource !== source || !isCurrentTabContext(tabContext)) return;
@@ -45167,6 +46102,11 @@ elements.skillEditorDialog?.addEventListener("keydown", (event) => {
45167
46102
  if (!elements.skillEditorSaveButton?.disabled) saveSkillEditor();
45168
46103
  });
45169
46104
  elements.skillEditorDialog?.querySelector("form")?.addEventListener("submit", (event) => event.preventDefault());
46105
+ elements.intercomConversationDialog?.addEventListener("close", resetIntercomConversationDialog);
46106
+ elements.intercomConversationDialog?.addEventListener("cancel", () => {
46107
+ clearTimeout(intercomDetailRefreshTimer);
46108
+ intercomDetailRefreshTimer = null;
46109
+ });
45170
46110
  elements.featureCategoryTag?.addEventListener("click", openFeatureDecisionDialog);
45171
46111
  elements.featureDecisionDialog?.addEventListener("close", () => {
45172
46112
  featureDecisionDialogTabId = null;
@@ -45461,6 +46401,8 @@ elements.optionsSummarySetupButton?.addEventListener("click", () => runNativeCom
45461
46401
  elements.optionsWorkflowSetupButton?.addEventListener("click", () => runNativeCommandMenu("/workflow-setup"));
45462
46402
  elements.optionsSafetyGuardSetupButton?.addEventListener("click", () => runNativeCommandMenu("/safety-guard-setup"));
45463
46403
  elements.optionsGitWorkflowSetupButton?.addEventListener("click", () => runNativeCommandMenu("/git-workflow-setup"));
46404
+ elements.optionsToolsSetupButton?.addEventListener("click", () => runNativeCommandMenu("/tools"));
46405
+ elements.optionsSkillsSetupButton?.addEventListener("click", () => runNativeCommandMenu("/skills"));
45464
46406
  elements.optionsExportButton.addEventListener("click", () => runNativeCommandMenu("/export"));
45465
46407
  elements.optionsForkButton.addEventListener("click", () => runNativeCommandMenu("/fork"));
45466
46408
  elements.optionsTreeButton.addEventListener("click", () => runNativeCommandMenu("/tree"));