@firstpick/pi-package-webui 0.9.4 → 0.9.5

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 (42) hide show
  1. package/README.md +3 -0
  2. package/lib/ui-layout-settings.mjs +37 -6
  3. package/package.json +1 -1
  4. package/public/app.js +499 -6
  5. package/public/index.html +33 -26
  6. package/public/service-worker.js +1 -1
  7. package/public/stream-output-controller.mjs +31 -2
  8. package/public/styles.css +27 -2
  9. package/tests/boot-failure-diagnostics.test.mjs +3 -3
  10. package/tests/browser/control-deck-side-panels.spec.mjs +42 -0
  11. package/tests/browser/control-visibility.spec.mjs +396 -0
  12. package/tests/browser/persistent-ui-layout.spec.mjs +9 -9
  13. package/tests/codex-fast-mode-static.test.mjs +2 -2
  14. package/tests/composer-action-grid-reorder-static.test.mjs +3 -3
  15. package/tests/control-deck-side-panels-static.test.mjs +3 -1
  16. package/tests/control-visibility-static.test.mjs +294 -0
  17. package/tests/controls-layout-static.test.mjs +3 -3
  18. package/tests/fast-mode-client-static.test.mjs +1 -1
  19. package/tests/feature-decision-output-popup-static.test.mjs +2 -2
  20. package/tests/file-viewer-image-static.test.mjs +3 -3
  21. package/tests/fixtures/streaming-workloads.mjs +131 -0
  22. package/tests/git-workflow-preferences.test.mjs +2 -2
  23. package/tests/http-endpoints-harness.test.mjs +4 -4
  24. package/tests/intercom-conversation-viewer-static.test.mjs +4 -4
  25. package/tests/main-output-loading-static.test.mjs +3 -3
  26. package/tests/middle-button-drag-scroll-static.test.mjs +3 -3
  27. package/tests/mobile-continuity-tablet-static.test.mjs +3 -3
  28. package/tests/mobile-foundation-static.test.mjs +3 -3
  29. package/tests/mobile-phone-experience-static.test.mjs +1 -1
  30. package/tests/mobile-static.test.mjs +3 -3
  31. package/tests/open-issue-wizard-static.test.mjs +2 -2
  32. package/tests/persistent-ui-layout-static.test.mjs +6 -6
  33. package/tests/questionnaire-dialog.test.mjs +3 -3
  34. package/tests/session-sampling-ui-static.test.mjs +3 -3
  35. package/tests/side-panel-section-height-removal-static.test.mjs +3 -3
  36. package/tests/stream-output-isolation-static.test.mjs +7 -0
  37. package/tests/stream-output-workloads.test.mjs +239 -0
  38. package/tests/subagent-observability-static.test.mjs +2 -2
  39. package/tests/syntax-highlighting-static.test.mjs +3 -3
  40. package/tests/theme-customizer-static.test.mjs +1 -1
  41. package/tests/ui-layout-settings.test.mjs +54 -7
  42. package/tests/webui-settings-locking.test.mjs +3 -3
package/public/app.js CHANGED
@@ -350,6 +350,7 @@ const elements = {
350
350
  fileSelectionSendButton: $("#fileSelectionSendButton"),
351
351
  fileContextMenu: $("#fileContextMenu"),
352
352
  sidePanelContextMenu: $("#sidePanelContextMenu"),
353
+ visibilityContextMenu: $("#visibilityContextMenu"),
353
354
  gitFooterContextMenu: $("#gitFooterContextMenu"),
354
355
  sidePanelResizeHandle: $("#sidePanelResizeHandle"),
355
356
  sidePanelResizeHandleLeft: $("#sidePanelLeftResizeHandle"),
@@ -668,7 +669,7 @@ const STREAM_ISOLATION_DEBUG_LIMIT = 4096;
668
669
  const STREAM_ISOLATION_DEBUG_ENABLED = globalThis.__PI_STREAM_ISOLATION_DEBUG__ === true
669
670
  || new URLSearchParams(window.location.search).get("streamIsolationDebug") === "1";
670
671
  const streamIsolationDebugLedger = STREAM_ISOLATION_DEBUG_ENABLED ? {
671
- version: 1,
672
+ version: 2,
672
673
  counters: {
673
674
  receivedEvents: 0,
674
675
  appliedEvents: 0,
@@ -680,7 +681,28 @@ const streamIsolationDebugLedger = STREAM_ISOLATION_DEBUG_ENABLED ? {
680
681
  staleEvents: 0,
681
682
  highWaterPendingCount: 0,
682
683
  highWaterPendingBytes: 0,
684
+ // Version 2 streaming-performance baseline counters (webui-output-streaming plan, Phase 0).
685
+ batchLatencyMaxMs: 0,
686
+ batchDrainMaxMs: 0,
687
+ batchPaintMaxMs: 0,
688
+ transcriptNodeMax: 0,
689
+ currentMessageNodeMax: 0,
690
+ deriveCalls: 0,
691
+ deriveMaxBytes: 0,
692
+ deriveMaxMs: 0,
693
+ tokenizeCalls: 0,
694
+ tokenizeMaxBytes: 0,
695
+ tokenizeMaxMs: 0,
696
+ markdownCommits: 0,
697
+ markdownCommitMaxMs: 0,
698
+ tailMaxBytes: 0,
699
+ longTasks: 0,
700
+ longAnimationFrames: 0,
701
+ focusLossNearStreamBatch: 0,
702
+ detachedScrollMoves: 0,
683
703
  },
704
+ lastBatchAppliedAt: 0,
705
+ lastChatScrollTop: undefined,
684
706
  receivedIndexes: [],
685
707
  appliedIndexes: [],
686
708
  records: [],
@@ -714,6 +736,10 @@ function recordStreamIsolationDiagnostic(record) {
714
736
  if (record.kind === "unknown-message-update") counters.unknownEvents += Number(record.sourceCount) || 1;
715
737
  } else if (record.type === "batch") {
716
738
  counters.batches += 1;
739
+ counters.batchLatencyMaxMs = Math.max(counters.batchLatencyMaxMs, Number(record.maxAgeMs) || 0);
740
+ counters.batchDrainMaxMs = Math.max(counters.batchDrainMaxMs, Number(record.drainMs) || 0);
741
+ ledger.lastBatchAppliedAt = performance.now();
742
+ scheduleStreamPaintDiagnostic(record);
717
743
  } else if (record.type === "barrier") {
718
744
  counters.barriers += 1;
719
745
  } else if (record.type === "overflow") {
@@ -731,12 +757,120 @@ function recordStreamIsolationDiagnostic(record) {
731
757
  });
732
758
  }
733
759
 
760
+ /**
761
+ * Streaming-performance profile records for the opt-in debug ledger. Every
762
+ * caller guards on `streamIsolationDebugLedger` before doing measurement work,
763
+ * so the disabled hot path pays only one falsy check per instrumented site.
764
+ */
765
+ function streamDiagnosticBytes(value) {
766
+ // Match the controller's conservative UTF-16 queue accounting.
767
+ return String(value || "").length * 2;
768
+ }
769
+
770
+ function recordStreamProfileDiagnostic(record) {
771
+ const ledger = streamIsolationDebugLedger;
772
+ if (!ledger || !record) return;
773
+ const counters = ledger.counters;
774
+ if (record.type === "derive") {
775
+ counters.deriveCalls += 1;
776
+ counters.deriveMaxBytes = Math.max(counters.deriveMaxBytes, Number(record.bytes) || 0);
777
+ counters.deriveMaxMs = Math.max(counters.deriveMaxMs, Number(record.ms) || 0);
778
+ } else if (record.type === "tokenize") {
779
+ counters.tokenizeCalls += 1;
780
+ counters.tokenizeMaxBytes = Math.max(counters.tokenizeMaxBytes, Number(record.bytes) || 0);
781
+ counters.tokenizeMaxMs = Math.max(counters.tokenizeMaxMs, Number(record.ms) || 0);
782
+ } else if (record.type === "markdown-commit") {
783
+ counters.markdownCommits += 1;
784
+ counters.markdownCommitMaxMs = Math.max(counters.markdownCommitMaxMs, Number(record.ms) || 0);
785
+ counters.tailMaxBytes = Math.max(counters.tailMaxBytes, Number(record.tailBytes) || 0);
786
+ } else if (record.type === "paint-opportunity") {
787
+ counters.batchPaintMaxMs = Math.max(counters.batchPaintMaxMs, Number(record.ms) || 0);
788
+ counters.transcriptNodeMax = Math.max(counters.transcriptNodeMax, Number(record.transcriptNodes) || 0);
789
+ counters.currentMessageNodeMax = Math.max(counters.currentMessageNodeMax, Number(record.currentMessageNodes) || 0);
790
+ } else if (record.type === "longtask") {
791
+ counters.longTasks += 1;
792
+ } else if (record.type === "long-animation-frame") {
793
+ counters.longAnimationFrames += 1;
794
+ } else if (record.type === "focus-loss") {
795
+ counters.focusLossNearStreamBatch += 1;
796
+ } else if (record.type === "detached-scroll") {
797
+ counters.detachedScrollMoves += 1;
798
+ }
799
+ appendBoundedStreamDiagnostic(ledger.records, record);
800
+ }
801
+
802
+ function scheduleStreamPaintDiagnostic(batchRecord) {
803
+ if (!streamIsolationDebugLedger || typeof requestAnimationFrame !== "function") return;
804
+ const scheduledAt = performance.now();
805
+ requestAnimationFrame(() => {
806
+ const activeMessage = streamBubble?.isConnected
807
+ ? streamBubble
808
+ : streamThinkingBubble?.isConnected
809
+ ? streamThinkingBubble
810
+ : compactTextBubble?.isConnected
811
+ ? compactTextBubble
812
+ : compactThinkingBubble?.isConnected
813
+ ? compactThinkingBubble
814
+ : null;
815
+ recordStreamProfileDiagnostic({
816
+ type: "paint-opportunity",
817
+ ms: (Number(batchRecord.maxAgeMs) || 0) + Math.max(0, performance.now() - scheduledAt),
818
+ transcriptNodes: elements.chat.querySelectorAll("*").length,
819
+ currentMessageNodes: activeMessage?.querySelectorAll?.("*").length || 0,
820
+ });
821
+ });
822
+ }
823
+
824
+ /**
825
+ * Detached-mode movement tracking: while the user owns the scroll position,
826
+ * any chat scroll change right after a stream batch that is not explained by
827
+ * user intent or a recent programmatic follow write is recorded as a
828
+ * regression candidate. Runs only when the debug ledger is enabled.
829
+ */
830
+ function noteDetachedChatScrollMovement() {
831
+ const ledger = streamIsolationDebugLedger;
832
+ if (!ledger) return;
833
+ const previousTop = ledger.lastChatScrollTop;
834
+ const currentTop = elements.chat.scrollTop;
835
+ ledger.lastChatScrollTop = currentTop;
836
+ if (autoFollowChat || previousTop === undefined) return;
837
+ if (isChatUserScrollIntentActive()) return;
838
+ if (performance.now() - lastChatProgrammaticScrollAt <= CHAT_PROGRAMMATIC_SCROLL_GRACE_MS) return;
839
+ const lastBatch = ledger.lastBatchAppliedAt || 0;
840
+ if (!lastBatch || performance.now() - lastBatch > 250) return;
841
+ const deltaTop = currentTop - previousTop;
842
+ if (deltaTop !== 0) recordStreamProfileDiagnostic({ type: "detached-scroll", deltaTop });
843
+ }
844
+
734
845
  if (streamIsolationDebugLedger) {
735
846
  Object.defineProperty(globalThis, "__piStreamIsolationDebug", {
736
847
  configurable: true,
737
848
  enumerable: false,
738
849
  value: streamIsolationDebugLedger,
739
850
  });
851
+ try {
852
+ const longTaskObserver = new PerformanceObserver((list) => {
853
+ for (const entry of list.getEntries()) recordStreamProfileDiagnostic({ type: "longtask", ms: entry.duration });
854
+ });
855
+ longTaskObserver.observe({ type: "longtask", buffered: false });
856
+ } catch {
857
+ // Long-task timing is unsupported in this browser; counters stay at zero.
858
+ }
859
+ try {
860
+ const longFrameObserver = new PerformanceObserver((list) => {
861
+ for (const entry of list.getEntries()) recordStreamProfileDiagnostic({ type: "long-animation-frame", ms: entry.duration });
862
+ });
863
+ longFrameObserver.observe({ type: "long-animation-frame", buffered: false });
864
+ } catch {
865
+ // Long-animation-frame timing is unsupported in this browser.
866
+ }
867
+ document.addEventListener("focusout", (event) => {
868
+ if (event.target !== elements.promptInput) return;
869
+ const lastBatch = streamIsolationDebugLedger.lastBatchAppliedAt || 0;
870
+ if (!lastBatch) return;
871
+ const msSinceBatch = performance.now() - lastBatch;
872
+ if (msSinceBatch <= 250) recordStreamProfileDiagnostic({ type: "focus-loss", msSinceBatch });
873
+ }, true);
740
874
  }
741
875
 
742
876
  const streamOutputController = createStreamOutputController({
@@ -4529,6 +4663,11 @@ function restoreComposerActionSlotLayout() {
4529
4663
  if (slot !== null) composerActionSlotLayout.set(id, slot);
4530
4664
  }
4531
4665
  applyComposerActionSlotLayout();
4666
+ // Project visible actions into a dense grid without overwriting the user's
4667
+ // saved layout. Restoring all hidden actions restores their original slots.
4668
+ if (composerActionRecords().some(({ root }) => root.classList.contains("webui-user-hidden"))) {
4669
+ repackComposerActionSlotLayout({ persist: false });
4670
+ }
4532
4671
  }
4533
4672
 
4534
4673
  function scheduleComposerActionSlotLayoutRestore() {
@@ -4561,7 +4700,7 @@ function captureComposerActionSlotLayout() {
4561
4700
  applyComposerActionSlotLayout();
4562
4701
  }
4563
4702
 
4564
- function repackComposerActionSlotLayout() {
4703
+ function repackComposerActionSlotLayout({ persist = true } = {}) {
4565
4704
  if (composerActionLayoutColumns < 1) return;
4566
4705
  const nextLayout = new Map();
4567
4706
  let slot = 0;
@@ -4573,7 +4712,7 @@ function repackComposerActionSlotLayout() {
4573
4712
  }
4574
4713
  composerActionSlotLayout = nextLayout;
4575
4714
  applyComposerActionSlotLayout();
4576
- persistComposerActionSlotLayout();
4715
+ if (persist) persistComposerActionSlotLayout();
4577
4716
  }
4578
4717
 
4579
4718
  function syncComposerActionOrderFromSlots() {
@@ -4813,7 +4952,10 @@ function initializeComposerActionOrdering() {
4813
4952
  }
4814
4953
  window.addEventListener("resize", scheduleComposerActionSlotLayoutRestore);
4815
4954
  for (const record of composerActionRecords()) {
4816
- record.focusTarget.setAttribute("aria-keyshortcuts", "Alt+ArrowLeft Alt+ArrowRight Alt+ArrowUp Alt+ArrowDown");
4955
+ // Send also anchors the keyboard-only visibility recovery menu.
4956
+ record.focusTarget.setAttribute("aria-keyshortcuts", record.id === "send"
4957
+ ? "Alt+ArrowLeft Alt+ArrowRight Alt+ArrowUp Alt+ArrowDown ContextMenu Shift+F10"
4958
+ : "Alt+ArrowLeft Alt+ArrowRight Alt+ArrowUp Alt+ArrowDown");
4817
4959
  record.focusTarget.addEventListener("keydown", (event) => {
4818
4960
  if (isMobileView() || !event.altKey || !["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown"].includes(event.key)) return;
4819
4961
  event.preventDefault();
@@ -12805,11 +12947,11 @@ async function moveFileTreeEntry(entry = fileContextMenuState?.entry) {
12805
12947
  // per-user layout lives in the WebUI settings file behind
12806
12948
  // GET/PUT /api/interface-preferences. Local writes always apply first; server
12807
12949
  // reconciliation is non-blocking, coalesced, and revision guarded.
12808
- const UI_LAYOUT_SCHEMA_VERSION = 2;
12950
+ const UI_LAYOUT_SCHEMA_VERSION = 3;
12809
12951
  const UI_LAYOUT_ENDPOINT = "/api/interface-preferences";
12810
12952
  const UI_LAYOUT_SAVE_DEBOUNCE_MS = 250;
12811
12953
  const UI_LAYOUT_MAX_CONFLICT_RETRIES = 1;
12812
- const UI_LAYOUT_FIELDS = ["sidePanel", "composerActions", "footerScopedModelOrder", "terminalTabs", "fileViewerWidth"];
12954
+ const UI_LAYOUT_FIELDS = ["sidePanel", "composerActions", "controlVisibility", "footerScopedModelOrder", "terminalTabs", "fileViewerWidth"];
12813
12955
  const UI_LAYOUT_SIDE_PANEL_FIELDS = ["placement", "sectionLayout", "collapsedSectionIds", "hiddenSectionIds", "collapsedPanels", "panelWidths"];
12814
12956
  const REMOVED_SIDE_PANEL_SECTION_HEIGHT_STORAGE_KEY = "pi-webui-side-panel-section-heights-v1";
12815
12957
  const UI_LAYOUT_COMPOSER_FIELDS = ["order", "grid"];
@@ -13016,6 +13158,271 @@ function collectDurableTerminalTabsLayout() {
13016
13158
  };
13017
13159
  }
13018
13160
 
13161
+ // --- Control visibility registry -------------------------------------------
13162
+ // Stable preference keys are independent of DOM ids. Each entry maps to a
13163
+ // static selector so user hiding composes with runtime capability gating via
13164
+ // the dedicated .webui-user-hidden class (never touches the hidden attribute).
13165
+ // Send is intentionally unregistered: it can never be hidden by preference.
13166
+ const CONTROL_VISIBILITY_HIDDEN_IDS_STORAGE_KEY = "pi-webui-control-visibility-hidden-ids-v1";
13167
+ const CONTROL_VISIBILITY_GROUP_LABELS = [
13168
+ ["workspace", "Workspace toolbar"],
13169
+ ["control-deck", "Control Deck"],
13170
+ ["composer", "Composer actions"],
13171
+ ["inputframe", "Input-frame controls"],
13172
+ ["tags", "Input-frame tags"],
13173
+ ];
13174
+ const CONTROL_VISIBILITY_CATALOG = [
13175
+ { id: "workspace.save", group: "workspace", label: "Save workspace", selector: "#workspaceSaveButton" },
13176
+ { id: "workspace.command-palette", group: "workspace", label: "Command palette", selector: "#commandPaletteButton" },
13177
+ { id: "workspace.overview", group: "workspace", label: "Show workspace overview", selector: "#workspaceDashboardToggleButton" },
13178
+ { id: "workspace.close-all-tabs", group: "workspace", label: "Close all tabs", selector: "#closeAllTabsButton" },
13179
+ { id: "control-deck.sponsor", group: "control-deck", label: "Sponsor", selector: ".sponsor-link" },
13180
+ { id: "control-deck.open-issue", group: "control-deck", label: "Open Issue", selector: "#openIssueButton" },
13181
+ { id: "composer.new", group: "composer", label: "New", selector: '[data-composer-action-id="new"]' },
13182
+ { id: "composer.compact", group: "composer", label: "Compact", selector: '[data-composer-action-id="compact"]' },
13183
+ { id: "composer.guided-git", group: "composer", label: "Guided Git workflow", selector: '[data-composer-action-id="git"]' },
13184
+ { id: "composer.publish", group: "composer", label: "AUR/npm release dropdown", selector: '[data-composer-action-id="publish"]' },
13185
+ { id: "composer.tools-skills", group: "composer", label: "Tools/skills setup dropdown", selector: '[data-composer-action-id="native-command"]' },
13186
+ { id: "composer.common-options", group: "composer", label: "Common options", selector: '[data-composer-action-id="options"]' },
13187
+ { id: "composer.app-runner", group: "composer", label: "App runner", selector: '[data-composer-action-id="app-runner"]' },
13188
+ { id: "composer.steer", group: "composer", label: "Steer", selector: '[data-composer-action-id="steer"]' },
13189
+ { id: "composer.follow-up", group: "composer", label: "Follow-up", selector: '[data-composer-action-id="follow-up"]' },
13190
+ { id: "composer.btw", group: "composer", label: "/btw side question", selector: '[data-composer-action-id="btw"]' },
13191
+ { id: "input.workflow", group: "inputframe", label: "Workflow controls", selector: "#workflowModeControls" },
13192
+ { id: "input.attach-files", group: "inputframe", label: "Attach files", selector: "#attachButton" },
13193
+ { id: "tag.prompt-behavior", group: "tags", label: "Follow-up/Steer busy-prompt behavior tag", selector: "#busyPromptBehaviorTag" },
13194
+ { id: "tag.skills", group: "tags", label: "Session skill tags", selector: "#sessionSkillTags" },
13195
+ { id: "tag.agent-conversations", group: "tags", label: "Intercom agent-conversation tags", selector: "#intercomConversationTags" },
13196
+ { id: "tag.feature-category", group: "tags", label: "Feature-category tag", selector: "#featureCategoryTag" },
13197
+ { id: "tag.voice-mode", group: "tags", label: "Natural-conversation/voice tag", selector: "#conversationModeChip" },
13198
+ { id: "tag.workflow-mode", group: "tags", label: "Workflow-mode tag", selector: "#workflowModeChip" },
13199
+ ];
13200
+ const CONTROL_VISIBILITY_REGISTRY = new Map(CONTROL_VISIBILITY_CATALOG.map((entry) => [entry.id, entry]));
13201
+
13202
+ function readStoredControlVisibilityHiddenIds() {
13203
+ const raw = readDurableLayoutCache(CONTROL_VISIBILITY_HIDDEN_IDS_STORAGE_KEY);
13204
+ if (raw === null) return null;
13205
+ try {
13206
+ return durableLayoutIdList(JSON.parse(raw));
13207
+ } catch {
13208
+ return null;
13209
+ }
13210
+ }
13211
+
13212
+ function userControlHiddenIds() {
13213
+ const dirtyHiddenIds = durableLayoutDirtyFields.get("controlVisibility")?.value?.hiddenIds;
13214
+ if (dirtyHiddenIds === null || Array.isArray(dirtyHiddenIds)) return dirtyHiddenIds || [];
13215
+ return readStoredControlVisibilityHiddenIds() || [];
13216
+ }
13217
+
13218
+ // Only the preference class is managed here. A runtime `hidden` attribute
13219
+ // owned by capability/state gating always remains authoritative.
13220
+ function applyControlVisibility(hiddenIdsOverride) {
13221
+ // An explicit override lets this tab keep showing its own pending mutation
13222
+ // while another same-origin tab's cache value is still unacknowledged.
13223
+ const hiddenSet = new Set(hiddenIdsOverride === undefined ? userControlHiddenIds() : hiddenIdsOverride || []);
13224
+ let composerChanged = false;
13225
+ for (const entry of CONTROL_VISIBILITY_CATALOG) {
13226
+ const shouldHide = hiddenSet.has(entry.id);
13227
+ for (const element of document.querySelectorAll(entry.selector)) {
13228
+ const wasHidden = element.classList.contains("webui-user-hidden");
13229
+ element.classList.toggle("webui-user-hidden", shouldHide);
13230
+ // Reflow on a real state change in either direction: un-hiding must
13231
+ // restore saved slots, and unchanged reapplies (storage events, snapshot
13232
+ // adoption) must not schedule spurious repacks.
13233
+ if (wasHidden !== shouldHide && entry.group === "composer") composerChanged = true;
13234
+ }
13235
+ }
13236
+ // Hiding composer actions leaves grid holes; repack/restore the saved layout.
13237
+ if (composerChanged) scheduleComposerActionSlotLayoutRestore();
13238
+ }
13239
+
13240
+ function persistControlVisibilityHiddenIds(hiddenIds) {
13241
+ writeDurableLayoutCache(CONTROL_VISIBILITY_HIDDEN_IDS_STORAGE_KEY, JSON.stringify(hiddenIds ?? null));
13242
+ markDurableUiLayoutDirty("controlVisibility");
13243
+ applyControlVisibility(hiddenIds);
13244
+ }
13245
+
13246
+ function setControlVisibilityHidden(id, hidden) {
13247
+ if (!CONTROL_VISIBILITY_REGISTRY.has(id)) return;
13248
+ const current = userControlHiddenIds();
13249
+ const next = hidden ? [...new Set([...current, id])] : current.filter((entry) => entry !== id);
13250
+ persistControlVisibilityHiddenIds(next);
13251
+ }
13252
+
13253
+ function showAllControls() {
13254
+ persistControlVisibilityHiddenIds([]);
13255
+ }
13256
+
13257
+ function resetControlVisibilityDefaults() {
13258
+ persistControlVisibilityHiddenIds(null);
13259
+ }
13260
+
13261
+ let visibilityContextMenuState = null;
13262
+
13263
+ function closeVisibilityContextMenu({ returnFocus = true } = {}) {
13264
+ const trigger = visibilityContextMenuState?.trigger;
13265
+ visibilityContextMenuState = null;
13266
+ if (elements.visibilityContextMenu) elements.visibilityContextMenu.hidden = true;
13267
+ if (!returnFocus) return;
13268
+ const triggerSurvives = trigger
13269
+ && trigger.isConnected
13270
+ && !trigger.hidden
13271
+ && !trigger.classList?.contains("webui-user-hidden")
13272
+ && typeof trigger.focus === "function";
13273
+ if (triggerSurvives) trigger.focus({ preventScroll: true });
13274
+ else elements.promptInput?.focus({ preventScroll: true });
13275
+ }
13276
+
13277
+ function positionControlVisibilityMenu(clientX, clientY) {
13278
+ const menu = elements.visibilityContextMenu;
13279
+ menu.hidden = false;
13280
+ const rect = menu.getBoundingClientRect();
13281
+ const left = Math.min(clientX, Math.max(8, window.innerWidth - rect.width - 8));
13282
+ const top = Math.min(clientY, Math.max(8, window.innerHeight - rect.height - 8));
13283
+ menu.style.left = `${Math.max(8, left)}px`;
13284
+ menu.style.top = `${Math.max(8, top)}px`;
13285
+ }
13286
+
13287
+ function controlVisibilityMenuLabel(text) {
13288
+ const label = make("div", "control-visibility-menu-label", text);
13289
+ label.setAttribute("role", "presentation");
13290
+ label.setAttribute("aria-hidden", "true");
13291
+ return label;
13292
+ }
13293
+
13294
+ function controlVisibilityMenuAction(action, text) {
13295
+ const button = make("button", "control-visibility-menu-item control-visibility-menu-action", text);
13296
+ button.type = "button";
13297
+ button.setAttribute("role", "menuitem");
13298
+ button.dataset.visibilityMenuAction = action;
13299
+ return button;
13300
+ }
13301
+
13302
+ function prepareControlVisibilityMenu(trigger, entryId = null) {
13303
+ if (!elements.visibilityContextMenu) return null;
13304
+ closeFileContextMenu({ returnFocus: false });
13305
+ closeGitPanelContextMenu({ returnFocus: false });
13306
+ closeSidePanelContextMenu({ returnFocus: false });
13307
+ closeGitFooterContextMenu({ returnFocus: false });
13308
+ closeVisibilityContextMenu({ returnFocus: false });
13309
+ // Region hosts are plain non-focusable containers; storing one as the
13310
+ // trigger would let Escape focus fall through to <body>. Fall back to the
13311
+ // prompt unless the trigger can actually receive keyboard focus.
13312
+ const focusableTrigger = trigger
13313
+ && typeof trigger.focus === "function"
13314
+ && trigger.matches("button, a, input, select, textarea, [tabindex]")
13315
+ ? trigger
13316
+ : elements.promptInput;
13317
+ visibilityContextMenuState = {
13318
+ trigger: focusableTrigger,
13319
+ entryId,
13320
+ openedAt: performance.now(),
13321
+ };
13322
+ return elements.visibilityContextMenu;
13323
+ }
13324
+
13325
+ // Right-clicking a visible registered control offers Hide <label> plus the
13326
+ // recovery actions; empty marked regions open the grouped full catalog.
13327
+ function showControlVisibilityDirectMenu(entry, directElement, { clientX, clientY }) {
13328
+ const menu = prepareControlVisibilityMenu(directElement, entry.id);
13329
+ if (!menu) return;
13330
+ const items = [
13331
+ controlVisibilityMenuLabel("Hide or restore controls"),
13332
+ controlVisibilityMenuAction("hide", `Hide ${entry.label}`),
13333
+ controlVisibilityMenuAction("show-all", "Show all"),
13334
+ controlVisibilityMenuAction("reset-defaults", "Reset defaults"),
13335
+ ];
13336
+ menu.replaceChildren(...items);
13337
+ positionControlVisibilityMenu(clientX, clientY);
13338
+ menu.querySelector('[role="menuitem"]')?.focus({ preventScroll: true });
13339
+ }
13340
+
13341
+ function showControlVisibilityRegionMenu(trigger, { clientX, clientY }) {
13342
+ const menu = prepareControlVisibilityMenu(trigger, null);
13343
+ if (!menu) return;
13344
+ const hiddenSet = new Set(userControlHiddenIds());
13345
+ const children = [controlVisibilityMenuLabel("Choose visible controls")];
13346
+ for (const [groupId, groupLabel] of CONTROL_VISIBILITY_GROUP_LABELS) {
13347
+ children.push(controlVisibilityMenuLabel(groupLabel));
13348
+ for (const entry of CONTROL_VISIBILITY_CATALOG.filter((item) => item.group === groupId)) {
13349
+ const button = make("button", "control-visibility-menu-item side-panel-context-menu-item", entry.label);
13350
+ button.type = "button";
13351
+ button.setAttribute("role", "menuitemcheckbox");
13352
+ button.setAttribute("aria-checked", hiddenSet.has(entry.id) ? "false" : "true");
13353
+ button.dataset.visibilityMenuToggle = entry.id;
13354
+ children.push(button);
13355
+ }
13356
+ }
13357
+ children.push(controlVisibilityMenuAction("show-all", "Show all"));
13358
+ children.push(controlVisibilityMenuAction("reset-defaults", "Reset defaults"));
13359
+ menu.replaceChildren(...children);
13360
+ positionControlVisibilityMenu(clientX, clientY);
13361
+ menu.querySelector('[role="menuitemcheckbox"]')?.focus({ preventScroll: true });
13362
+ }
13363
+
13364
+ // Registered visibility targets always win; unrelated editable/input/link
13365
+ // contexts and existing specialized menus keep their native behavior.
13366
+ function handleControlVisibilityContextMenu(event) {
13367
+ const target = event.target;
13368
+ if (!(target instanceof Element)) return;
13369
+ if (target.closest?.(".file-context-menu, dialog, .composer-publish-menu-panel")) return;
13370
+ const direct = target.closest?.("[data-visibility-key]");
13371
+ const entry = direct ? CONTROL_VISIBILITY_REGISTRY.get(direct.dataset.visibilityKey) : null;
13372
+ if (entry) {
13373
+ event.preventDefault();
13374
+ event.stopPropagation();
13375
+ showControlVisibilityDirectMenu(entry, direct, { clientX: event.clientX, clientY: event.clientY });
13376
+ return;
13377
+ }
13378
+ if (target.closest?.("button, input, textarea, select, [contenteditable='true'], a")) return;
13379
+ const region = target.closest?.("[data-visibility-region]");
13380
+ if (!region) return;
13381
+ event.preventDefault();
13382
+ event.stopPropagation();
13383
+ showControlVisibilityRegionMenu(region, { clientX: event.clientX, clientY: event.clientY });
13384
+ }
13385
+
13386
+ function handleControlVisibilityKeydown(event) {
13387
+ if (event.key !== "ContextMenu" && !(event.shiftKey && event.key === "F10")) return;
13388
+ const target = event.target instanceof Element ? event.target : document.activeElement;
13389
+ if (!(target instanceof Element)) return;
13390
+ if (target.closest?.(".file-context-menu, dialog, .composer-publish-menu-panel")) return;
13391
+ const direct = target.closest?.("[data-visibility-key]");
13392
+ const entry = direct ? CONTROL_VISIBILITY_REGISTRY.get(direct.dataset.visibilityKey) : null;
13393
+ // Send is permanently visible and never toggleable, so from the keyboard it
13394
+ // doubles as the always-reachable anchor for the grouped recovery menu when
13395
+ // every optional control is hidden. Pointer right-click on Send stays native.
13396
+ const sendAnchor = entry ? null : target.closest?.("#sendButton");
13397
+ const anchor = direct || sendAnchor || target.closest?.("[data-visibility-region]");
13398
+ if (!anchor) return;
13399
+ if (!entry && !sendAnchor && target.closest?.("button, input, textarea, select, [contenteditable='true'], a")) return;
13400
+ const rect = anchor.getBoundingClientRect();
13401
+ const position = { clientX: rect.left + Math.min(rect.width, 24), clientY: rect.bottom };
13402
+ event.preventDefault();
13403
+ event.stopPropagation();
13404
+ if (entry) showControlVisibilityDirectMenu(entry, direct, position);
13405
+ else showControlVisibilityRegionMenu(anchor, position);
13406
+ }
13407
+
13408
+ function initializeControlVisibility() {
13409
+ applyControlVisibility();
13410
+ document.addEventListener("contextmenu", handleControlVisibilityContextMenu, { capture: true });
13411
+ document.addEventListener("keydown", handleControlVisibilityKeydown, { capture: true });
13412
+ document.addEventListener("pointerdown", (event) => {
13413
+ if (!elements.visibilityContextMenu || elements.visibilityContextMenu.hidden) return;
13414
+ if (!event.target?.closest?.(".control-visibility-context-menu")) closeVisibilityContextMenu({ returnFocus: false });
13415
+ }, { passive: true });
13416
+ window.addEventListener("resize", () => closeVisibilityContextMenu({ returnFocus: false }), { passive: true });
13417
+ document.addEventListener("scroll", () => {
13418
+ // Pointer-driven context-menu invocation can finish an automatic
13419
+ // scroll-into-view after the menu opens. Ignore that trailing event while
13420
+ // still dismissing the menu for subsequent user scrolling.
13421
+ if (!visibilityContextMenuState || performance.now() - visibilityContextMenuState.openedAt < 100) return;
13422
+ closeVisibilityContextMenu({ returnFocus: false });
13423
+ }, { capture: true, passive: true });
13424
+ }
13425
+
13019
13426
  function collectDurableFileViewerWidth() {
13020
13427
  const width = readStoredFileViewerWidth();
13021
13428
  if (!Number.isFinite(width)) return null;
@@ -13029,6 +13436,8 @@ function collectDurableUiLayoutField(field) {
13029
13436
  return collectDurableSidePanelLayout();
13030
13437
  case "composerActions":
13031
13438
  return collectDurableComposerActionsLayout();
13439
+ case "controlVisibility":
13440
+ return { hiddenIds: readStoredControlVisibilityHiddenIds() };
13032
13441
  case "footerScopedModelOrder":
13033
13442
  return durableLayoutStoredIdList(FOOTER_SCOPED_MODEL_ORDER_STORAGE_KEY);
13034
13443
  case "terminalTabs":
@@ -13267,6 +13676,12 @@ function applyDurableComposerActionsLayout(value) {
13267
13676
  }
13268
13677
  }
13269
13678
 
13679
+ function applyDurableControlVisibility(value) {
13680
+ if (!value || typeof value !== "object") return;
13681
+ writeDurableLayoutCache(CONTROL_VISIBILITY_HIDDEN_IDS_STORAGE_KEY, JSON.stringify(value.hiddenIds ?? null));
13682
+ applyControlVisibility();
13683
+ }
13684
+
13270
13685
  function applyDurableFooterScopedModelOrder(value) {
13271
13686
  if (!Array.isArray(value)) return;
13272
13687
  writeDurableLayoutCache(FOOTER_SCOPED_MODEL_ORDER_STORAGE_KEY, JSON.stringify(value));
@@ -13304,6 +13719,7 @@ function applyDurableFileViewerWidth(value) {
13304
13719
  function applyDurableUiLayoutField(field, value) {
13305
13720
  if (field === "sidePanel") applyDurableSidePanelLayout(value);
13306
13721
  else if (field === "composerActions") applyDurableComposerActionsLayout(value);
13722
+ else if (field === "controlVisibility") applyDurableControlVisibility(value);
13307
13723
  else if (field === "footerScopedModelOrder") applyDurableFooterScopedModelOrder(value);
13308
13724
  else if (field === "terminalTabs") applyDurableTerminalTabsLayout(value);
13309
13725
  else if (field === "fileViewerWidth") applyDurableFileViewerWidth(value);
@@ -13313,6 +13729,7 @@ function durableUiLayoutInteractionActive(field = null) {
13313
13729
  const activeByField = {
13314
13730
  sidePanel: Boolean(sidePanelSectionPointerDrag?.active || sidePanelResizeState),
13315
13731
  composerActions: Boolean(composerActionPointerDrag?.active),
13732
+ controlVisibility: false,
13316
13733
  footerScopedModelOrder: Boolean(footerScopedModelPointerDrag?.active),
13317
13734
  terminalTabs: Boolean(terminalTabDragId || terminalTabsResizeState),
13318
13735
  fileViewerWidth: Boolean(fileViewerResizeState),
@@ -13495,6 +13912,12 @@ async function flushDurableUiLayoutSave() {
13495
13912
  else current.value = collectDurableUiLayoutField(field);
13496
13913
  } else if (current.generation === entry.generation && current.mutationId === entry.mutationId) {
13497
13914
  durableLayoutDirtyFields.delete(field);
13915
+ if (field === "controlVisibility") {
13916
+ // Another tab may have overwritten the same-origin cache while this
13917
+ // mutation was pending; the acknowledged value is authoritative now.
13918
+ writeDurableLayoutCache(CONTROL_VISIBILITY_HIDDEN_IDS_STORAGE_KEY, JSON.stringify(entry.value?.hiddenIds ?? null));
13919
+ applyControlVisibility();
13920
+ }
13498
13921
  }
13499
13922
  }
13500
13923
  clearAcknowledgedDurableUiLayoutPendingMutations(snapshot);
@@ -33893,7 +34316,11 @@ function appendMarkdownMermaidBlock(parent, code) {
33893
34316
  // reproduces the source exactly, and unknown/oversized blocks fall back to one
33894
34317
  // plain token so copy, selection, and transcript search stay unchanged.
33895
34318
  function appendMarkdownCodeTokens(codeNode, source, language) {
34319
+ const profileStart = streamIsolationDebugLedger ? performance.now() : 0;
33896
34320
  const tokens = tokenizeCode(source, normalizedMarkdownLanguage(language));
34321
+ if (streamIsolationDebugLedger) {
34322
+ recordStreamProfileDiagnostic({ type: "tokenize", ms: performance.now() - profileStart, bytes: streamDiagnosticBytes(source), language: String(language || "") });
34323
+ }
33897
34324
  if (!tokens.length) {
33898
34325
  codeNode.textContent = source;
33899
34326
  return;
@@ -34124,7 +34551,15 @@ function clearStreamingMarkdownBlock(block) {
34124
34551
  while (block.firstChild) block.firstChild.remove();
34125
34552
  }
34126
34553
 
34554
+ function streamingMarkdownTailProfile(text) {
34555
+ const boundary = streamingMarkdownStableBoundary(text);
34556
+ const tail = text.slice(boundary);
34557
+ const fenceLines = tail.match(/^\s*```/gm);
34558
+ return { tailBytes: streamDiagnosticBytes(tail), tailKind: fenceLines && fenceLines.length % 2 === 1 ? "open-fence" : "text" };
34559
+ }
34560
+
34127
34561
  function renderStreamingMarkdown(block, text) {
34562
+ const profileStart = streamIsolationDebugLedger ? performance.now() : 0;
34128
34563
  const selectionSnapshot = captureChatTextSelection(block);
34129
34564
  const bubble = block?.closest(".message");
34130
34565
  transcriptRenderer.reconcileMarkdownSurface({
@@ -34137,6 +34572,10 @@ function renderStreamingMarkdown(block, text) {
34137
34572
  renderInto: renderMarkdownInto,
34138
34573
  });
34139
34574
  restoreChatTextSelection(selectionSnapshot);
34575
+ if (streamIsolationDebugLedger) {
34576
+ const { tailBytes, tailKind } = streamingMarkdownTailProfile(String(text || ""));
34577
+ recordStreamProfileDiagnostic({ type: "markdown-commit", ms: performance.now() - profileStart, textBytes: streamDiagnosticBytes(text), tailBytes, tailKind });
34578
+ }
34140
34579
  }
34141
34580
 
34142
34581
  function appendImage(parent, part) {
@@ -37377,6 +37816,7 @@ function scrollChatToBottom({ force = false } = {}) {
37377
37816
  function syncAutoFollowFromChatScroll() {
37378
37817
  const nearBottom = isChatNearBottom();
37379
37818
  const recentProgrammaticScroll = performance.now() - lastChatProgrammaticScrollAt <= CHAT_PROGRAMMATIC_SCROLL_GRACE_MS;
37819
+ if (streamIsolationDebugLedger) noteDetachedChatScrollMovement();
37380
37820
  if (performance.now() <= chatPausedScrollRestoreUntil) {
37381
37821
  autoFollowChat = false;
37382
37822
  } else if (isChatUserScrollAwayIntentActive()) {
@@ -42443,10 +42883,14 @@ function syncStreamRawTextFromUpdate(event, update) {
42443
42883
 
42444
42884
  function streamDerivedText() {
42445
42885
  if (streamDerivedTextCache.rawText === streamRawText) return streamDerivedTextCache;
42886
+ const profileStart = streamIsolationDebugLedger ? performance.now() : 0;
42446
42887
  const assistantText = stripTodoProgressLines(streamRawText, { streaming: true });
42447
42888
  const thinkingFormat = splitThinkingFormatText(assistantText, { streaming: true });
42448
42889
  const finalText = thinkingFormat?.hasThinkingFormat ? stripTodoProgressLines(thinkingFormat.finalText, { streaming: true }) : assistantText;
42449
42890
  streamDerivedTextCache = { rawText: streamRawText, assistantText, thinkingFormat, finalText };
42891
+ if (streamIsolationDebugLedger) {
42892
+ recordStreamProfileDiagnostic({ type: "derive", ms: performance.now() - profileStart, bytes: streamDiagnosticBytes(streamRawText) });
42893
+ }
42450
42894
  return streamDerivedTextCache;
42451
42895
  }
42452
42896
 
@@ -47140,6 +47584,7 @@ elements.sidePanelBackdrop.addEventListener("click", () => {
47140
47584
  setSidePanelCollapsed(true);
47141
47585
  });
47142
47586
  bindSidePanelContextMenu();
47587
+ initializeControlVisibility();
47143
47588
  elements.stickyUserPromptButton?.addEventListener("click", jumpToStickyUserPrompt);
47144
47589
  elements.jumpToLatestButton.addEventListener("click", jumpToLatest);
47145
47590
  elements.chat.addEventListener("wheel", noteChatUserScrollIntent, { passive: true });
@@ -47501,6 +47946,13 @@ window.addEventListener("storage", (event) => {
47501
47946
  }
47502
47947
  if (event.key === COMPOSER_ACTION_ORDER_STORAGE_KEY) restoreComposerActionOrder();
47503
47948
  if (event.key === COMPOSER_ACTION_LAYOUT_STORAGE_KEY) restoreComposerActionSlotLayout();
47949
+ if (event.key === CONTROL_VISIBILITY_HIDDEN_IDS_STORAGE_KEY) {
47950
+ // A pending local mutation stays visually authoritative for this tab;
47951
+ // adopting another tab's cache value here would revert the dirty change
47952
+ // that is still waiting for its acknowledged server write.
47953
+ const dirtyVisibility = durableLayoutDirtyFields.get("controlVisibility");
47954
+ applyControlVisibility(dirtyVisibility ? dirtyVisibility.value?.hiddenIds : undefined);
47955
+ }
47504
47956
  if (event.key === SIDE_PANEL_WIDTH_STORAGE_KEY && !ignoreLegacySidePanelEvent("panelWidths", Boolean(sidePanelResizeState))) {
47505
47957
  const width = readStoredSidePanelWidth();
47506
47958
  if (width && !isSidePanelOverlayView()) applySidePanelWidth(width);
@@ -47728,6 +48180,47 @@ elements.sidePanelContextMenu?.addEventListener("keydown", (event) => {
47728
48180
  items[event.key === "Home" ? 0 : items.length - 1]?.focus({ preventScroll: true });
47729
48181
  }
47730
48182
  });
48183
+ function visibilityContextMenuItems() {
48184
+ return [...elements.visibilityContextMenu.querySelectorAll('[role="menuitem"], [role="menuitemcheckbox"]')];
48185
+ }
48186
+ elements.visibilityContextMenu?.addEventListener("keydown", (event) => {
48187
+ const items = visibilityContextMenuItems();
48188
+ const index = items.indexOf(document.activeElement);
48189
+ if (event.key === "Escape") {
48190
+ event.preventDefault();
48191
+ closeVisibilityContextMenu();
48192
+ } else if (event.key === "ArrowDown" || event.key === "ArrowUp") {
48193
+ event.preventDefault();
48194
+ const direction = event.key === "ArrowDown" ? 1 : -1;
48195
+ items[(Math.max(0, index) + direction + items.length) % items.length]?.focus({ preventScroll: true });
48196
+ } else if (event.key === "Home" || event.key === "End") {
48197
+ event.preventDefault();
48198
+ items[event.key === "Home" ? 0 : items.length - 1]?.focus({ preventScroll: true });
48199
+ }
48200
+ });
48201
+ elements.visibilityContextMenu?.addEventListener("click", (event) => {
48202
+ const button = event.target?.closest?.("[data-visibility-menu-toggle], [data-visibility-menu-action]");
48203
+ if (!button) return;
48204
+ const toggleId = button.dataset.visibilityMenuToggle;
48205
+ if (toggleId) {
48206
+ const hiddenSet = new Set(userControlHiddenIds());
48207
+ setControlVisibilityHidden(toggleId, !hiddenSet.has(toggleId));
48208
+ button.setAttribute("aria-checked", hiddenSet.has(toggleId) ? "true" : "false");
48209
+ return;
48210
+ }
48211
+ const action = button.dataset.visibilityMenuAction;
48212
+ if (action === "hide") {
48213
+ const entryId = visibilityContextMenuState?.entryId;
48214
+ if (entryId) setControlVisibilityHidden(entryId, true);
48215
+ closeVisibilityContextMenu();
48216
+ } else if (action === "show-all") {
48217
+ closeVisibilityContextMenu();
48218
+ showAllControls();
48219
+ } else if (action === "reset-defaults") {
48220
+ closeVisibilityContextMenu();
48221
+ resetControlVisibilityDefaults();
48222
+ }
48223
+ });
47731
48224
  elements.gitFooterContextMenu?.addEventListener("keydown", (event) => {
47732
48225
  const items = [...elements.gitFooterContextMenu.querySelectorAll('[role="menuitem"]:not([disabled])')];
47733
48226
  const index = items.indexOf(document.activeElement);