@firstpick/pi-package-webui 0.9.5 → 0.9.6

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 (61) hide show
  1. package/README.md +5 -3
  2. package/bin/pi-webui.mjs +90 -5
  3. package/lib/optional-feature-catalog.mjs +1 -1
  4. package/lib/session-actions.mjs +20 -2
  5. package/package.json +1 -1
  6. package/public/app.js +1823 -262
  7. package/public/index.html +51 -31
  8. package/public/service-worker.js +4 -1
  9. package/public/stream-derived-output.mjs +799 -0
  10. package/public/stream-markdown-tail.mjs +204 -0
  11. package/public/stream-output-controller.mjs +193 -51
  12. package/public/stream-render-scheduler.mjs +85 -0
  13. package/public/styles.css +249 -18
  14. package/public/transcript-renderer.mjs +73 -24
  15. package/tests/boot-failure-diagnostics.test.mjs +3 -3
  16. package/tests/browser/composer-action-grid-reorder.spec.mjs +114 -31
  17. package/tests/browser/mobile-foundation.spec.mjs +28 -0
  18. package/tests/browser/stream-output-isolation.spec.mjs +308 -3
  19. package/tests/browser/user-noticeable-fixes.spec.mjs +204 -0
  20. package/tests/codex-fast-mode-static.test.mjs +2 -2
  21. package/tests/composer-action-grid-reorder-static.test.mjs +8 -7
  22. package/tests/control-visibility-static.test.mjs +3 -3
  23. package/tests/controls-layout-static.test.mjs +3 -3
  24. package/tests/cwd-footer-reliability-static.test.mjs +1 -1
  25. package/tests/fast-mode-client-static.test.mjs +1 -1
  26. package/tests/feature-decision-output-popup-static.test.mjs +2 -2
  27. package/tests/file-viewer-image-static.test.mjs +3 -3
  28. package/tests/fixtures/fake-pi.mjs +57 -10
  29. package/tests/fixtures/streaming-workloads.mjs +36 -0
  30. package/tests/footer-provider-usage-visual-static.test.mjs +15 -0
  31. package/tests/foreground-transcript-catch-up-static.test.mjs +7 -1
  32. package/tests/interaction-state-stability-static.test.mjs +3 -1
  33. package/tests/intercom-conversation-viewer-static.test.mjs +3 -3
  34. package/tests/intercom-conversations-http.test.mjs +16 -0
  35. package/tests/main-output-loading-static.test.mjs +3 -3
  36. package/tests/middle-button-drag-scroll-static.test.mjs +3 -3
  37. package/tests/mobile-continuity-tablet-static.test.mjs +3 -3
  38. package/tests/mobile-foundation-static.test.mjs +3 -3
  39. package/tests/mobile-phone-experience-static.test.mjs +1 -1
  40. package/tests/mobile-static.test.mjs +74 -63
  41. package/tests/open-issue-wizard-static.test.mjs +1 -1
  42. package/tests/persistent-ui-layout-static.test.mjs +4 -4
  43. package/tests/prompt-input-vertical-scroll-static.test.mjs +26 -0
  44. package/tests/questionnaire-dialog.test.mjs +3 -3
  45. package/tests/runtime-error-visibility.test.mjs +3 -3
  46. package/tests/session-auth-harness.test.mjs +26 -1
  47. package/tests/session-sampling-ui-static.test.mjs +3 -3
  48. package/tests/side-panel-section-height-removal-static.test.mjs +3 -3
  49. package/tests/stream-derived-output.test.mjs +121 -0
  50. package/tests/stream-markdown-tail.test.mjs +218 -0
  51. package/tests/stream-output-controller.test.mjs +119 -4
  52. package/tests/stream-output-isolation-static.test.mjs +27 -6
  53. package/tests/stream-output-workloads.test.mjs +40 -3
  54. package/tests/stream-render-scheduler.test.mjs +115 -0
  55. package/tests/streaming-ui-coupling.test.mjs +1 -1
  56. package/tests/subagent-observability-static.test.mjs +2 -2
  57. package/tests/syntax-highlighting-static.test.mjs +3 -3
  58. package/tests/theme-customizer-static.test.mjs +1 -1
  59. package/tests/thinking-format-parser.test.mjs +15 -0
  60. package/tests/todo-filter-static.test.mjs +148 -0
  61. package/tests/transcript-markdown-tail.test.mjs +137 -0
package/public/app.js CHANGED
@@ -9,6 +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 { createStreamDerivedOutputState } from "./stream-derived-output.mjs";
13
+ import { advanceStreamingMarkdownTail } from "./stream-markdown-tail.mjs";
14
+ import { createLatestWinsRenderScheduler } from "./stream-render-scheduler.mjs";
12
15
  import { classifyTranscriptStreamEvent, createStreamOutputController, reconcileTranscriptThinkingSnapshot } from "./stream-output-controller.mjs";
13
16
  import { installMiddleButtonDragScroll } from "./middle-button-drag-scroll.mjs";
14
17
  import { tokenizeCode } from "./syntax-highlight.mjs";
@@ -293,6 +296,8 @@ const elements = {
293
296
  agentDoneNotificationsStatus: $("#agentDoneNotificationsStatus"),
294
297
  optionalFeaturesBox: $("#optionalFeaturesBox"),
295
298
  optionalFeatureMigrationSurface: $("#optionalFeatureMigrationSurface"),
299
+ noticeToastStack: $("#noticeToastStack"),
300
+ eventsUnreadBadge: $("#eventsUnreadBadge"),
296
301
  optionalFeatureMigrationDialog: $("#optionalFeatureMigrationDialog"),
297
302
  optionalFeatureMigrationDialogTitle: $("#optionalFeatureMigrationDialogTitle"),
298
303
  optionalFeatureMigrationDialogMessage: $("#optionalFeatureMigrationDialogMessage"),
@@ -314,6 +319,7 @@ const elements = {
314
319
  fileTreeRoot: $("#fileTreeRoot"),
315
320
  fileTreeStatus: $("#fileTreeStatus"),
316
321
  fileTreeRefreshButton: $("#fileTreeRefreshButton"),
322
+ fileTreeNewFileButton: $("#fileTreeNewFileButton"),
317
323
  fileTreeSearchInput: $("#fileTreeSearchInput"),
318
324
  fileTreeSearchClearButton: $("#fileTreeSearchClearButton"),
319
325
  gitPanelGroups: $("#gitPanelGroups"),
@@ -459,6 +465,13 @@ const elements = {
459
465
  undoToastButton: $("#undoToastButton"),
460
466
  undoToastDismissButton: $("#undoToastDismissButton"),
461
467
  confirmationDialog: $("#confirmationDialog"),
468
+ textPromptDialog: $("#textPromptDialog"),
469
+ textPromptTitle: $("#textPromptTitle"),
470
+ textPromptSummary: $("#textPromptSummary"),
471
+ textPromptInput: $("#textPromptInput"),
472
+ textPromptError: $("#textPromptError"),
473
+ textPromptCancelButton: $("#textPromptCancelButton"),
474
+ textPromptConfirmButton: $("#textPromptConfirmButton"),
462
475
  confirmationTitle: $("#confirmationTitle"),
463
476
  confirmationSummary: $("#confirmationSummary"),
464
477
  confirmationAffected: $("#confirmationAffected"),
@@ -637,9 +650,18 @@ const promptRoutingTabs = new Set();
637
650
  let tabSeenCompletionSerials = new Map();
638
651
  let streamBubble = null;
639
652
  let streamText = null;
653
+ // Controls-panel Model / Thinking selections the user has made but not applied yet. While set,
654
+ // status refreshes must not snap the selects back to the live value.
655
+ let controlsPendingModelValue = "";
656
+ let controlsPendingThinkingValue = "";
657
+ const PATH_SUGGEST_DEBOUNCE_MS = 120;
658
+ const NOTICE_TOAST_LIMIT = 3;
659
+ const NOTICE_TOAST_TIMEOUT_MS = { info: 5000, success: 5000, warn: 6000, error: 10000 };
660
+ const noticeToasts = [];
661
+ let eventsUnreadCount = 0;
640
662
  let streamRawText = "";
641
663
  let streamThinkingRawText = "";
642
- let streamDerivedTextCache = { rawText: null, assistantText: "", thinkingFormat: null, finalText: "" };
664
+ let streamDerivedOutputState = null;
643
665
  let streamBubbleVisibleSince = 0;
644
666
  let streamBubbleHideTimer = null;
645
667
  let streamToolCallSeen = false;
@@ -700,6 +722,10 @@ const streamIsolationDebugLedger = STREAM_ISOLATION_DEBUG_ENABLED ? {
700
722
  longAnimationFrames: 0,
701
723
  focusLossNearStreamBatch: 0,
702
724
  detachedScrollMoves: 0,
725
+ renderSchedulerFlushes: 0,
726
+ renderSchedulerDefers: 0,
727
+ pressureDeferred: 0,
728
+ pressureSynchronousFallbacks: 0,
703
729
  },
704
730
  lastBatchAppliedAt: 0,
705
731
  lastChatScrollTop: undefined,
@@ -746,6 +772,12 @@ function recordStreamIsolationDiagnostic(record) {
746
772
  counters.overflows += 1;
747
773
  } else if (record.type === "stale") {
748
774
  counters.staleEvents += 1;
775
+ } else if (record.type === "render-scheduler") {
776
+ if (record.action === "flush") counters.renderSchedulerFlushes += 1;
777
+ else if (record.action === "defer") counters.renderSchedulerDefers += 1;
778
+ } else if (record.type === "pressure") {
779
+ if (record.action === "deferred") counters.pressureDeferred += 1;
780
+ else if (record.action === "synchronous-fallback") counters.pressureSynchronousFallbacks += 1;
749
781
  }
750
782
  if (record.type === "queued") {
751
783
  counters.highWaterPendingCount = Math.max(counters.highWaterPendingCount, Number(record.pendingCount) || 0);
@@ -873,6 +905,54 @@ if (streamIsolationDebugLedger) {
873
905
  }, true);
874
906
  }
875
907
 
908
+ let normalStreamFollowPending = false;
909
+ const normalStreamSchedulerDiagnostic = streamIsolationDebugLedger ? recordStreamIsolationDiagnostic : undefined;
910
+ const assistantStreamRenderScheduler = createLatestWinsRenderScheduler({
911
+ render: (options) => {
912
+ renderStreamingAssistantText(options);
913
+ completeNormalStreamScheduledRender();
914
+ },
915
+ onDiagnostic: normalStreamSchedulerDiagnostic,
916
+ });
917
+ const thinkingStreamRenderScheduler = createLatestWinsRenderScheduler({
918
+ render: (options = {}) => {
919
+ if (streamThinkingRawText) setStreamingThinkingText(streamThinkingRawText, options);
920
+ if (options.complete) streamThinkingBubble?.classList.add("complete");
921
+ completeNormalStreamScheduledRender();
922
+ },
923
+ onDiagnostic: normalStreamSchedulerDiagnostic,
924
+ });
925
+
926
+ function normalStreamRenderPending() {
927
+ return assistantStreamRenderScheduler.pending() || thinkingStreamRenderScheduler.pending();
928
+ }
929
+
930
+ function completeNormalStreamScheduledRender() {
931
+ if (!normalStreamFollowPending || normalStreamRenderPending()) return;
932
+ normalStreamFollowPending = false;
933
+ scheduleChatFollowScroll();
934
+ }
935
+
936
+ function requestNormalStreamFollowAfterRender() {
937
+ if (normalStreamRenderPending()) {
938
+ normalStreamFollowPending = true;
939
+ return;
940
+ }
941
+ scheduleChatFollowScroll();
942
+ }
943
+
944
+ function flushNormalStreamRenders(reason = "semantic") {
945
+ assistantStreamRenderScheduler.flushNow(reason);
946
+ thinkingStreamRenderScheduler.flushNow(reason);
947
+ completeNormalStreamScheduledRender();
948
+ }
949
+
950
+ function cancelNormalStreamRenders() {
951
+ assistantStreamRenderScheduler.cancel();
952
+ thinkingStreamRenderScheduler.cancel();
953
+ normalStreamFollowPending = false;
954
+ }
955
+
876
956
  const streamOutputController = createStreamOutputController({
877
957
  isOwnerCurrent: (owner) => owner === transcriptStreamOwner(),
878
958
  applyTextUpdate: (event) => handleMessageUpdate(event),
@@ -892,7 +972,7 @@ const streamOutputController = createStreamOutputController({
892
972
  applyStreamError: (event) => handleMessageUpdate(event),
893
973
  applyFollowScroll: () => {
894
974
  if (compactOutputActive()) flushCompactLiveOutput();
895
- scheduleChatFollowScroll();
975
+ else requestNormalStreamFollowAfterRender();
896
976
  },
897
977
  onUnknownStreamEvent: preserveUnknownTranscriptEvidence,
898
978
  onDiagnostic: streamIsolationDebugLedger ? recordStreamIsolationDiagnostic : undefined,
@@ -901,6 +981,7 @@ let assistantErrorSurfacedThisRun = false;
901
981
  let runIndicatorBubble = null;
902
982
  let runIndicatorText = null;
903
983
  let runIndicatorMeta = null;
984
+ let runIndicatorElapsed = null;
904
985
  let runIndicatorTimer = null;
905
986
  let runIndicatorRenderFrame = null;
906
987
  let runIndicatorRenderScroll = false;
@@ -1451,7 +1532,9 @@ const UPDATE_STATUS_INITIAL_DELAY_MS = 1800;
1451
1532
  const RUN_INDICATOR_TICK_MS = 1000;
1452
1533
  const RUN_INDICATOR_START_GRACE_MS = 2500;
1453
1534
  const RUN_INDICATOR_STATE_RECHECK_MS = 5000;
1454
- const ABORT_LONG_PRESS_MS = 3000;
1535
+ const ABORT_LONG_PRESS_MS = 1200;
1536
+ const ABORT_TAP_HINT_MS = 1800;
1537
+ let abortTapHintTimer = null;
1455
1538
  const ABORT_LONG_PRESS_TICK_MS = 100;
1456
1539
  const ABORT_LONG_PRESS_RELEASE_GRACE_MS = 350;
1457
1540
  const EMPTY_PROMPT_ESCAPE_AFTER_ABORT_GRACE_MS = 1000;
@@ -1624,6 +1707,55 @@ function persistMobileContinuityState() {
1624
1707
  function scheduleMobileContinuityPersist() {
1625
1708
  clearTimeout(mobileContinuityPersistTimer);
1626
1709
  mobileContinuityPersistTimer = setTimeout(persistMobileContinuityState, MOBILE_CONTINUITY_PERSIST_DEBOUNCE_MS);
1710
+ scheduleDesktopDraftPersist();
1711
+ }
1712
+
1713
+ // Desktop draft continuity: composer text per tab survives reloads and browser restarts (the
1714
+ // mobile v2 shell has its own richer continuity store; this covers everything else).
1715
+ const DESKTOP_DRAFT_STORAGE_KEY = "pi-webui-composer-drafts-v1";
1716
+ const DESKTOP_DRAFT_PERSIST_DEBOUNCE_MS = 500;
1717
+ const DESKTOP_DRAFT_MAX_TABS = 24;
1718
+ let desktopDraftPersistTimer = null;
1719
+
1720
+ function persistDesktopDrafts() {
1721
+ clearTimeout(desktopDraftPersistTimer);
1722
+ desktopDraftPersistTimer = null;
1723
+ if (isMobileShellV2Active()) return;
1724
+ if (activeTabId && elements.promptInput) tabDrafts.set(activeTabId, elements.promptInput.value || "");
1725
+ const liveIds = new Set(tabs.map((tab) => tab.id));
1726
+ const drafts = {};
1727
+ let count = 0;
1728
+ for (const [tabId, draft] of tabDrafts) {
1729
+ if (!liveIds.has(tabId) || !draft || count >= DESKTOP_DRAFT_MAX_TABS) continue;
1730
+ drafts[tabId] = String(draft).slice(0, 200_000);
1731
+ count += 1;
1732
+ }
1733
+ try {
1734
+ if (count === 0) localStorage.removeItem(DESKTOP_DRAFT_STORAGE_KEY);
1735
+ else localStorage.setItem(DESKTOP_DRAFT_STORAGE_KEY, JSON.stringify({ v: 1, drafts, savedAt: Date.now() }));
1736
+ } catch {
1737
+ // Storage may be unavailable (private mode / quota); drafts then live for this page only.
1738
+ }
1739
+ }
1740
+
1741
+ function scheduleDesktopDraftPersist() {
1742
+ clearTimeout(desktopDraftPersistTimer);
1743
+ desktopDraftPersistTimer = setTimeout(persistDesktopDrafts, DESKTOP_DRAFT_PERSIST_DEBOUNCE_MS);
1744
+ }
1745
+
1746
+ function restoreDesktopDrafts() {
1747
+ if (isMobileShellV2Active()) return;
1748
+ let stored = null;
1749
+ try {
1750
+ stored = JSON.parse(localStorage.getItem(DESKTOP_DRAFT_STORAGE_KEY) || "null");
1751
+ } catch {
1752
+ stored = null;
1753
+ }
1754
+ if (!stored || stored.v !== 1 || !stored.drafts || typeof stored.drafts !== "object") return;
1755
+ const liveIds = new Set(tabs.map((tab) => tab.id));
1756
+ for (const [tabId, draft] of Object.entries(stored.drafts)) {
1757
+ if (liveIds.has(tabId) && !tabDrafts.get(tabId) && typeof draft === "string" && draft) tabDrafts.set(tabId, draft);
1758
+ }
1627
1759
  }
1628
1760
 
1629
1761
  function restoreMobileContinuityState() {
@@ -4177,7 +4309,6 @@ function moveSidePanelSectionRelative(fromId, targetRecord, insertBefore, target
4177
4309
 
4178
4310
  function completeControlDeckSectionSideMove(record, side) {
4179
4311
  if (!record) return;
4180
- if (!record.section.classList.contains("collapsed")) setOnlySidePanelSectionExpanded(record);
4181
4312
  const sideRecords = sidePanelSectionRecords()
4182
4313
  .filter(({ id, section }) => !section.hidden && controlDeckSectionSide(id) === side)
4183
4314
  .sort((a, b) => controlDeckLayout.sectionLayout.order.indexOf(a.id) - controlDeckLayout.sectionLayout.order.indexOf(b.id));
@@ -4369,6 +4500,8 @@ function setSidePanelSectionCollapsed(record, collapsed, { persist = true } = {}
4369
4500
  record.content.hidden = collapsed;
4370
4501
  record.button.setAttribute("aria-expanded", collapsed ? "false" : "true");
4371
4502
  updateSidePanelSectionEditAffordance(record);
4503
+ if (!collapsed && record.id === "events") clearUnreadEvents();
4504
+ if (!collapsed && record.id === "subagents") queueMicrotask(() => revealSubagentLaunchSlotConfigIfDeferred());
4372
4505
  if (!collapsed && record.id === "git" && !record.section.hidden) {
4373
4506
  queueMicrotask(() => {
4374
4507
  renderGitPanel();
@@ -4391,18 +4524,13 @@ function setOnlySidePanelSectionExpanded(targetRecord, { persist = true } = {})
4391
4524
  if (persist) persistSidePanelSectionState();
4392
4525
  }
4393
4526
 
4527
+ // Sections open and close independently (any number may be expanded at once); the persisted
4528
+ // collapsed set is honored as-is. With no stored state every section starts collapsed.
4394
4529
  function restoreSidePanelSectionState() {
4395
4530
  const records = sidePanelSectionRecords();
4396
4531
  const collapsedIds = readStoredSidePanelSectionCollapsedIds();
4397
- const expandedBySide = new Map();
4398
- if (collapsedIds) {
4399
- for (const record of records) {
4400
- const side = controlDeckSectionSide(record.id);
4401
- if (!collapsedIds.has(record.id) && !expandedBySide.has(side)) expandedBySide.set(side, record.id);
4402
- }
4403
- }
4404
4532
  for (const record of records) {
4405
- setSidePanelSectionCollapsed(record, expandedBySide.get(controlDeckSectionSide(record.id)) !== record.id, { persist: false });
4533
+ setSidePanelSectionCollapsed(record, collapsedIds ? collapsedIds.has(record.id) : true, { persist: false });
4406
4534
  }
4407
4535
  }
4408
4536
 
@@ -4465,11 +4593,7 @@ function bindSidePanelSectionToggles() {
4465
4593
  event.preventDefault();
4466
4594
  return;
4467
4595
  }
4468
- if (record.section.classList.contains("collapsed")) {
4469
- setOnlySidePanelSectionExpanded(record);
4470
- } else {
4471
- setSidePanelSectionCollapsed(record, true);
4472
- }
4596
+ setSidePanelSectionCollapsed(record, !record.section.classList.contains("collapsed"));
4473
4597
  });
4474
4598
  record.button.addEventListener("keydown", (event) => {
4475
4599
  if (!isSidePanelSectionReorderingEnabled() || !event.altKey || !["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight"].includes(event.key)) return;
@@ -4616,13 +4740,48 @@ function persistComposerActionSlotLayout() {
4616
4740
  markDurableUiLayoutDirty("composerActions");
4617
4741
  }
4618
4742
 
4619
- function remapComposerActionSlot(record, slot, sourceColumns, targetColumns) {
4620
- const sourceRow = Math.floor(slot / sourceColumns);
4621
- const sourceColumn = slot % sourceColumns;
4622
- const sourceMaxColumn = Math.max(0, sourceColumns - record.span);
4623
- const targetMaxColumn = Math.max(0, targetColumns - record.span);
4624
- const relativeColumn = sourceMaxColumn > 0 ? Math.min(sourceColumn, sourceMaxColumn) / sourceMaxColumn : 0;
4625
- return sourceRow * targetColumns + Math.round(relativeColumn * targetMaxColumn);
4743
+ function projectComposerActionSlots(entries, sourceColumns, targetColumns) {
4744
+ const projected = new Map();
4745
+ const chunks = [];
4746
+ let chunk = [];
4747
+ const flushChunk = () => {
4748
+ if (chunk.length) chunks.push(chunk);
4749
+ chunk = [];
4750
+ };
4751
+
4752
+ for (const entry of entries) {
4753
+ const sourceRow = Math.floor(entry.storedSlot / sourceColumns);
4754
+ const sourceColumn = entry.storedSlot % sourceColumns;
4755
+ const sourceEnd = sourceColumn + entry.record.span;
4756
+ const first = chunk[0];
4757
+ const previous = chunk.at(-1);
4758
+ const continuesChunk = !!first
4759
+ && first.sourceRow === sourceRow
4760
+ && sourceColumn <= previous.sourceEnd + 1
4761
+ && sourceEnd - first.sourceColumn <= targetColumns;
4762
+ if (chunk.length && !continuesChunk) flushChunk();
4763
+ chunk.push({ ...entry, sourceRow, sourceColumn, sourceEnd });
4764
+ }
4765
+ flushChunk();
4766
+
4767
+ let lastTargetRow = -1;
4768
+ let lastTargetEnd = 0;
4769
+ for (const entriesInChunk of chunks) {
4770
+ const sourceRow = entriesInChunk[0].sourceRow;
4771
+ const sourceStart = entriesInChunk[0].sourceColumn;
4772
+ const sourceEnd = Math.max(...entriesInChunk.map((entry) => entry.sourceEnd));
4773
+ const chunkWidth = sourceEnd - sourceStart;
4774
+ const targetStart = Math.max(0, Math.min(sourceStart, targetColumns - chunkWidth));
4775
+ let targetRow = Math.max(sourceRow, lastTargetRow);
4776
+ if (targetRow === lastTargetRow && targetStart < lastTargetEnd) targetRow += 1;
4777
+ for (const entry of entriesInChunk) {
4778
+ const targetColumn = targetStart + (entry.sourceColumn - sourceStart);
4779
+ projected.set(entry.id, targetRow * targetColumns + targetColumn);
4780
+ }
4781
+ lastTargetRow = targetRow;
4782
+ lastTargetEnd = targetStart + chunkWidth;
4783
+ }
4784
+ return projected;
4626
4785
  }
4627
4786
 
4628
4787
  function nearestAvailableComposerActionSlot(record, preferredSlot, layout, columns) {
@@ -4653,13 +4812,15 @@ function restoreComposerActionSlotLayout() {
4653
4812
  return;
4654
4813
  }
4655
4814
  const records = new Map(composerActionRecords().map((record) => [record.id, record]));
4656
- for (const [id, storedSlot] of [...stored.positions].sort((a, b) => a[1] - b[1])) {
4657
- const record = records.get(id);
4658
- if (!record || record.root.hidden || !record.root.getClientRects().length) continue;
4659
- const preferredSlot = stored.columns === columns
4660
- ? storedSlot
4661
- : remapComposerActionSlot(record, storedSlot, stored.columns, columns);
4662
- const slot = nearestAvailableComposerActionSlot(record, preferredSlot, composerActionSlotLayout, columns);
4815
+ const storedEntries = [...stored.positions]
4816
+ .sort((a, b) => a[1] - b[1])
4817
+ .map(([id, storedSlot]) => ({ id, storedSlot, record: records.get(id) }))
4818
+ .filter(({ record }) => record && !record.root.hidden && record.root.getClientRects().length);
4819
+ const projectedSlots = stored.columns === columns
4820
+ ? new Map(storedEntries.map(({ id, storedSlot }) => [id, storedSlot]))
4821
+ : projectComposerActionSlots(storedEntries, stored.columns, columns);
4822
+ for (const { id, record } of storedEntries) {
4823
+ const slot = nearestAvailableComposerActionSlot(record, projectedSlots.get(id), composerActionSlotLayout, columns);
4663
4824
  if (slot !== null) composerActionSlotLayout.set(id, slot);
4664
4825
  }
4665
4826
  applyComposerActionSlotLayout();
@@ -5497,7 +5658,7 @@ async function hydrateLoadedWorkspaceActiveTab(requestedTabId) {
5497
5658
 
5498
5659
  async function saveWebuiWorkspace({ triggerButton = elements.workspaceSaveButton } = {}) {
5499
5660
  if (!tabs.length) return;
5500
- const promptedName = window.prompt("Save workspace as:", workspaceDefaultName());
5661
+ const promptedName = await appPromptText({ title: "Save workspace", summary: "Captures all open tabs, sessions, groups, and the active tab.", defaultValue: workspaceDefaultName(), confirmLabel: "Save workspace" });
5501
5662
  if (promptedName === null) return;
5502
5663
  const body = {
5503
5664
  name: promptedName.trim() || workspaceDefaultName(),
@@ -6993,7 +7154,11 @@ function setSkillEditorStatus(message = "", level = "muted") {
6993
7154
  status.hidden = !message;
6994
7155
  }
6995
7156
 
6996
- function closeSkillEditor() {
7157
+ async function closeSkillEditor({ force = false } = {}) {
7158
+ if (!force && activeSkillEditor?.dirty && elements.skillEditorDialog?.open) {
7159
+ if (!(await confirmDiscardEdits({ what: "unsaved skill edits", target: activeSkillEditor.path || activeSkillEditor.name || "SKILL.md" }))) return;
7160
+ activeSkillEditor.dirty = false;
7161
+ }
6997
7162
  if (elements.skillEditorDialog?.open) elements.skillEditorDialog.close();
6998
7163
  else activeSkillEditor = null;
6999
7164
  }
@@ -7258,7 +7423,7 @@ function resizePromptInput() {
7258
7423
  const maxHeight = Number.parseFloat(getComputedStyle(input).maxHeight);
7259
7424
  const nextHeight = Number.isFinite(maxHeight) ? Math.min(input.scrollHeight, maxHeight) : input.scrollHeight;
7260
7425
  input.style.height = `${Math.ceil(nextHeight)}px`;
7261
- input.style.overflowY = Number.isFinite(maxHeight) && input.scrollHeight > maxHeight + 1 ? "auto" : "hidden";
7426
+ input.style.overflowY = "auto";
7262
7427
  }
7263
7428
 
7264
7429
  function updateComposerModeButtons() {
@@ -7297,10 +7462,29 @@ function updateComposerModeButtons() {
7297
7462
  if (elements.abortButton.getAttribute("aria-label") !== abortTitle) elements.abortButton.setAttribute("aria-label", abortTitle);
7298
7463
  }
7299
7464
  renderBusyPromptBehaviorTag();
7465
+ renderSendButtonMode(runActive);
7300
7466
  document.body.classList.toggle("pi-run-active", runActive || abortAvailable);
7301
7467
  scheduleComposerActionSlotLayoutRestore();
7302
7468
  }
7303
7469
 
7470
+ // While Pi is running, Send does not start a new turn: it queues a follow-up or steers the active
7471
+ // run (per the busy-behavior tag). Say so on the button instead of silently acting differently.
7472
+ function renderSendButtonMode(runActive = isRunActive()) {
7473
+ const button = elements.sendButton;
7474
+ if (!button) return;
7475
+ const behavior = normalizeBusyPromptBehavior(busyPromptBehavior);
7476
+ const label = !runActive ? "Send" : behavior === "steer" ? "Steer" : "Queue";
7477
+ const title = !runActive
7478
+ ? "Send prompt — Shift+F10 opens visibility options"
7479
+ : behavior === "steer"
7480
+ ? "Pi is running: Enter steers the active run with this text. Change the behavior via the tag above the prompt."
7481
+ : "Pi is running: Enter queues this text as a follow-up. Change the behavior via the tag above the prompt.";
7482
+ if (button.textContent !== label) button.textContent = label;
7483
+ if (button.title !== title) button.title = title;
7484
+ button.setAttribute("aria-label", runActive ? `${label} (Send while Pi is running)` : "Send");
7485
+ button.classList.toggle("send-busy-mode", runActive);
7486
+ }
7487
+
7304
7488
  function scheduleComposerModeButtonsUpdate() {
7305
7489
  if (composerModeButtonsFrame !== null) return;
7306
7490
  const flush = () => {
@@ -7554,6 +7738,72 @@ function appConfirm({ title = "Confirm action", summary = "Continue?", affected
7554
7738
  });
7555
7739
  }
7556
7740
 
7741
+ // Ask before an action would throw away unsaved edits. Resolves true when it is fine to proceed.
7742
+ function confirmDiscardEdits({ what = "unsaved edits", target = "" } = {}) {
7743
+ return appConfirm({
7744
+ title: `Discard ${what}?`,
7745
+ summary: target ? `${target} has changes that have not been saved.` : "There are changes that have not been saved.",
7746
+ affected: target || "The current editor contents",
7747
+ undoable: false,
7748
+ confirmLabel: "Discard changes",
7749
+ });
7750
+ }
7751
+
7752
+ // Application text prompt (replaces blocking window.prompt): resolves with the entered string,
7753
+ // or null when cancelled. `validate` may return an error message to keep the dialog open.
7754
+ let activeTextPromptResolve = null;
7755
+
7756
+ function appPromptText({ title = "Enter a value", summary = "", defaultValue = "", placeholder = "", confirmLabel = "OK", validate = null, selectRange = null } = {}) {
7757
+ const dialog = elements.textPromptDialog;
7758
+ if (!dialog?.showModal) {
7759
+ const value = window.prompt([title, summary].filter(Boolean).join("\n\n"), defaultValue);
7760
+ return Promise.resolve(value === null ? null : String(value));
7761
+ }
7762
+ if (activeTextPromptResolve) finishTextPrompt(null);
7763
+ elements.textPromptTitle.textContent = title;
7764
+ elements.textPromptSummary.textContent = summary;
7765
+ elements.textPromptSummary.hidden = !summary;
7766
+ elements.textPromptInput.value = defaultValue;
7767
+ elements.textPromptInput.placeholder = placeholder;
7768
+ elements.textPromptError.hidden = true;
7769
+ elements.textPromptError.textContent = "";
7770
+ elements.textPromptConfirmButton.textContent = confirmLabel;
7771
+ dialog.dataset.validate = validate ? "1" : "";
7772
+ textPromptValidator = typeof validate === "function" ? validate : null;
7773
+ return new Promise((resolve) => {
7774
+ activeTextPromptResolve = resolve;
7775
+ dialog.showModal();
7776
+ queueMicrotask(() => {
7777
+ const input = elements.textPromptInput;
7778
+ input.focus();
7779
+ if (Array.isArray(selectRange)) input.setSelectionRange(selectRange[0], selectRange[1]);
7780
+ else input.select();
7781
+ });
7782
+ });
7783
+ }
7784
+
7785
+ let textPromptValidator = null;
7786
+
7787
+ function finishTextPrompt(value) {
7788
+ const resolve = activeTextPromptResolve;
7789
+ activeTextPromptResolve = null;
7790
+ textPromptValidator = null;
7791
+ if (elements.textPromptDialog?.open) elements.textPromptDialog.close();
7792
+ resolve?.(value);
7793
+ }
7794
+
7795
+ function submitTextPrompt() {
7796
+ const value = String(elements.textPromptInput?.value ?? "");
7797
+ const problem = textPromptValidator ? textPromptValidator(value) : "";
7798
+ if (problem) {
7799
+ elements.textPromptError.textContent = String(problem);
7800
+ elements.textPromptError.hidden = false;
7801
+ elements.textPromptInput?.focus();
7802
+ return;
7803
+ }
7804
+ finishTextPrompt(value);
7805
+ }
7806
+
7557
7807
  function appConfirmText(message, options = {}) {
7558
7808
  const text = String(message || "Continue?").trim();
7559
7809
  const [firstLine, ...rest] = text.split("\n");
@@ -8383,10 +8633,28 @@ function scopedApiPath(path, tabId = activeTabId) {
8383
8633
  return `${url.pathname}${url.search}${url.hash}`;
8384
8634
  }
8385
8635
 
8636
+ // Identical GET requests that overlap in time (boot fans out several refresh paths that ask for
8637
+ // the same catalogs) share one in-flight fetch. Callers still get their own resolved value.
8638
+ const inFlightGetRequests = new Map();
8639
+
8386
8640
  async function api(path, { method = "GET", body, tabId = activeTabId, scoped = true, signal } = {}) {
8641
+ const url = scoped ? scopedApiPath(path, tabId) : path;
8642
+ if (method === "GET" && !signal) {
8643
+ const pending = inFlightGetRequests.get(url);
8644
+ if (pending) return pending;
8645
+ const request = apiUncached(url, { method, body, signal }).finally(() => {
8646
+ if (inFlightGetRequests.get(url) === request) inFlightGetRequests.delete(url);
8647
+ });
8648
+ inFlightGetRequests.set(url, request);
8649
+ return request;
8650
+ }
8651
+ return apiUncached(url, { method, body, signal });
8652
+ }
8653
+
8654
+ async function apiUncached(url, { method = "GET", body, signal } = {}) {
8387
8655
  let response;
8388
8656
  try {
8389
- response = await fetch(scoped ? scopedApiPath(path, tabId) : path, {
8657
+ response = await fetch(url, {
8390
8658
  method,
8391
8659
  headers: body === undefined ? undefined : { "content-type": "application/json" },
8392
8660
  body: body === undefined ? undefined : JSON.stringify(body),
@@ -9130,7 +9398,22 @@ function renderAttachmentTray() {
9130
9398
  const pill = make("span", "attachment-pill");
9131
9399
  pill.title = attachment.requiresReselect ? `${attachment.name}\nReselect required; only metadata was restored.` : `${attachment.name}\n${attachment.mimeType}\n${formatBytes(attachment.size)}`;
9132
9400
  pill.classList.toggle("requires-reselect", attachment.requiresReselect === true);
9133
- const icon = make("span", "attachment-pill-icon", attachmentIcon(attachment.kind));
9401
+ let icon = make("span", "attachment-pill-icon", attachmentIcon(attachment.kind));
9402
+ if (attachment.kind === "image" && attachment.previewUrl) {
9403
+ // Show the actual picture so a pasted screenshot can be checked at a glance.
9404
+ const thumb = make("img", "attachment-pill-thumb");
9405
+ thumb.src = attachment.previewUrl;
9406
+ thumb.alt = "";
9407
+ thumb.decoding = "async";
9408
+ thumb.loading = "lazy";
9409
+ const thumbButton = make("button", "attachment-pill-thumb-button");
9410
+ thumbButton.type = "button";
9411
+ thumbButton.title = `Preview ${attachment.name}`;
9412
+ thumbButton.setAttribute("aria-label", `Preview ${attachment.name}`);
9413
+ thumbButton.append(thumb);
9414
+ thumbButton.addEventListener("click", () => openImageLightbox(attachment.previewUrl, attachment.name));
9415
+ icon = thumbButton;
9416
+ }
9134
9417
  const name = make("span", "attachment-pill-name", attachment.name);
9135
9418
  const meta = make("span", "attachment-pill-meta", attachment.requiresReselect ? `${attachment.kind} · ${formatBytes(attachment.size)} · Reselect required` : `${attachment.kind} · ${formatBytes(attachment.size)}`);
9136
9419
  const edit = !attachment.requiresReselect && isEditableTextAttachment(attachment) ? make("button", "attachment-edit-button", "Edit") : null;
@@ -9163,7 +9446,7 @@ function removeAttachment(id, tabId = activeTabId) {
9163
9446
  if (index === -1) return;
9164
9447
  const [removed] = attachments.splice(index, 1);
9165
9448
  if (removed?.previewUrl) URL.revokeObjectURL(removed.previewUrl);
9166
- if (activeTextAttachmentEditor?.tabId === tabId && activeTextAttachmentEditor?.attachmentId === id) closeTextAttachmentEditor();
9449
+ if (activeTextAttachmentEditor?.tabId === tabId && activeTextAttachmentEditor?.attachmentId === id) closeTextAttachmentEditor({ force: true });
9167
9450
  if (attachments.length === 0) tabAttachments.delete(tabId);
9168
9451
  if (tabId === activeTabId) renderAttachmentTray();
9169
9452
  persistMobileContinuityState();
@@ -9174,7 +9457,7 @@ function clearAttachments(tabId = activeTabId) {
9174
9457
  for (const attachment of attachments) {
9175
9458
  if (attachment.previewUrl) URL.revokeObjectURL(attachment.previewUrl);
9176
9459
  }
9177
- if (activeTextAttachmentEditor?.tabId === tabId) closeTextAttachmentEditor();
9460
+ if (activeTextAttachmentEditor?.tabId === tabId) closeTextAttachmentEditor({ force: true });
9178
9461
  if (tabId) tabAttachments.delete(tabId);
9179
9462
  if (tabId === activeTabId) renderAttachmentTray();
9180
9463
  persistMobileContinuityState();
@@ -9237,20 +9520,15 @@ function attachLongTextAsFile(text, source = "input text") {
9237
9520
  return result.added > 0;
9238
9521
  }
9239
9522
 
9240
- function moveLongPromptInputToAttachment() {
9241
- const text = elements.promptInput.value || "";
9242
- if (!attachLongTextAsFile(text, "input text")) return false;
9243
- elements.promptInput.value = "";
9244
- resizePromptInput();
9245
- hideCommandSuggestions();
9246
- return true;
9247
- }
9248
-
9249
9523
  function attachmentById(tabId, id) {
9250
9524
  return attachmentsForTab(tabId).find((attachment) => attachment.id === id) || null;
9251
9525
  }
9252
9526
 
9253
- function closeTextAttachmentEditor() {
9527
+ async function closeTextAttachmentEditor({ force = false } = {}) {
9528
+ if (!force && activeTextAttachmentEditor?.dirty && elements.attachmentTextDialog?.open) {
9529
+ if (!(await confirmDiscardEdits({ what: "unsaved attachment edits", target: "The attachment text" }))) return;
9530
+ activeTextAttachmentEditor.dirty = false;
9531
+ }
9254
9532
  if (elements.attachmentTextDialog?.open) elements.attachmentTextDialog.close();
9255
9533
  else activeTextAttachmentEditor = null;
9256
9534
  }
@@ -9348,7 +9626,7 @@ function saveTextAttachmentEdit() {
9348
9626
  attachment.previewUrl = undefined;
9349
9627
  if (tabId === activeTabId) renderAttachmentTray();
9350
9628
  addEvent(`updated text attachment ${attachment.name} (${formatBytes(attachment.size)})`, "info");
9351
- closeTextAttachmentEditor();
9629
+ closeTextAttachmentEditor({ force: true });
9352
9630
  }
9353
9631
 
9354
9632
  function clipboardFiles(dataTransfer) {
@@ -12919,6 +13197,37 @@ async function moveFileTreeEntryToDestination(entry = {}, destinationPath = "",
12919
13197
  }
12920
13198
  }
12921
13199
 
13200
+ // "New file… / New folder…" for the Files panel. `entry` is the folder (or a file, whose parent
13201
+ // folder is used) the action was invoked on; the workspace root when invoked from the toolbar.
13202
+ async function createFileTreeEntry(entry = null, kind = "file") {
13203
+ const entryPath = normalizeFileTreePath(entry?.path || "");
13204
+ const parentPath = !entryPath ? "" : entry?.type === "directory" ? entryPath : entryPath.split("/").slice(0, -1).join("/");
13205
+ const label = kind === "directory" ? "folder" : "file";
13206
+ const name = await appPromptText({
13207
+ title: `New ${label}`,
13208
+ summary: `Created inside ${parentPath || "the workspace root"}. Use "/" to create it deeper (existing folders only).`,
13209
+ placeholder: kind === "directory" ? "folder-name" : "notes.md",
13210
+ confirmLabel: "Create",
13211
+ validate: (value) => {
13212
+ const text = String(value || "").trim();
13213
+ if (!text) return "A name is required.";
13214
+ if (text === "." || text === ".." || text.includes("\0")) return "That name is not allowed.";
13215
+ if (text.startsWith("/") || text.startsWith("..")) return "Use a path relative to this folder.";
13216
+ return "";
13217
+ },
13218
+ });
13219
+ if (name === null) return;
13220
+ const relative = normalizeFileTreePath([parentPath, String(name).trim()].filter(Boolean).join("/"));
13221
+ const tabContext = activeTabContext();
13222
+ const response = await api("/api/files/create", { method: "POST", body: { path: relative, type: kind }, tabId: tabContext.tabId });
13223
+ if (!isCurrentTabContext(tabContext)) return;
13224
+ const created = response.data || {};
13225
+ addEvent(`Created ${label} ${created.path || relative}.`, "success");
13226
+ if (parentPath) fileTreeState.expanded.add(parentPath);
13227
+ await refreshFileTreeLive(tabContext).catch(() => {});
13228
+ if (kind === "file") await openFileInViewer(created.path || relative);
13229
+ }
13230
+
12922
13231
  async function moveFileTreeEntry(entry = fileContextMenuState?.entry) {
12923
13232
  if (!entry) return;
12924
13233
  const sourcePath = normalizeFileTreePath(entry.path || "");
@@ -12927,12 +13236,18 @@ async function moveFileTreeEntry(entry = fileContextMenuState?.entry) {
12927
13236
  return;
12928
13237
  }
12929
13238
  const typeLabel = fileOperationTypeLabel(entry);
12930
- const destinationInput = window.prompt([
12931
- `Move/rename ${typeLabel} ${sourcePath}`,
12932
- "",
12933
- "Enter a destination path inside the current workspace.",
12934
- `Existing directories receive the ${typeLabel} as a child.`,
12935
- ].join("\n"), sourcePath);
13239
+ const baseName = sourcePath.split("/").pop() || sourcePath;
13240
+ const nameStart = sourcePath.length - baseName.length;
13241
+ const dotIndex = baseName.lastIndexOf(".");
13242
+ const destinationInput = await appPromptText({
13243
+ title: `Move or rename ${typeLabel}`,
13244
+ summary: `${sourcePath} — enter a new name or a destination path inside the workspace. An existing folder receives the ${typeLabel} as a child.`,
13245
+ defaultValue: sourcePath,
13246
+ confirmLabel: "Move",
13247
+ // Pre-select the file name (without extension) so a plain rename is one keystroke away.
13248
+ selectRange: [nameStart, entry.type === "directory" || dotIndex <= 0 ? sourcePath.length : nameStart + dotIndex],
13249
+ validate: (value) => (String(value || "").trim() ? "" : "Destination path is required."),
13250
+ });
12936
13251
  if (destinationInput === null) return;
12937
13252
  const destinationPath = String(destinationInput || "").trim();
12938
13253
  if (!destinationPath) {
@@ -14947,6 +15262,9 @@ async function applyGitFileChangesSnapshot(request, tabContext, viewerPath, requ
14947
15262
  async function openFileInViewer(path = "", { gitCategory = "", gitPath = "" } = {}) {
14948
15263
  const normalized = normalizeFileTreePath(path);
14949
15264
  if (!normalized) return;
15265
+ if (activeFileViewer?.dirty && activeFileViewer.path !== normalized) {
15266
+ if (!(await confirmDiscardEdits({ what: "unsaved file edits", target: activeFileViewer.path }))) return;
15267
+ }
14950
15268
  const openRequestSerial = ++fileViewerOpenRequestSerial;
14951
15269
  const tabContext = activeTabContext();
14952
15270
  fileTreeState.selectedPath = normalized;
@@ -15443,6 +15761,7 @@ function updateDocumentTitle() {
15443
15761
  function saveActiveDraft() {
15444
15762
  if (activeTabId) tabDrafts.set(activeTabId, elements.promptInput.value || "");
15445
15763
  persistMobileContinuityState();
15764
+ persistDesktopDrafts();
15446
15765
  }
15447
15766
 
15448
15767
  function restoreActiveDraft() {
@@ -15603,6 +15922,8 @@ function resetActiveTabUi() {
15603
15922
  clearRefreshTimers();
15604
15923
  eventSource?.close();
15605
15924
  eventSource = null;
15925
+ setControlsPendingModel("");
15926
+ setControlsPendingThinking("");
15606
15927
  currentState = cachedStateForTabSwitch(activeTabId);
15607
15928
  latestStats = activeTabId ? tabStatsCache.get(activeTabId) || null : null;
15608
15929
  latestStatsOverlayPayload = null;
@@ -16042,6 +16363,30 @@ function showGitPanelContextMenu(event, context) {
16042
16363
  menu.querySelector('[role="menuitem"]:not([disabled])')?.focus({ preventScroll: true });
16043
16364
  }
16044
16365
 
16366
+ // Touch- and keyboard-discoverable entry to the same actions as the right-click menu.
16367
+ function gitPanelOverflowButton(context, label) {
16368
+ const button = make("button", "git-side-panel-overflow-button file-tree-overflow-button", "⋯");
16369
+ button.type = "button";
16370
+ button.setAttribute("aria-label", `Git actions for ${label}`);
16371
+ button.setAttribute("aria-haspopup", "menu");
16372
+ button.title = "Git actions";
16373
+ button.addEventListener("click", (event) => {
16374
+ event.stopPropagation();
16375
+ const rect = button.getBoundingClientRect();
16376
+ showGitPanelContextMenu({
16377
+ preventDefault: () => event.preventDefault(),
16378
+ stopPropagation: () => event.stopPropagation(),
16379
+ clientX: rect.right,
16380
+ clientY: rect.bottom,
16381
+ currentTarget: button,
16382
+ }, context);
16383
+ });
16384
+ button.addEventListener("keydown", (event) => {
16385
+ if (event.key === "Enter" || event.key === " ") event.stopPropagation();
16386
+ });
16387
+ return button;
16388
+ }
16389
+
16045
16390
  function bindGitPanelContextMenu(trigger, context) {
16046
16391
  trigger.setAttribute("aria-haspopup", "menu");
16047
16392
  trigger.addEventListener("contextmenu", (event) => showGitPanelContextMenu(event, context));
@@ -16149,7 +16494,7 @@ function renderGitPanelFile(entry, card, category) {
16149
16494
  const row = make("div", `git-side-panel-file ${category}`);
16150
16495
  row.dataset.gitPanelContinuityKey = `file:${card.root}:${category}:${entry.path}`;
16151
16496
  const fullPath = entry.oldPath ? `${entry.oldPath} → ${entry.path}` : entry.path;
16152
- row.title = `${fullPath} · Open in WebUI · Right-click for Git actions`;
16497
+ row.title = `${fullPath} · Open in WebUI · ⋯ or right-click for Git actions`;
16153
16498
  row.tabIndex = 0;
16154
16499
  row.setAttribute("role", "button");
16155
16500
  row.setAttribute("aria-label", `Open ${entry.name || entry.path} in WebUI, ${gitPanelStatsText(entry, category) || "no line statistics"}`);
@@ -16166,8 +16511,9 @@ function renderGitPanelFile(entry, card, category) {
16166
16511
  const statsText = gitPanelStatsText(entry, category);
16167
16512
  const stats = make("span", "git-side-panel-file-stats", statsText);
16168
16513
  stats.hidden = !statsText;
16169
- bindGitPanelContextMenu(row, { card, category, kind: "file", path: entry.path });
16170
- row.append(status, name, stats);
16514
+ const context = { card, category, kind: "file", path: entry.path };
16515
+ bindGitPanelContextMenu(row, context);
16516
+ row.append(status, name, stats, gitPanelOverflowButton(context, entry.name || entry.path));
16171
16517
  return row;
16172
16518
  }
16173
16519
 
@@ -16336,7 +16682,7 @@ function renderGitPanelRepositoryCard(card) {
16336
16682
  button.type = "button";
16337
16683
  button.dataset.gitPanelContinuityKey = `repository:${card.root}`;
16338
16684
  button.setAttribute("aria-expanded", expanded ? "true" : "false");
16339
- button.title = `${expanded ? "Collapse" : "Expand"} ${card.root} · Right-click for repository actions`;
16685
+ button.title = `${expanded ? "Collapse" : "Expand"} ${card.root} · ⋯ or right-click for repository actions`;
16340
16686
  const count = gitPanelChangeCount(snapshot?.data);
16341
16687
  button.append(
16342
16688
  make("span", "git-side-panel-repository-chevron", "›"),
@@ -16346,8 +16692,11 @@ function renderGitPanelRepositoryCard(card) {
16346
16692
  const copy = button.querySelector(".git-side-panel-repository-copy");
16347
16693
  copy.append(make("strong", undefined, gitPanelRootLabel(card.root)), make("span", undefined, card.root));
16348
16694
  button.addEventListener("click", () => toggleGitPanelRepository(card));
16349
- bindGitPanelContextMenu(button, { card, kind: "repository", path: card.root });
16350
- section.append(button);
16695
+ const repositoryContext = { card, kind: "repository", path: card.root };
16696
+ bindGitPanelContextMenu(button, repositoryContext);
16697
+ const header = make("div", "git-side-panel-repository-header");
16698
+ header.append(button, gitPanelOverflowButton(repositoryContext, gitPanelRootLabel(card.root)));
16699
+ section.append(header);
16351
16700
  if (expanded) section.append(renderGitPanelRepositoryContent(card, snapshot));
16352
16701
  return section;
16353
16702
  }
@@ -16410,7 +16759,7 @@ function renderGitPanel() {
16410
16759
  ? "No terminal tabs are open."
16411
16760
  : discovering
16412
16761
  ? "Discovering repositories…"
16413
- : `${repositoryCount} Git ${repositoryCount === 1 ? "repository" : "repositories"} · Right-click for actions`;
16762
+ : `${repositoryCount} Git ${repositoryCount === 1 ? "repository" : "repositories"} · ⋯ or right-click for actions`;
16414
16763
  }
16415
16764
  ensureGitPanelRepositoriesDiscovered();
16416
16765
  ensureGitPanelVisibleRepositoriesFresh(cards);
@@ -17077,10 +17426,11 @@ async function switchTab(tabId) {
17077
17426
  focusPromptInput({ defer: true });
17078
17427
  connectEvents(tabContext);
17079
17428
  await refreshAll(tabContext);
17429
+ noteRecentFullRefresh();
17080
17430
  if (isCurrentTabContext(tabContext)) markTabOutputSeen();
17081
17431
  await refreshThemeCatalog(tabContext).catch((error) => addEvent(`Custom theme catalog refresh failed: ${error.message || String(error)}`, "warn"));
17082
17432
  if (!subagentLaunchSlotDraftIsDirty()) {
17083
- loadSubagentLaunchSlotConfig({ tabId }).catch(() => {});
17433
+ loadSubagentLaunchSlotConfigWhenVisible({ tabId }).catch(() => {});
17084
17434
  } else {
17085
17435
  renderSubagentLaunchSlots();
17086
17436
  }
@@ -17285,11 +17635,21 @@ async function confirmCloseTerminalTabs(targetTabs, label) {
17285
17635
  });
17286
17636
  }
17287
17637
 
17638
+ async function reopenClosedTerminalTab(tabId) {
17639
+ const response = await api("/api/tabs/reopen", { method: "POST", body: { id: tabId }, scoped: false });
17640
+ await refreshTabs();
17641
+ const reopened = response.data?.tab?.id;
17642
+ if (reopened) await switchTab(reopened);
17643
+ }
17644
+
17288
17645
  async function closeTerminalTabs(tabIds, { label = "selected terminal tabs", allowEmpty = false } = {}) {
17289
17646
  const targetIds = [...new Set(tabIds.filter(Boolean))];
17290
17647
  const targetTabs = targetIds.map((id) => tabs.find((item) => item.id === id)).filter(Boolean);
17291
17648
  if (!targetTabs.length) return;
17292
- if (!(await confirmCloseTerminalTabs(targetTabs, label))) return;
17649
+ // Closing one idle tab is routine and reversible (its session stays resumable), so it closes at
17650
+ // once with an Undo instead of a confirmation. Anything with running work still asks first.
17651
+ const quickClose = targetTabs.length === 1 && !tabHasActiveAgent(targetTabs[0]) && !allowEmpty;
17652
+ if (!quickClose && !(await confirmCloseTerminalTabs(targetTabs, label))) return;
17293
17653
 
17294
17654
  const closedActiveTab = targetTabs.some((tab) => tab.id === activeTabId);
17295
17655
  const fallbackTabId = tabs.find((item) => !targetIds.includes(item.id))?.id || null;
@@ -17315,6 +17675,14 @@ async function closeTerminalTabs(tabIds, { label = "selected terminal tabs", all
17315
17675
  syncTerminalCustomGroupsWithTabs(tabs);
17316
17676
  clearOpenTerminalTabGroup(null, { force: true });
17317
17677
  if (!tabs.length) setWorkspaceDashboardCollapsed(false, { persist: false });
17678
+ if (quickClose && closedIds.length === 1) {
17679
+ const closedTitle = targetTabs[0].title || "tab";
17680
+ offerUndo({
17681
+ message: `Closed ${closedTitle}.`,
17682
+ undo: () => reopenClosedTerminalTab(closedIds[0]),
17683
+ successMessage: `${closedTitle} reopened.`,
17684
+ });
17685
+ }
17318
17686
 
17319
17687
  const activeTabNeedsFallback = closedIds.includes(activeTabId) || !tabs.some((item) => item.id === activeTabId);
17320
17688
  if (activeTabNeedsFallback) {
@@ -17361,6 +17729,7 @@ async function initializeTabs() {
17361
17729
  restoreTerminalCustomGroups();
17362
17730
  syncTerminalCustomGroupsWithTabs(tabs, { persist: false });
17363
17731
  restoreMobileContinuityState();
17732
+ restoreDesktopDrafts();
17364
17733
  resetActiveTabUi();
17365
17734
  renderTabs();
17366
17735
  restoreActiveDraft();
@@ -17379,9 +17748,10 @@ async function initializeTabs() {
17379
17748
  connectEvents(tabContext);
17380
17749
  if (activeTabId) {
17381
17750
  await refreshAll(tabContext);
17751
+ noteRecentFullRefresh();
17382
17752
  if (isCurrentTabContext(tabContext)) markTabOutputSeen();
17383
17753
  if (!subagentLaunchSlotDraftIsDirty() || subagentLaunchSlotConfigTabId !== activeTabId) {
17384
- loadSubagentLaunchSlotConfig().catch(() => {});
17754
+ loadSubagentLaunchSlotConfigWhenVisible().catch(() => {});
17385
17755
  }
17386
17756
  refreshSamplingParametersForTabContext(tabContext);
17387
17757
  await refreshThemeCatalog(tabContext).catch((error) => addEvent(`Custom theme catalog refresh failed: ${error.message || String(error)}`, "warn"));
@@ -17439,7 +17809,7 @@ function jumpToChatEvent(line) {
17439
17809
  }
17440
17810
  }
17441
17811
 
17442
- function addEvent(message, level = "info", { toolCallId = "" } = {}) {
17812
+ function addEvent(message, level = "info", { toolCallId = "", notify = true } = {}) {
17443
17813
  const occurredAt = Date.now();
17444
17814
  const line = make("button", `event ${level}`.trim());
17445
17815
  line.type = "button";
@@ -17451,6 +17821,122 @@ function addEvent(message, level = "info", { toolCallId = "" } = {}) {
17451
17821
  line.addEventListener("click", () => jumpToChatEvent(line));
17452
17822
  elements.eventLog.prepend(line);
17453
17823
  while (elements.eventLog.children.length > 120) elements.eventLog.lastElementChild?.remove();
17824
+ if (notify && (level === "error" || level === "warn")) {
17825
+ showNoticeToast(message, level);
17826
+ noteUnreadEvent();
17827
+ }
17828
+ }
17829
+
17830
+ // --- Non-blocking warn/error notices -------------------------------------------------------
17831
+ // The Events log lives in a collapsed Control Deck section, so on its own it makes failures look
17832
+ // like "nothing happened". Warnings and errors additionally surface as a short-lived toast (max 3,
17833
+ // deduplicated) with a shortcut to the Events log, and the Events header shows an unread count.
17834
+ function noticeToastTimeout(level) {
17835
+ return NOTICE_TOAST_TIMEOUT_MS[level] || (level === "error" ? NOTICE_TOAST_TIMEOUT_MS.error : NOTICE_TOAST_TIMEOUT_MS.warn);
17836
+ }
17837
+
17838
+ function removeNoticeToast(entry) {
17839
+ const index = noticeToasts.indexOf(entry);
17840
+ if (index >= 0) noticeToasts.splice(index, 1);
17841
+ clearTimeout(entry.timer);
17842
+ entry.node.remove();
17843
+ }
17844
+
17845
+ function armNoticeToastTimer(entry) {
17846
+ clearTimeout(entry.timer);
17847
+ entry.timer = setTimeout(() => removeNoticeToast(entry), noticeToastTimeout(entry.level));
17848
+ }
17849
+
17850
+ function showNoticeToast(message, level = "warn") {
17851
+ const stack = elements.noticeToastStack;
17852
+ const text = String(message || "").trim();
17853
+ if (!stack || !text) return null;
17854
+ const existing = noticeToasts.find((entry) => entry.level === level && entry.text === text);
17855
+ if (existing) {
17856
+ existing.count += 1;
17857
+ existing.countNode.textContent = `×${existing.count}`;
17858
+ existing.countNode.hidden = false;
17859
+ armNoticeToastTimer(existing);
17860
+ return existing;
17861
+ }
17862
+ const node = make("div", `notice-toast ${level}`);
17863
+ node.setAttribute("role", level === "error" ? "alert" : "status");
17864
+ const messageNode = make("span", "notice-toast-message", text);
17865
+ const countNode = make("span", "notice-toast-count", "");
17866
+ countNode.hidden = true;
17867
+ messageNode.append(countNode);
17868
+ const eventsButton = make("button", "notice-toast-events", "Events");
17869
+ eventsButton.type = "button";
17870
+ eventsButton.title = "Open the Events log in the Control Deck";
17871
+ const dismissButton = make("button", "notice-toast-dismiss", "×");
17872
+ dismissButton.type = "button";
17873
+ dismissButton.setAttribute("aria-label", "Dismiss notification");
17874
+ node.append(messageNode, eventsButton, dismissButton);
17875
+ const entry = { node, level, text, count: 1, countNode, timer: null };
17876
+ eventsButton.addEventListener("click", () => {
17877
+ removeNoticeToast(entry);
17878
+ revealEventsSection();
17879
+ });
17880
+ dismissButton.addEventListener("click", () => removeNoticeToast(entry));
17881
+ node.addEventListener("pointerenter", () => clearTimeout(entry.timer));
17882
+ node.addEventListener("pointerleave", () => armNoticeToastTimer(entry));
17883
+ noticeToasts.push(entry);
17884
+ stack.append(node);
17885
+ while (noticeToasts.length > NOTICE_TOAST_LIMIT) removeNoticeToast(noticeToasts[0]);
17886
+ armNoticeToastTimer(entry);
17887
+ return entry;
17888
+ }
17889
+
17890
+ function eventsSectionRecord() {
17891
+ return sidePanelSectionRecords().find((record) => record.id === "events") || null;
17892
+ }
17893
+
17894
+ function eventsSectionIsVisibleAndExpanded() {
17895
+ const record = eventsSectionRecord();
17896
+ if (!record || record.section.hidden || record.section.classList.contains("collapsed")) return false;
17897
+ return !document.body.classList.contains("side-panel-collapsed") || document.body.classList.contains("control-deck-left");
17898
+ }
17899
+
17900
+ function renderEventsUnreadBadge() {
17901
+ const badge = elements.eventsUnreadBadge;
17902
+ if (!badge) return;
17903
+ badge.textContent = eventsUnreadCount > 99 ? "99+" : String(eventsUnreadCount);
17904
+ badge.hidden = eventsUnreadCount === 0;
17905
+ badge.setAttribute("aria-label", `${eventsUnreadCount} unread warning${eventsUnreadCount === 1 ? "" : "s"} or errors`);
17906
+ }
17907
+
17908
+ function noteUnreadEvent() {
17909
+ if (eventsSectionIsVisibleAndExpanded()) return;
17910
+ eventsUnreadCount += 1;
17911
+ renderEventsUnreadBadge();
17912
+ }
17913
+
17914
+ function clearUnreadEvents() {
17915
+ if (!eventsUnreadCount) return;
17916
+ eventsUnreadCount = 0;
17917
+ renderEventsUnreadBadge();
17918
+ }
17919
+
17920
+ function revealSidePanelSectionById(id) {
17921
+ const record = sidePanelSectionRecords().find((entry) => entry.id === id);
17922
+ if (!record) return;
17923
+ if (record.section.hidden) setSidePanelSectionVisible(record, true);
17924
+ if (document.body.classList.contains("side-panel-collapsed") && !document.body.classList.contains("control-deck-left")) setSidePanelCollapsed(false, { focusPanel: true });
17925
+ if (record.section.classList.contains("collapsed")) setSidePanelSectionCollapsed(record, false);
17926
+ queueMicrotask(() => {
17927
+ record.section.scrollIntoView?.({ block: "nearest" });
17928
+ record.button?.focus?.({ preventScroll: true });
17929
+ });
17930
+ }
17931
+
17932
+ function revealEventsSection() {
17933
+ const record = eventsSectionRecord();
17934
+ if (!record) return;
17935
+ if (record.section.hidden) setSidePanelSectionVisible(record, true);
17936
+ if (document.body.classList.contains("side-panel-collapsed") && !document.body.classList.contains("control-deck-left")) setSidePanelCollapsed(false);
17937
+ if (record.section.classList.contains("collapsed")) setSidePanelSectionCollapsed(record, false);
17938
+ clearUnreadEvents();
17939
+ queueMicrotask(() => record.section.scrollIntoView?.({ block: "nearest" }));
17454
17940
  }
17455
17941
 
17456
17942
  function browserNotificationSupported() {
@@ -17745,6 +18231,24 @@ function formatDate(value) {
17745
18231
  return Number.isNaN(date.getTime()) ? "" : date.toLocaleString();
17746
18232
  }
17747
18233
 
18234
+ // "3 min ago", "yesterday 14:05", "Aug 3, 09:12" — for lists where raw ISO stamps were shown.
18235
+ function formatRelativeDate(value, now = Date.now()) {
18236
+ if (!value) return "";
18237
+ const date = typeof value === "number" ? new Date(value) : new Date(String(value));
18238
+ const time = date.getTime();
18239
+ if (Number.isNaN(time)) return String(value);
18240
+ const diff = Math.max(0, now - time);
18241
+ const minute = 60_000;
18242
+ const hour = 60 * minute;
18243
+ const day = 24 * hour;
18244
+ if (diff < minute) return "just now";
18245
+ if (diff < hour) return `${Math.round(diff / minute)} min ago`;
18246
+ if (diff < day && new Date(now).getDate() === date.getDate()) return `today ${date.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })}`;
18247
+ if (diff < 2 * day) return `yesterday ${date.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })}`;
18248
+ if (diff < 7 * day) return `${Math.round(diff / day)} days ago`;
18249
+ return date.toLocaleDateString([], { month: "short", day: "numeric", ...(new Date(now).getFullYear() === date.getFullYear() ? {} : { year: "numeric" }) });
18250
+ }
18251
+
17748
18252
  function stripAnsi(text) {
17749
18253
  return String(text ?? "").replace(/(?:\x1B|\u241B)(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g, "");
17750
18254
  }
@@ -17895,7 +18399,9 @@ function formatStatusEntry(key, value) {
17895
18399
 
17896
18400
  function shortModelLabel(model) {
17897
18401
  if (!model) return "unknown";
17898
- return `(${model.provider}) ${model.id}`;
18402
+ // Model id first: when a narrow footer chip truncates from the end, the useful part survives
18403
+ // ("qwen3.6-35b-a3b · lmstu…" instead of "(lmstu…").
18404
+ return `${model.id} · ${model.provider}`;
17899
18405
  }
17900
18406
 
17901
18407
  function footerThinkingLevelLabel(level) {
@@ -17948,6 +18454,37 @@ function footerThinkingLevels() {
17948
18454
  return levels.length ? levels : ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
17949
18455
  }
17950
18456
 
18457
+ // Which thinking levels the active model actually honors (mirrors the server-side rule used for
18458
+ // launch slots): non-reasoning models only "off"; xhigh/max only when the model maps them.
18459
+ function activeModelSupportedThinkingLevels(model = currentState?.model) {
18460
+ const catalogModel = model && Array.isArray(availableModels)
18461
+ ? availableModels.find((candidate) => candidate?.provider === model.provider && candidate?.id === model.id) || model
18462
+ : model;
18463
+ if (!catalogModel || typeof catalogModel.reasoning !== "boolean") return null; // unknown → don't restrict
18464
+ if (!catalogModel.reasoning) return ["off"];
18465
+ const mapping = catalogModel.thinkingLevelMap && typeof catalogModel.thinkingLevelMap === "object" ? catalogModel.thinkingLevelMap : {};
18466
+ return footerThinkingLevels().filter((level) => {
18467
+ if (mapping[level] === null) return false;
18468
+ if (["xhigh", "max"].includes(level)) return typeof mapping[level] === "string" || !Object.keys(mapping).length;
18469
+ return true;
18470
+ });
18471
+ }
18472
+
18473
+ function thinkingLevelSupportedByActiveModel(level) {
18474
+ const supported = activeModelSupportedThinkingLevels();
18475
+ return !supported || supported.includes(level);
18476
+ }
18477
+
18478
+ function syncThinkingSelectSupport() {
18479
+ const supported = activeModelSupportedThinkingLevels();
18480
+ for (const option of elements.thinkingSelect?.options || []) {
18481
+ const ok = !supported || supported.includes(option.value);
18482
+ option.disabled = !ok && option.value !== elements.thinkingSelect.value;
18483
+ const base = option.dataset.baseLabel || (option.dataset.baseLabel = option.textContent);
18484
+ option.textContent = ok ? base : `${base} (not supported by this model)`;
18485
+ }
18486
+ }
18487
+
17951
18488
  function formatFooterTokenCount(value) {
17952
18489
  const n = Math.max(0, Number(value) || 0);
17953
18490
  if (n < 1000) return `${Math.round(n)}`;
@@ -18955,6 +19492,39 @@ function normalizeFooterPayloadChip(value, index) {
18955
19492
  return chip;
18956
19493
  }
18957
19494
 
19495
+ function normalizeFooterProviderUsageWindow(value) {
19496
+ if (!value || typeof value !== "object") return null;
19497
+ const label = cleanFooterPayloadText(value.label, "Usage window", 32);
19498
+ const usedPercent = Number(value.usedPercent);
19499
+ if (!Number.isFinite(usedPercent) || usedPercent < 0 || usedPercent > 100) return null;
19500
+ const window = { label, usedPercent };
19501
+ const windowMinutes = typeof value.windowMinutes === "number" ? value.windowMinutes : Number.NaN;
19502
+ if (Number.isFinite(windowMinutes) && windowMinutes > 0) window.windowMinutes = windowMinutes;
19503
+ const resetAt = typeof value.resetAt === "number" ? value.resetAt : Number.NaN;
19504
+ if (Number.isFinite(resetAt) && resetAt >= 0) window.resetAt = resetAt;
19505
+ const resetAfterSeconds = typeof value.resetAfterSeconds === "number" ? value.resetAfterSeconds : Number.NaN;
19506
+ if (Number.isFinite(resetAfterSeconds) && resetAfterSeconds >= 0) window.resetAfterSeconds = resetAfterSeconds;
19507
+ return window;
19508
+ }
19509
+
19510
+ function normalizeFooterProviderUsage(value) {
19511
+ if (!value || typeof value !== "object") return null;
19512
+ if (value.provider !== "anthropic" && value.provider !== "openai-codex") return null;
19513
+ const capturedAt = typeof value.capturedAt === "number" ? value.capturedAt : Number.NaN;
19514
+ if (!Number.isFinite(capturedAt) || capturedAt <= 0) return null;
19515
+ const primary = normalizeFooterProviderUsageWindow(value.primary);
19516
+ const secondary = normalizeFooterProviderUsageWindow(value.secondary);
19517
+ if (!primary && !secondary) return null;
19518
+ const plan = cleanFooterPayloadText(value.plan, "", 80);
19519
+ return {
19520
+ provider: value.provider,
19521
+ capturedAt,
19522
+ ...(primary ? { primary } : {}),
19523
+ ...(secondary ? { secondary } : {}),
19524
+ ...(plan ? { plan } : {}),
19525
+ };
19526
+ }
19527
+
18958
19528
  function currentGitFooterCacheCwd(tabId = activeTabId) {
18959
19529
  const tab = tabs.find((item) => item.id === tabId) || activeTab();
18960
19530
  return latestWorkspace?.cwd || tab?.cwd || "";
@@ -18968,8 +19538,9 @@ function parseGitFooterWebuiPayloadRaw(raw) {
18968
19538
  const main = Array.isArray(parsed.main) ? parsed.main.map(normalizeFooterPayloadChip).filter(Boolean).slice(0, 8) : [];
18969
19539
  const meta = Array.isArray(parsed.meta) ? parsed.meta.map(normalizeFooterPayloadChip).filter(Boolean).slice(0, 10) : [];
18970
19540
  const visibility = normalizeGitFooterWebuiVisibility(parsed.visibility);
18971
- if (!main.length && !meta.length && !parsed.visibility) return null;
18972
- return { main, meta, visibility };
19541
+ const providerUsage = normalizeFooterProviderUsage(parsed.providerUsage);
19542
+ if (!main.length && !meta.length && !parsed.visibility && !providerUsage) return null;
19543
+ return { main, meta, visibility, ...(providerUsage ? { providerUsage } : {}) };
18973
19544
  } catch {
18974
19545
  return null;
18975
19546
  }
@@ -19970,9 +20541,15 @@ function gitFileActionButtons(actions) {
19970
20541
  const button = make("button", `git-file-action ${action.className || ""}`.trim(), action.label);
19971
20542
  button.type = "button";
19972
20543
  button.title = action.title || action.label;
20544
+ if (action.path) button.dataset.gitFileActionPath = action.path;
20545
+ if (action.path && gitChangesState.busyPath === action.path) {
20546
+ button.disabled = true;
20547
+ button.setAttribute("aria-busy", "true");
20548
+ }
19973
20549
  button.addEventListener("click", (event) => {
19974
20550
  event.preventDefault();
19975
20551
  event.stopPropagation();
20552
+ if (button.disabled) return;
19976
20553
  action.onClick();
19977
20554
  });
19978
20555
  wrap.append(button);
@@ -20056,14 +20633,14 @@ function gitChangesFileActionsFor(sectionKey, path) {
20056
20633
  if (!path || gitChangesState.loading || gitChangesState.pulling || gitChangesState.fetching) return [];
20057
20634
  if (sectionKey === "unstaged") {
20058
20635
  return [
20059
- { label: "Stage", title: `git add -- ${path}`, onClick: () => runGitFileAction("stage", path) },
20636
+ { label: "Stage", path, title: `git add -- ${path}`, onClick: () => runGitFileAction("stage", path) },
20060
20637
  ...gitChangesCommonFileActions(path),
20061
- { label: "Discard", className: "danger", title: `git restore -- ${path} (destructive)`, onClick: () => runGitFileAction("discard", path) },
20638
+ { label: "Discard", path, className: "danger", title: `git restore -- ${path} (destructive)`, onClick: () => runGitFileAction("discard", path) },
20062
20639
  ];
20063
20640
  }
20064
20641
  if (sectionKey === "staged") {
20065
20642
  return [
20066
- { label: "Unstage", title: `git restore --staged -- ${path}`, onClick: () => runGitFileAction("unstage", path) },
20643
+ { label: "Unstage", path, title: `git restore --staged -- ${path}`, onClick: () => runGitFileAction("unstage", path) },
20067
20644
  ...gitChangesCommonFileActions(path),
20068
20645
  ];
20069
20646
  }
@@ -20071,9 +20648,18 @@ function gitChangesFileActionsFor(sectionKey, path) {
20071
20648
  return [];
20072
20649
  }
20073
20650
 
20651
+ // Per-file fold state for the Git Changes dialog survives the full re-render that follows every
20652
+ // stage/unstage/discard, so files the user collapsed stay collapsed.
20653
+ const gitChangesCollapsedFiles = new Set();
20654
+
20074
20655
  function renderGitDiffFile(file, actions = []) {
20075
20656
  const details = make("details", `git-diff-file ${file.className || ""}`.trim());
20076
- details.open = true;
20657
+ const fileKey = file.path || "diff";
20658
+ details.open = !gitChangesCollapsedFiles.has(fileKey);
20659
+ details.addEventListener("toggle", () => {
20660
+ if (details.open) gitChangesCollapsedFiles.delete(fileKey);
20661
+ else gitChangesCollapsedFiles.add(fileKey);
20662
+ });
20077
20663
  details.dataset.gitDiffFile = file.path || "diff";
20078
20664
  const summary = make("summary", "git-diff-file-summary");
20079
20665
  summary.append(
@@ -20194,9 +20780,9 @@ function renderGitUntrackedFile(entry) {
20194
20780
  if (!gitChangesState.loading && !gitChangesState.pulling && !gitChangesState.fetching) {
20195
20781
  const summary = node.querySelector("summary");
20196
20782
  const actions = gitFileActionButtons([
20197
- { label: "Stage", title: `git add -- ${entry.path}`, onClick: () => runGitFileAction("stage", entry.path) },
20783
+ { label: "Stage", path: entry.path, title: `git add -- ${entry.path}`, onClick: () => runGitFileAction("stage", entry.path) },
20198
20784
  ...gitChangesCommonFileActions(entry.path),
20199
- { label: "Delete", className: "danger", title: "Delete this untracked file from disk (destructive)", onClick: () => runGitFileAction("delete-untracked", entry.path) },
20785
+ { label: "Delete", path: entry.path, className: "danger", title: "Delete this untracked file from disk (destructive)", onClick: () => runGitFileAction("delete-untracked", entry.path) },
20200
20786
  ]);
20201
20787
  if (summary && actions) summary.append(actions);
20202
20788
  }
@@ -20505,7 +21091,7 @@ function renderGitChangesDialog() {
20505
21091
  return;
20506
21092
  }
20507
21093
  if (!data) {
20508
- body.append(make("div", "git-changes-empty", "Open from the footer CHANGES chip to load the current git diff."));
21094
+ body.append(make("div", "git-changes-empty", "No diff loaded yet. Open this from the CHANGES chip in the footer, or expand a repository in the Git panel."));
20509
21095
  return;
20510
21096
  }
20511
21097
 
@@ -20547,7 +21133,8 @@ function renderGitChangesDialog() {
20547
21133
  async function loadGitChangesDialog(tabContext = activeTabContext()) {
20548
21134
  const requestSerial = ++gitChangesRequestSerial;
20549
21135
  gitChangesUntrackedContentRequests.clear();
20550
- gitChangesState = { ...gitChangesState, loading: true, error: "", errorCode: "", errorHint: "", message: "", pullResult: null, tabId: tabContext.tabId || activeTabId, mode: "changes", commit: null };
21136
+ if (gitChangesState.tabId !== (tabContext.tabId || activeTabId)) gitChangesCollapsedFiles.clear();
21137
+ gitChangesState = { ...gitChangesState, loading: true, busyPath: "", error: "", errorCode: "", errorHint: "", message: "", pullResult: null, tabId: tabContext.tabId || activeTabId, mode: "changes", commit: null };
20551
21138
  renderGitChangesDialog();
20552
21139
  try {
20553
21140
  const [response, operationResponse] = await Promise.all([
@@ -20789,16 +21376,30 @@ async function runGitFileAction(action, path) {
20789
21376
  }[action];
20790
21377
  if (!config) return;
20791
21378
  if (config.confirm && !(await appConfirmText(config.confirm, { affected: path, confirmLabel: action }))) return;
21379
+ if (gitChangesState.busyPath) return; // one file action at a time; ignore double clicks
21380
+ // Remember which control had focus so it can be restored after the dialog re-renders.
21381
+ const focusedActionLabel = document.activeElement?.classList?.contains("git-file-action") ? document.activeElement.textContent : "";
21382
+ const restoreFocus = () => {
21383
+ if (!focusedActionLabel) return;
21384
+ const candidates = [...(elements.gitChangesBody?.querySelectorAll(`.git-file-action[data-git-file-action-path="${CSS.escape(path)}"]`) || [])];
21385
+ const target = candidates.find((node) => node.textContent === focusedActionLabel) || candidates[0]
21386
+ || elements.gitChangesBody?.querySelector(".git-file-action") || elements.gitChangesDialog?.querySelector("button");
21387
+ target?.focus?.({ preventScroll: true });
21388
+ };
21389
+ gitChangesState = { ...gitChangesState, busyPath: path };
21390
+ renderGitChangesDialog();
20792
21391
  try {
20793
21392
  const response = await api(config.url, { method: "POST", body: config.body, tabId });
20794
21393
  if (!response.ok) throw new Error([response.error, response.hint].filter(Boolean).join("\n") || `git ${action} failed`);
20795
- gitChangesState = { ...gitChangesState, data: response.data?.changes || gitChangesState.data, message: config.label, error: "", errorCode: "", errorHint: "" };
21394
+ gitChangesState = { ...gitChangesState, busyPath: "", data: response.data?.changes || gitChangesState.data, message: config.label, error: "", errorCode: "", errorHint: "" };
20796
21395
  addEvent(config.label, "success");
20797
21396
  renderGitChangesDialog();
21397
+ restoreFocus();
20798
21398
  requestGitFooterWebuiPayload(activeTabContext(tabId), { force: true });
20799
21399
  } catch (error) {
20800
- gitChangesState = { ...gitChangesState, error: error.message || String(error) };
21400
+ gitChangesState = { ...gitChangesState, busyPath: "", error: error.message || String(error) };
20801
21401
  renderGitChangesDialog();
21402
+ restoreFocus();
20802
21403
  addEvent(error.message || String(error), "error");
20803
21404
  }
20804
21405
  }
@@ -21195,8 +21796,8 @@ function renderGitUndoTools(body, data, busy) {
21195
21796
  row.append(gitToolsButton(
21196
21797
  "Amend last commit message",
21197
21798
  { disabled: busy || !data.canAmendMessage, title: data.canAmendMessage ? "git commit --amend -m <message>" : "Requires an unpushed commit and an empty staging area." },
21198
- () => {
21199
- const message = window.prompt("New commit message:", last?.subject || "");
21799
+ async () => {
21800
+ const message = await appPromptText({ title: "Amend last commit message", summary: `git commit --amend -m <message> · current: ${last?.subject || ""}`, defaultValue: last?.subject || "", confirmLabel: "Amend", validate: (value) => (String(value || "").trim() ? "" : "A commit message is required.") });
21200
21801
  if (!message || !message.trim()) return;
21201
21802
  runGitToolAction("undo", {
21202
21803
  url: "/api/git-undo/amend-message",
@@ -21341,10 +21942,10 @@ function renderGitTagTools(body, data, busy) {
21341
21942
  body.append(item);
21342
21943
  }
21343
21944
  const row = make("div", "git-operation-actions");
21344
- row.append(gitToolsButton("Create annotated tag…", { disabled: busy, title: "git tag -a <name> -m <message> (never pushed automatically)" }, () => {
21345
- const name = window.prompt("Tag name (annotated tag at HEAD):", "");
21945
+ row.append(gitToolsButton("Create annotated tag…", { disabled: busy, title: "git tag -a <name> -m <message> (never pushed automatically)" }, async () => {
21946
+ const name = await appPromptText({ title: "Create annotated tag", summary: "git tag -a <name> -m <message> at HEAD. Tags are never pushed automatically.", placeholder: "v1.2.3", confirmLabel: "Next", validate: (value) => (String(value || "").trim() ? "" : "A tag name is required.") });
21346
21947
  if (!name || !name.trim()) return;
21347
- const message = window.prompt("Tag message:", name.trim());
21948
+ const message = await appPromptText({ title: `Tag message for ${name.trim()}`, defaultValue: name.trim(), confirmLabel: "Create tag" });
21348
21949
  if (message === null) return;
21349
21950
  runGitToolAction("tags", {
21350
21951
  url: "/api/git-tags/create",
@@ -22028,6 +22629,7 @@ function applyOptimisticGitFooterBranch(branch, tabContext = activeTabContext())
22028
22629
  type: GIT_FOOTER_WEBUI_PAYLOAD_TYPE,
22029
22630
  version: GIT_FOOTER_WEBUI_PAYLOAD_VERSION,
22030
22631
  generatedAt: Date.now(),
22632
+ ...(payload.providerUsage ? { providerUsage: payload.providerUsage } : {}),
22031
22633
  main: payload.main,
22032
22634
  meta: payload.meta.map((chip) => chip.key === "git" ? { ...chip, value: nextBranch, title: `git branch: ${nextBranch}` } : chip),
22033
22635
  visibility: payload.visibility,
@@ -23005,7 +23607,8 @@ async function applyFooterThinking(level) {
23005
23607
  } else if (response.data?.level) {
23006
23608
  const requested = response.data.requestedLevel;
23007
23609
  const effective = response.data.level;
23008
- addEvent(requested && requested !== effective ? `Thinking effort set to ${effective} (requested ${requested}).` : `Thinking effort set to ${effective}.`, "info");
23610
+ if (requested && requested !== effective) addEvent(`Thinking effort set to ${effective}: the active model does not support ${requested}.`, "warn");
23611
+ else addEvent(`Thinking effort set to ${effective}.`, "info");
23009
23612
  }
23010
23613
  await refreshState(tabContext);
23011
23614
  } catch (error) {
@@ -23027,12 +23630,14 @@ function renderFooterThinkingPicker() {
23027
23630
  const current = currentState?.pendingThinkingLevel || currentState?.thinkingLevel || "off";
23028
23631
  for (const level of footerThinkingLevels()) {
23029
23632
  const selected = current === level;
23030
- const button = make("button", `footer-model-option${selected ? " active" : ""}`);
23633
+ const supported = thinkingLevelSupportedByActiveModel(level);
23634
+ const button = make("button", `footer-model-option${selected ? " active" : ""}${supported ? "" : " unsupported"}`);
23031
23635
  button.type = "button";
23032
23636
  button.setAttribute("role", "option");
23033
23637
  button.setAttribute("aria-selected", selected ? "true" : "false");
23034
- button.title = `Set thinking effort to ${level}`;
23035
- button.append(make("span", "footer-model-option-main", footerThinkingLevelLabel(level)));
23638
+ button.title = supported ? `Set thinking effort to ${level}` : `${level} is not supported by the active model`;
23639
+ button.disabled = !supported && !selected;
23640
+ button.append(make("span", "footer-model-option-main", supported ? footerThinkingLevelLabel(level) : `${footerThinkingLevelLabel(level)} · not supported`));
23036
23641
  button.addEventListener("click", () => applyFooterThinking(level));
23037
23642
  picker.append(button);
23038
23643
  }
@@ -23221,25 +23826,25 @@ function currentFastPick() {
23221
23826
  function updateAddFastPickButton() {
23222
23827
  if (!pathFastPicksReady) {
23223
23828
  elements.pathPickerAddFastPickButton.disabled = true;
23224
- elements.pathPickerAddFastPickButton.textContent = "Loading fast picks…";
23829
+ elements.pathPickerAddFastPickButton.textContent = "Loading pinned folders…";
23225
23830
  return;
23226
23831
  }
23227
23832
  const pick = currentFastPick();
23228
23833
  const exists = !!pick && loadFastPicks().some((item) => item.cwd === pick.cwd);
23229
23834
  elements.pathPickerAddFastPickButton.disabled = !pick || exists;
23230
- elements.pathPickerAddFastPickButton.textContent = exists ? "Fast pick added" : "Add fast pick";
23835
+ elements.pathPickerAddFastPickButton.textContent = exists ? "Pinned" : "Pin this folder";
23231
23836
  }
23232
23837
 
23233
23838
  function renderFastPicks() {
23234
23839
  const picks = loadFastPicks();
23235
23840
  elements.pathPickerFastPicks.replaceChildren();
23236
23841
  if (!pathFastPicksReady) {
23237
- elements.pathPickerFastPicks.append(make("div", "path-picker-fast-picks-empty muted", "Loading fast picks…"));
23842
+ elements.pathPickerFastPicks.append(make("div", "path-picker-fast-picks-empty muted", "Loading pinned folders…"));
23238
23843
  updateAddFastPickButton();
23239
23844
  return;
23240
23845
  }
23241
23846
  if (picks.length === 0) {
23242
- elements.pathPickerFastPicks.append(make("div", "path-picker-fast-picks-empty muted", "No fast picks yet."));
23847
+ elements.pathPickerFastPicks.append(make("div", "path-picker-fast-picks-empty muted", "No pinned folders yet. Pin the folders you switch to often."));
23243
23848
  updateAddFastPickButton();
23244
23849
  return;
23245
23850
  }
@@ -23247,7 +23852,7 @@ function renderFastPicks() {
23247
23852
  for (const pick of picks) {
23248
23853
  const item = make("span", "path-picker-fast-pick");
23249
23854
  const jump = pathPickerButton(fastPickLabel(pick), pick.cwd, () => loadPathPickerDirectory(pick.cwd), "path-picker-fast-pick-button");
23250
- const remove = pathPickerButton("×", `Remove fast pick ${pick.cwd}`, async () => {
23855
+ const remove = pathPickerButton("×", `Unpin ${pick.cwd}`, async () => {
23251
23856
  await saveFastPicks(loadFastPicks().filter((item) => item.cwd !== pick.cwd));
23252
23857
  }, "path-picker-fast-pick-remove");
23253
23858
  item.append(jump, remove);
@@ -23405,6 +24010,7 @@ async function changeActiveTabCwd() {
23405
24010
  }
23406
24011
 
23407
24012
  if (!(await appConfirmText(`Restart ${tab.title} in:\n${cwd}\n\nCurrent in-flight work in this tab will be stopped. The conversation continues in the new directory.`, { affected: tab.title, confirmLabel: "Change working folder" }))) return;
24013
+ if (activeFileViewer?.dirty && !(await confirmDiscardEdits({ what: "unsaved file edits", target: activeFileViewer.path }))) return;
23408
24014
 
23409
24015
  saveActiveDraft();
23410
24016
  if (isCurrentTabContext(tabContext)) {
@@ -23980,6 +24586,54 @@ function initializeCodexUsage() {
23980
24586
  codexUsageRenderTimer = setInterval(renderCodexUsage, CODEX_USAGE_RENDER_TICK_MS);
23981
24587
  }
23982
24588
 
24589
+ function claudeUsageWindowFromProvider(window, capturedAt) {
24590
+ if (!window) return null;
24591
+ const resetAt = Number(window.resetAt);
24592
+ const resetAfterSeconds = Number(window.resetAfterSeconds);
24593
+ const resetsAt = Number.isFinite(resetAt) && resetAt >= 0
24594
+ ? new Date(resetAt).toISOString()
24595
+ : Number.isFinite(resetAfterSeconds) && resetAfterSeconds >= 0
24596
+ ? new Date(capturedAt + resetAfterSeconds * 1000).toISOString()
24597
+ : undefined;
24598
+ return {
24599
+ label: window.label || "Usage window",
24600
+ usedPercent: window.usedPercent,
24601
+ ...(Number.isFinite(window.windowMinutes) ? { windowMinutes: window.windowMinutes } : {}),
24602
+ ...(resetsAt ? { resetsAt } : {}),
24603
+ };
24604
+ }
24605
+
24606
+ function claudeUsageFromGitFooterPayload(payload = parseGitFooterWebuiPayload()) {
24607
+ const providerUsage = payload?.providerUsage;
24608
+ if (providerUsage?.provider !== "anthropic") return null;
24609
+ const capturedAt = Number(providerUsage.capturedAt);
24610
+ if (!Number.isFinite(capturedAt) || capturedAt <= 0) return null;
24611
+ const windows = [providerUsage.primary, providerUsage.secondary]
24612
+ .map((window) => claudeUsageWindowFromProvider(window, capturedAt))
24613
+ .filter(Boolean);
24614
+ if (windows.length === 0) return null;
24615
+ return {
24616
+ available: true,
24617
+ providerId: "claude-code",
24618
+ source: "git-footer-status-provider-headers",
24619
+ fetchedAt: new Date(capturedAt).toISOString(),
24620
+ summary: "Live Anthropic subscription usage from provider response headers.",
24621
+ windows,
24622
+ activityTitle: "",
24623
+ activity: [],
24624
+ notes: [],
24625
+ };
24626
+ }
24627
+
24628
+ function syncClaudeUsageFromGitFooterPayload(payload = parseGitFooterWebuiPayload()) {
24629
+ const usage = claudeUsageFromGitFooterPayload(payload);
24630
+ if (!usage) return false;
24631
+ latestClaudeUsage = usage;
24632
+ claudeUsageError = null;
24633
+ renderClaudeUsage();
24634
+ return true;
24635
+ }
24636
+
23983
24637
  function claudeUsageResetDate(window) {
23984
24638
  const resetAt = window?.resetsAt ? new Date(window.resetsAt) : null;
23985
24639
  if (resetAt && Number.isFinite(resetAt.getTime())) return resetAt;
@@ -24124,15 +24778,18 @@ function renderClaudeUsage() {
24124
24778
  }
24125
24779
  }
24126
24780
 
24127
- async function refreshClaudeUsage() {
24781
+ async function refreshClaudeUsage({ forceCli = false } = {}) {
24782
+ if (!forceCli && syncClaudeUsageFromGitFooterPayload()) return;
24128
24783
  if (claudeUsageLoading) return;
24129
24784
  claudeUsageLoading = true;
24130
24785
  renderClaudeUsage();
24131
24786
  try {
24132
24787
  const response = await api("/api/claude-usage", { scoped: false });
24788
+ if (!forceCli && syncClaudeUsageFromGitFooterPayload()) return;
24133
24789
  latestClaudeUsage = response.data || null;
24134
24790
  claudeUsageError = null;
24135
24791
  } catch (error) {
24792
+ if (!forceCli && syncClaudeUsageFromGitFooterPayload()) return;
24136
24793
  claudeUsageError = error;
24137
24794
  } finally {
24138
24795
  claudeUsageLoading = false;
@@ -26139,9 +26796,38 @@ async function reloadActiveTabForSubagentLaunchSlots() {
26139
26796
  }
26140
26797
  }
26141
26798
 
26799
+ // The launch-slot editor lives in a collapsed <details> inside the (usually collapsed) Subagents
26800
+ // section, yet its config payload is one of the largest boot requests (~290 KB uncompressed).
26801
+ // Load it lazily: only when the editor is actually visible, otherwise on first reveal.
26802
+ let subagentLaunchSlotConfigDeferred = false;
26803
+
26804
+ function subagentLaunchSlotsVisible() {
26805
+ const details = elements.subagentLaunchSlots;
26806
+ if (!details || !details.open) return false;
26807
+ const section = details.closest?.("[data-side-panel-section]");
26808
+ return !section || (!section.hidden && !section.classList.contains("collapsed"));
26809
+ }
26810
+
26811
+ function loadSubagentLaunchSlotConfigWhenVisible(options = {}) {
26812
+ if (subagentLaunchSlotsVisible()) {
26813
+ subagentLaunchSlotConfigDeferred = false;
26814
+ return loadSubagentLaunchSlotConfig(options);
26815
+ }
26816
+ subagentLaunchSlotConfigDeferred = true;
26817
+ renderSubagentLaunchSlots();
26818
+ return Promise.resolve();
26819
+ }
26820
+
26821
+ function revealSubagentLaunchSlotConfigIfDeferred() {
26822
+ if (!subagentLaunchSlotConfigDeferred || !subagentLaunchSlotsVisible()) return;
26823
+ subagentLaunchSlotConfigDeferred = false;
26824
+ loadSubagentLaunchSlotConfig().catch(() => {});
26825
+ }
26826
+
26142
26827
  function initializeSubagentLaunchSlots() {
26143
26828
  renderSubagentLaunchSlots();
26144
- if (activeTabId) loadSubagentLaunchSlotConfig().catch(() => {});
26829
+ if (activeTabId) loadSubagentLaunchSlotConfigWhenVisible().catch(() => {});
26830
+ elements.subagentLaunchSlots?.addEventListener("toggle", () => revealSubagentLaunchSlotConfigIfDeferred());
26145
26831
  }
26146
26832
 
26147
26833
  function samplingParametersPath(tabId) {
@@ -26738,7 +27424,9 @@ function renderStatus() {
26738
27424
  );
26739
27425
  elements.stateDetails.append(overview, infoGrid);
26740
27426
 
26741
- if (shownThinkingLevel) elements.thinkingSelect.value = shownThinkingLevel;
27427
+ if (controlsPendingThinkingValue && shownThinkingLevel === controlsPendingThinkingValue) setControlsPendingThinking("");
27428
+ if (shownThinkingLevel && !controlsPendingThinkingValue) elements.thinkingSelect.value = shownThinkingLevel;
27429
+ syncThinkingSelectSupport();
26742
27430
  elements.compactButton.disabled = !!state?.isCompacting;
26743
27431
  elements.compactButton.textContent = state?.isCompacting ? "Compacting…" : "Compact";
26744
27432
  syncModelSelectToState();
@@ -28942,6 +29630,47 @@ function renderAppRunnerInputForm(run) {
28942
29630
  return form;
28943
29631
  }
28944
29632
 
29633
+ // Fast path for streaming app-runner output: same run, same lifecycle state, output only grew.
29634
+ function patchAppRunnerWidgetInPlace(tabId, previousRun, nextRun) {
29635
+ if (tabId !== activeTabId) return true; // not the visible tab; nothing to repaint here
29636
+ if (!previousRun || !nextRun || previousRun.id !== nextRun.id) return false;
29637
+ if (appRunnerIsRunning(previousRun) !== appRunnerIsRunning(nextRun)) return false;
29638
+ if ((previousRun.status || "") !== (nextRun.status || "") || Boolean(previousRun.truncated) !== Boolean(nextRun.truncated)) return false;
29639
+ const widget = elements.widgetArea?.querySelector(".app-runner-widget");
29640
+ const terminal = widget?.querySelector(".release-npm-terminal");
29641
+ if (!widget || !terminal) return false;
29642
+ const previousLines = appRunnerOutputLines(previousRun);
29643
+ const nextLines = appRunnerOutputLines(nextRun);
29644
+ if (nextLines.length < previousLines.length) return false;
29645
+ // The server keeps a bounded window; when it starts dropping the head, prefixes diverge.
29646
+ const sample = Math.min(previousLines.length, 3);
29647
+ for (let index = 0; index < sample; index += 1) {
29648
+ if (previousLines[previousLines.length - 1 - index] !== nextLines[previousLines.length - 1 - index]) return false;
29649
+ }
29650
+ const renderedCount = previousLines.length ? terminal.childElementCount : 0;
29651
+ if (renderedCount !== previousLines.length) return false;
29652
+ // A partial pending line is re-rendered as it grows: replace the last row when it changed.
29653
+ const pendingIndex = previousRun.pendingLine ? previousLines.length - 1 : -1;
29654
+ if (pendingIndex >= 0 && nextLines[pendingIndex] !== previousLines[pendingIndex]) {
29655
+ terminal.children[pendingIndex]?.remove();
29656
+ const rest = nextLines.slice(pendingIndex);
29657
+ if (!previousLines.length) terminal.replaceChildren();
29658
+ for (const line of rest) appendReleaseNpmTerminalLine(terminal, line);
29659
+ } else {
29660
+ if (!previousLines.length) terminal.replaceChildren();
29661
+ for (const line of nextLines.slice(previousLines.length)) appendReleaseNpmTerminalLine(terminal, line);
29662
+ }
29663
+ const count = widget.querySelector(".release-npm-stream-count");
29664
+ const lineCount = Math.max(nextRun.lineCount || 0, nextLines.length);
29665
+ if (count) count.textContent = `${lineCount} line${lineCount === 1 ? "" : "s"}`;
29666
+ const elapsedPill = widget.querySelector(".release-npm-pill.elapsed");
29667
+ const elapsed = appRunnerElapsedLabel(nextRun);
29668
+ if (elapsedPill && elapsed && elapsedPill.textContent !== elapsed) elapsedPill.textContent = elapsed;
29669
+ // Keep the terminal pinned to the bottom when it was already there.
29670
+ if (terminal.scrollHeight - terminal.scrollTop - terminal.clientHeight < 40) terminal.scrollTop = terminal.scrollHeight;
29671
+ return true;
29672
+ }
29673
+
28945
29674
  function renderAppRunnerWidget() {
28946
29675
  const data = activeAppRunnerData();
28947
29676
  const run = data.activeRun;
@@ -31641,7 +32370,7 @@ function renderGitWorkflow() {
31641
32370
  }
31642
32371
  } else if (gitWorkflow.step === "generate") {
31643
32372
  const commitInputButton = renderGitWorkflowManualCommitInput({ appendCommitButton: false });
31644
- addGitWorkflowAction("Run /git-staged-msg", () => runGitMessagePrompt(), "primary", false);
32373
+ addGitWorkflowAction("Generate commit message", () => runGitMessagePrompt(), "primary", false);
31645
32374
  addGitWorkflowAction("Preview current message files", () => loadGitWorkflowMessage({ requireFresh: false }), "", false);
31646
32375
  elements.gitWorkflowActions.append(commitInputButton);
31647
32376
  } else if (gitWorkflow.step === "generating") {
@@ -31675,7 +32404,7 @@ function renderGitWorkflow() {
31675
32404
  addGitWorkflowAction("Refresh PR description", () => loadGitWorkflowPr({ requireFresh: true }), "", false);
31676
32405
  } else if (gitWorkflow.step === "prReview") {
31677
32406
  addGitWorkflowAction("Create PR", () => createGitPrFromReview(), "primary", false);
31678
- addGitWorkflowAction("Regenerate /pr", () => runGitPrPrompt(), "", false);
32407
+ addGitWorkflowAction("Regenerate PR text", () => runGitPrPrompt(), "", false);
31679
32408
  } else if (gitWorkflow.step === "prCreating") {
31680
32409
  addGitWorkflowAction("Creating PR…", () => {}, "primary", true);
31681
32410
  } else if (gitWorkflow.step === "done") {
@@ -32136,7 +32865,7 @@ async function promptGitInitReadme(status, { runId, tabId }) {
32136
32865
  try {
32137
32866
  await api("/api/prompt", { method: "POST", body: { message: gitInitReadmePromptMessage({ stack, status, repoName }) }, tabId });
32138
32867
  if (!isCurrentGitWorkflowRun(runId, tabId)) return;
32139
- appendGitWorkflowOutput("README.md request accepted. Waiting for agent_end, then README.md/.gitignore will be checked and staged. If Pi does not create README.md, Web UI will use a minimal fallback README.", { tabId });
32868
+ appendGitWorkflowOutput("README.md request accepted. Waiting for Pi to finish, then README.md/.gitignore will be checked and staged. If Pi does not create README.md, Web UI will use a minimal fallback README.", { tabId });
32140
32869
  if (isCurrentTabContext(tabContext)) scheduleRefreshState(120, tabContext);
32141
32870
  setTimeout(() => {
32142
32871
  const currentWorkflow = gitWorkflowForTab(tabId, { create: false });
@@ -32178,7 +32907,7 @@ async function promptGitInitGitignore(status, { runId, tabId }) {
32178
32907
  try {
32179
32908
  await api("/api/prompt", { method: "POST", body: { message: gitInitGitignorePromptMessage({ stack, status, repoName }) }, tabId });
32180
32909
  if (!isCurrentGitWorkflowRun(runId, tabId)) return;
32181
- appendGitWorkflowOutput(".gitignore request accepted. Waiting for agent_end, then README.md/.gitignore will be staged. If Pi does not create .gitignore, Web UI will use sane fallback patterns.", { tabId });
32910
+ appendGitWorkflowOutput(".gitignore request accepted. Waiting for Pi to finish, then README.md/.gitignore will be staged. If Pi does not create .gitignore, Web UI will use sane fallback patterns.", { tabId });
32182
32911
  if (isCurrentTabContext(tabContext)) scheduleRefreshState(120, tabContext);
32183
32912
  setTimeout(() => {
32184
32913
  const currentWorkflow = gitWorkflowForTab(tabId, { create: false });
@@ -32432,16 +33161,16 @@ async function runGitMessagePrompt(tabId = gitWorkflowActionTabId()) {
32432
33161
  error: "",
32433
33162
  messageRequestedAt: requestedAt,
32434
33163
  messageGenerationId: "",
32435
- output: "Sending /git-staged-msg to Pi.\n\nCancel will request Pi abort.",
33164
+ output: "Asking Pi to write the commit message…\n\nCancel stops the request.",
32436
33165
  }, { tabId });
32437
- if (isCurrentTabContext(tabContext)) setRunIndicatorActivity("Sending /git-staged-msg to Pi…");
33166
+ if (isCurrentTabContext(tabContext)) setRunIndicatorActivity("Generating commit message…");
32438
33167
  try {
32439
33168
  const generation = await gitWorkflowRequest("/api/git-workflow/generate", { body: { kind: "commit", ...(expectedStagedContentHash ? { expectedStagedContentHash } : {}) }, runId, tabId });
32440
33169
  if (!generation || !isCurrentGitWorkflowRun(runId, tabId)) return;
32441
33170
  const generationId = String(generation.generationId || "").trim();
32442
33171
  if (!generationId) throw new Error("The WebUI server did not return a commit-message generation ID. Restart Pi Web UI and regenerate.");
32443
33172
  setGitWorkflow({ messageGenerationId: generationId }, { tabId });
32444
- appendGitWorkflowOutput(`/git-staged-msg accepted with ${generation.generation.provider}/${generation.generation.modelId} at ${generation.generation.thinkingLevel} effort. Waiting for agent_end, then both correlated message files will be loaded.`, { tabId });
33173
+ appendGitWorkflowOutput(`Commit message generation started with ${generation.generation.provider}/${generation.generation.modelId} at ${generation.generation.thinkingLevel} effort. Waiting for Pi to finish, then the short and long messages will be loaded.`, { tabId });
32445
33174
  if (isCurrentTabContext(tabContext)) scheduleRefreshState(120, tabContext);
32446
33175
  setTimeout(() => {
32447
33176
  const currentWorkflow = gitWorkflowForTab(tabId, { create: false });
@@ -32603,7 +33332,7 @@ async function runGitBranchNamePrompt(tabId = gitWorkflowActionTabId()) {
32603
33332
  try {
32604
33333
  const generation = await gitWorkflowRequest("/api/git-workflow/generate", { body: { kind: "branch", ...(expectedStagedContentHash ? { expectedStagedContentHash } : {}) }, runId, tabId });
32605
33334
  if (!generation || !isCurrentGitWorkflowRun(runId, tabId)) return;
32606
- appendGitWorkflowOutput(`Branch-name request accepted with ${generation.generation.provider}/${generation.generation.modelId} at ${generation.generation.thinkingLevel} effort. Waiting for agent_end, then the branch name will be loaded.`, { tabId });
33335
+ appendGitWorkflowOutput(`Branch-name request accepted with ${generation.generation.provider}/${generation.generation.modelId} at ${generation.generation.thinkingLevel} effort. Waiting for Pi to finish, then the branch name will be loaded.`, { tabId });
32607
33336
  if (isCurrentTabContext(tabContext)) scheduleRefreshState(120, tabContext);
32608
33337
  setTimeout(() => {
32609
33338
  const currentWorkflow = gitWorkflowForTab(tabId, { create: false });
@@ -32675,7 +33404,7 @@ async function createGitPrBranchWithSuggestion(suggestion, tabId = gitWorkflowAc
32675
33404
  const workflow = gitWorkflowForTab(tabId, { create: false });
32676
33405
  if (!workflow) return;
32677
33406
  const sourceWorkflow = { ...workflow, actionsDone: createGitWorkflowActionsDone(workflow.actionsDone) };
32678
- const proposedBranch = prompt("New PR branch worktree name (example: type/feature-name)", suggestion || defaultGitPrBranchName(workflow.message));
33407
+ const proposedBranch = await appPromptText({ title: "New PR branch worktree", summary: "Branch name for the pull-request worktree (example: type/feature-name).", defaultValue: suggestion || defaultGitPrBranchName(workflow.message), confirmLabel: "Create worktree" });
32679
33408
  if (expectedRunId !== undefined && !isCurrentGitWorkflowRun(expectedRunId, tabId)) return;
32680
33409
  if (proposedBranch === null) {
32681
33410
  setGitWorkflow({ step: "message", busy: false, output: `${formatCommitMessagePreview(sourceWorkflow.message)}\n\nPR branch worktree creation cancelled. Use Create PR worktree to generate a branch name again or Manual worktree to type one.` }, { tabId });
@@ -32946,7 +33675,7 @@ async function runGitPrPrompt(tabId = gitWorkflowActionTabId(), { prefixOutput =
32946
33675
  try {
32947
33676
  const generation = await gitWorkflowRequest("/api/git-workflow/generate", { body: { kind: "pr" }, runId, tabId });
32948
33677
  if (!generation || !isCurrentGitWorkflowRun(runId, tabId)) return;
32949
- appendGitWorkflowOutput(`/pr accepted with ${generation.generation.provider}/${generation.generation.modelId} at ${generation.generation.thinkingLevel} effort. Waiting for agent_end, then the PR description will be loaded.`, { tabId });
33678
+ appendGitWorkflowOutput(`PR text generation started with ${generation.generation.provider}/${generation.generation.modelId} at ${generation.generation.thinkingLevel} effort. Waiting for Pi to finish, then the PR description will be loaded.`, { tabId });
32950
33679
  if (isCurrentTabContext(tabContext)) scheduleRefreshState(120, tabContext);
32951
33680
  setTimeout(() => {
32952
33681
  const currentWorkflow = gitWorkflowForTab(tabId, { create: false });
@@ -34064,9 +34793,22 @@ function appendInlineMarkdown(parent, text, depth = 0) {
34064
34793
  continue;
34065
34794
  }
34066
34795
  }
34796
+ if (value[index] === "h" && (value.startsWith("http://", index) || value.startsWith("https://", index)) && !isMarkdownWordCharacter(value[index - 1])) {
34797
+ const match = value.slice(index).match(MARKDOWN_BARE_URL_REGEX);
34798
+ const href = match ? trimBareUrl(match[0]) : "";
34799
+ const safeHref = href ? safeMarkdownLinkHref(href) : "";
34800
+ if (safeHref) {
34801
+ const link = make("a");
34802
+ configureMarkdownLink(link, safeHref);
34803
+ link.textContent = href;
34804
+ parent.append(link);
34805
+ index += href.length;
34806
+ continue;
34807
+ }
34808
+ }
34067
34809
  const strongMarker = value.startsWith("**", index) ? "**" : value.startsWith("__", index) ? "__" : "";
34068
- if (strongMarker) {
34069
- const end = value.indexOf(strongMarker, index + 2);
34810
+ if (strongMarker && markdownCanOpenEmphasis(value, index, strongMarker)) {
34811
+ const end = findMarkdownEmphasisClose(value, index + 2, strongMarker);
34070
34812
  if (end > index + 2) {
34071
34813
  const strong = make("strong");
34072
34814
  appendInlineMarkdown(strong, value.slice(index + 2, end), depth + 1);
@@ -34086,8 +34828,8 @@ function appendInlineMarkdown(parent, text, depth = 0) {
34086
34828
  }
34087
34829
  }
34088
34830
  const emphasisMarker = value[index] === "*" || value[index] === "_" ? value[index] : "";
34089
- if (emphasisMarker && value[index + 1] !== emphasisMarker) {
34090
- const end = value.indexOf(emphasisMarker, index + 1);
34831
+ if (emphasisMarker && value[index + 1] !== emphasisMarker && markdownCanOpenEmphasis(value, index, emphasisMarker)) {
34832
+ const end = findMarkdownEmphasisClose(value, index + 1, emphasisMarker);
34091
34833
  if (end > index + 1) {
34092
34834
  const em = make("em");
34093
34835
  appendInlineMarkdown(em, value.slice(index + 1, end), depth + 1);
@@ -34096,13 +34838,59 @@ function appendInlineMarkdown(parent, text, depth = 0) {
34096
34838
  continue;
34097
34839
  }
34098
34840
  }
34099
- const nextSpecials = ["`", "[", "**", "__", "~~", "*", "_"]
34841
+ const nextSpecials = ["`", "[", "**", "__", "~~", "*", "_", "http://", "https://"]
34100
34842
  .map((marker) => value.indexOf(marker, index + 1))
34101
34843
  .filter((pos) => pos !== -1);
34102
34844
  appendPlain(nextSpecials.length ? Math.min(...nextSpecials) : value.length);
34103
34845
  }
34104
34846
  }
34105
34847
 
34848
+ // CommonMark-ish flanking rules so identifiers such as snake_case_name, MAX_RETRY_COUNT or
34849
+ // 2*3*4 stop turning into emphasis. `_` never opens/closes inside a word; `*` may not open
34850
+ // before whitespace or close after whitespace.
34851
+ const MARKDOWN_BARE_URL_REGEX = /^https?:\/\/[^\s<>"'`]+/;
34852
+
34853
+ function isMarkdownWordCharacter(character) {
34854
+ return Boolean(character) && /[\p{L}\p{N}_]/u.test(character);
34855
+ }
34856
+
34857
+ function markdownCanOpenEmphasis(value, index, marker) {
34858
+ const after = value[index + marker.length];
34859
+ if (!after || /\s/.test(after)) return false;
34860
+ if (marker[0] === "_" && isMarkdownWordCharacter(value[index - 1])) return false;
34861
+ return true;
34862
+ }
34863
+
34864
+ function markdownCanCloseEmphasis(value, index, marker) {
34865
+ const before = value[index - 1];
34866
+ if (!before || /\s/.test(before)) return false;
34867
+ if (marker[0] === "_" && isMarkdownWordCharacter(value[index + marker.length])) return false;
34868
+ return true;
34869
+ }
34870
+
34871
+ function findMarkdownEmphasisClose(value, from, marker) {
34872
+ let cursor = from;
34873
+ while (cursor < value.length) {
34874
+ const candidate = value.indexOf(marker, cursor);
34875
+ if (candidate === -1) return -1;
34876
+ // Skip runs longer than the marker (e.g. "***" when looking for "*") — they are not a clean close.
34877
+ const runEnd = candidate + marker.length;
34878
+ const overlong = marker.length === 1 && value[runEnd] === marker;
34879
+ if (!overlong && markdownCanCloseEmphasis(value, candidate, marker)) return candidate;
34880
+ cursor = overlong ? runEnd + 1 : candidate + 1;
34881
+ }
34882
+ return -1;
34883
+ }
34884
+
34885
+ function trimBareUrl(url) {
34886
+ let text = String(url || "");
34887
+ // Trailing punctuation usually belongs to the sentence, not the link.
34888
+ while (/[.,;:!?'"]$/.test(text)) text = text.slice(0, -1);
34889
+ // Balance closing parentheses (Wikipedia-style links keep their own parens).
34890
+ while (text.endsWith(")") && (text.match(/\(/g) || []).length < (text.match(/\)/g) || []).length) text = text.slice(0, -1);
34891
+ return text;
34892
+ }
34893
+
34106
34894
  function appendMarkdownParagraph(parent, lines) {
34107
34895
  const paragraph = make("p");
34108
34896
  lines.forEach((line, index) => {
@@ -34385,13 +35173,84 @@ function appendMarkdownTable(parent, rows) {
34385
35173
  }
34386
35174
 
34387
35175
  function markdownListMatch(line) {
34388
- const unordered = line.match(/^\s{0,3}[-*+]\s+(.+)$/);
34389
- if (unordered) return { ordered: false, text: unordered[1] };
34390
- const ordered = line.match(/^\s{0,3}(\d+)[.)]\s+(.+)$/);
34391
- if (ordered) return { ordered: true, start: Number(ordered[1]), text: ordered[2] };
35176
+ const unordered = line.match(/^(\s*)[-*+]\s+(.+)$/);
35177
+ if (unordered) return { ordered: false, text: unordered[2], indent: unordered[1].replace(/\t/g, " ").length, markerWidth: 2 };
35178
+ const ordered = line.match(/^(\s*)(\d+)[.)]\s+(.+)$/);
35179
+ if (ordered) return { ordered: true, start: Number(ordered[2]), text: ordered[3], indent: ordered[1].replace(/\t/g, " ").length, markerWidth: ordered[2].length + 2 };
34392
35180
  return null;
34393
35181
  }
34394
35182
 
35183
+ // Builds nested lists from a block of list lines using indentation: a marker line indented at
35184
+ // least two columns deeper than the current list starts a child list of the previous item;
35185
+ // indented non-marker lines continue the previous item's text.
35186
+ function parseMarkdownListTree(blockLines) {
35187
+ const lists = [];
35188
+ const stack = [];
35189
+ let lastItem = null;
35190
+ const newList = (match) => ({ ordered: match.ordered, start: match.ordered ? match.start : null, items: [], indent: match.indent });
35191
+ for (const line of blockLines) {
35192
+ const match = markdownListMatch(line);
35193
+ if (!match) {
35194
+ if (lastItem && line.trim()) lastItem.text += `\n${line.trim()}`;
35195
+ continue;
35196
+ }
35197
+ while (stack.length && match.indent < stack[stack.length - 1].indent) stack.pop();
35198
+ let top = stack[stack.length - 1];
35199
+ if (!top) {
35200
+ top = newList(match);
35201
+ lists.push(top);
35202
+ stack.push(top);
35203
+ } else if (match.indent >= top.indent + 2 && lastItem && lastItem.list === top) {
35204
+ top = newList(match);
35205
+ lastItem.children.push(top);
35206
+ stack.push(top);
35207
+ } else if (top.ordered !== match.ordered) {
35208
+ stack.pop();
35209
+ top = newList(match);
35210
+ const parentList = stack[stack.length - 1];
35211
+ const owner = parentList?.items[parentList.items.length - 1];
35212
+ if (owner) owner.children.push(top);
35213
+ else lists.push(top);
35214
+ stack.push(top);
35215
+ }
35216
+ const item = { text: match.text, children: [], list: top };
35217
+ top.items.push(item);
35218
+ lastItem = item;
35219
+ }
35220
+ return lists;
35221
+ }
35222
+
35223
+ function appendMarkdownListTree(parent, tree) {
35224
+ const build = (list) => {
35225
+ const element = make(list.ordered ? "ol" : "ul", "markdown-list");
35226
+ if (list.ordered && Number.isFinite(list.start) && list.start > 1) element.start = list.start;
35227
+ for (const item of list.items) {
35228
+ const li = make("li");
35229
+ const [firstLine, ...moreLines] = String(item.text).split("\n");
35230
+ const task = firstLine.match(/^\[( |x|X|-)\]\s+(.+)$/);
35231
+ if (task) {
35232
+ li.classList.add("markdown-task-item");
35233
+ const checkbox = make("input", "markdown-task-checkbox");
35234
+ checkbox.type = "checkbox";
35235
+ checkbox.disabled = true;
35236
+ checkbox.checked = task[1].toLowerCase() === "x";
35237
+ li.append(checkbox);
35238
+ appendInlineMarkdown(li, task[2]);
35239
+ } else {
35240
+ appendInlineMarkdown(li, firstLine);
35241
+ }
35242
+ for (const extra of moreLines) {
35243
+ li.append(make("br"));
35244
+ appendInlineMarkdown(li, extra);
35245
+ }
35246
+ for (const child of item.children) li.append(build(child));
35247
+ element.append(li);
35248
+ }
35249
+ return element;
35250
+ };
35251
+ for (const list of tree) parent.append(build(list));
35252
+ }
35253
+
34395
35254
  function appendMarkdownList(parent, items, ordered = false, start = null) {
34396
35255
  const list = make(ordered ? "ol" : "ul", "markdown-list");
34397
35256
  if (ordered && Number.isFinite(start) && start > 1) list.start = start;
@@ -34431,13 +35290,15 @@ function renderMarkdownInto(parent, text) {
34431
35290
  index += 1;
34432
35291
  continue;
34433
35292
  }
34434
- const fence = line.match(/^\s*```\s*([\w.+-]*)\s*$/);
35293
+ const fence = line.match(/^\s*(`{3,}|~{3,})\s*([\w.+-]*)\s*$/);
34435
35294
  if (fence) {
34436
35295
  flushParagraph();
34437
- const language = fence[1] || "";
35296
+ const delimiter = fence[1];
35297
+ const language = fence[2] || "";
35298
+ const closingFence = new RegExp(`^\\s*${delimiter[0] === "~" ? "~" : "\`"}{${delimiter.length},}\\s*$`);
34438
35299
  const codeLines = [];
34439
35300
  index += 1;
34440
- while (index < lines.length && !/^\s*```\s*$/.test(lines[index])) {
35301
+ while (index < lines.length && !closingFence.test(lines[index])) {
34441
35302
  codeLines.push(lines[index]);
34442
35303
  index += 1;
34443
35304
  }
@@ -34488,16 +35349,25 @@ function renderMarkdownInto(parent, text) {
34488
35349
  const listMatch = markdownListMatch(line);
34489
35350
  if (listMatch) {
34490
35351
  flushParagraph();
34491
- const ordered = listMatch.ordered;
34492
- const start = listMatch.start || null;
34493
- const items = [];
35352
+ // Collect the whole list block: marker lines plus indented continuation lines. A blank line
35353
+ // followed by an indented line stays in the list (loose list); anything else ends it.
35354
+ const blockLines = [];
34494
35355
  while (index < lines.length) {
34495
- const item = markdownListMatch(lines[index]);
34496
- if (!item || item.ordered !== ordered) break;
34497
- items.push(item.text);
34498
- index += 1;
35356
+ const current = lines[index];
35357
+ if (markdownListMatch(current) || (blockLines.length && /^\s{2,}\S/.test(current))) {
35358
+ blockLines.push(current);
35359
+ index += 1;
35360
+ continue;
35361
+ }
35362
+ if (!current.trim() && blockLines.length && index + 1 < lines.length && /^\s{2,}\S/.test(lines[index + 1]) && (markdownListMatch(lines[index + 1]) || true)) {
35363
+ blockLines.push("");
35364
+ index += 1;
35365
+ continue;
35366
+ }
35367
+ break;
34499
35368
  }
34500
- appendMarkdownList(parent, items, ordered, start);
35369
+ while (blockLines.length && !blockLines[blockLines.length - 1].trim()) blockLines.pop();
35370
+ appendMarkdownListTree(parent, parseMarkdownListTree(blockLines));
34501
35371
  continue;
34502
35372
  }
34503
35373
  paragraph.push(line);
@@ -34519,63 +35389,127 @@ function renderMarkdown(block, text) {
34519
35389
  }
34520
35390
 
34521
35391
  /**
34522
- * Incremental renderer for streaming assistant markdown. The block-based
34523
- * parser in renderMarkdownInto only ever closes a block at a blank line
34524
- * outside a code fence, so everything before the last such boundary is
34525
- * stable: it is parsed exactly once and its DOM is never rebuilt. Only the
34526
- * open tail is re-parsed per streaming tick, keeping per-tick cost flat
34527
- * instead of O(message length).
35392
+ * Streaming Markdown keeps the boundary automaton in transcript-owned
35393
+ * per-surface state. The scanner consumes only appended suffixes; open fences
35394
+ * and bounded-fallback tails reuse one mounted live subtree until an
35395
+ * authoritative close/completion render.
34528
35396
  */
34529
- let streamMarkdownState = null;
34530
-
34531
- function streamingMarkdownStableBoundary(text) {
34532
- const lines = text.split("\n");
34533
- let inFence = false;
34534
- let boundary = 0;
34535
- let offset = 0;
34536
- // Exclude the final line: it may still be streaming in.
34537
- for (let index = 0; index < lines.length - 1; index += 1) {
34538
- const line = lines[index];
34539
- if (inFence) {
34540
- if (/^\s*```\s*$/.test(line)) inFence = false;
34541
- } else if (/^\s*```\s*[\w.+-]*\s*$/.test(line)) {
34542
- inFence = true;
34543
- }
34544
- offset += line.length + 1;
34545
- if (!inFence && !line.trim()) boundary = offset;
34546
- }
34547
- return boundary;
35397
+ function streamingMarkdownStableBoundary(text, previousState, options) {
35398
+ return advanceStreamingMarkdownTail(previousState, text, options);
34548
35399
  }
34549
35400
 
34550
35401
  function clearStreamingMarkdownBlock(block) {
34551
35402
  while (block.firstChild) block.firstChild.remove();
34552
35403
  }
34553
35404
 
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" };
35405
+ function streamingLiveCodeSource(tail, boundaryInfo) {
35406
+ const relativeOffset = Math.max(0, Number(boundaryInfo.fenceContentOffset) - Number(boundaryInfo.boundary));
35407
+ return String(tail || "").slice(relativeOffset).replace(/\n+$/g, "");
35408
+ }
35409
+
35410
+ function syncStreamingLiveCodeLanguage(wrapper, codeNode, language) {
35411
+ const value = String(language || "");
35412
+ let label = wrapper.querySelector(":scope > .markdown-code-language");
35413
+ if (value && !label) {
35414
+ label = make("div", "markdown-code-language");
35415
+ wrapper.prepend(label);
35416
+ }
35417
+ if (label) {
35418
+ label.textContent = value;
35419
+ if (!value) label.remove();
35420
+ }
35421
+ codeNode.className = value ? `language-${value.replace(/[^a-z0-9_-]/gi, "")}` : "";
35422
+ }
35423
+
35424
+ function renderStreamingMarkdownLiveTail(parent, tail, boundaryInfo) {
35425
+ if (boundaryInfo.liveMode === "open-fence") {
35426
+ const wrapper = make("div", "markdown-code-block");
35427
+ const pre = make("pre", "code-block markdown-code");
35428
+ const codeNode = make("code");
35429
+ codeNode.append(document.createTextNode(streamingLiveCodeSource(tail, boundaryInfo)));
35430
+ pre.append(codeNode);
35431
+ wrapper.append(pre);
35432
+ syncStreamingLiveCodeLanguage(wrapper, codeNode, boundaryInfo.fenceLanguage);
35433
+ attachMarkdownCodeCopyButton(wrapper);
35434
+ parent.append(wrapper);
35435
+ return;
35436
+ }
35437
+ const paragraph = make("p", "streaming-markdown-plain-tail");
35438
+ paragraph.append(document.createTextNode(String(tail || "")));
35439
+ parent.append(paragraph);
35440
+ }
35441
+
35442
+ function appendStreamingMarkdownLiveTail(nodes, previousTail, tail, boundaryInfo) {
35443
+ const root = nodes.find((node) => node.nodeType === Node.ELEMENT_NODE);
35444
+ const textNode = boundaryInfo.liveMode === "open-fence"
35445
+ ? root?.querySelector(":scope > pre.markdown-code > code")?.firstChild
35446
+ : root?.firstChild;
35447
+ const value = boundaryInfo.liveMode === "open-fence"
35448
+ ? streamingLiveCodeSource(tail, boundaryInfo)
35449
+ : String(tail || "");
35450
+ if (!textNode || textNode.nodeType !== Node.TEXT_NODE) return;
35451
+ if (boundaryInfo.liveMode === "open-fence") {
35452
+ const codeNode = textNode.parentElement;
35453
+ syncStreamingLiveCodeLanguage(root, codeNode, boundaryInfo.fenceLanguage);
35454
+ }
35455
+ if (value.startsWith(textNode.data)) textNode.appendData(value.slice(textNode.data.length));
35456
+ else textNode.data = value;
34559
35457
  }
34560
35458
 
34561
- function renderStreamingMarkdown(block, text) {
35459
+ function renderStreamingMarkdown(block, text, { complete = false } = {}) {
34562
35460
  const profileStart = streamIsolationDebugLedger ? performance.now() : 0;
34563
35461
  const selectionSnapshot = captureChatTextSelection(block);
34564
35462
  const bubble = block?.closest(".message");
34565
- transcriptRenderer.reconcileMarkdownSurface({
35463
+ const result = transcriptRenderer.reconcileMarkdownSurface({
34566
35464
  key: `stream:${bubble?.dataset?.transcriptMessageKey || bubble?.dataset?.itemKey || "assistant"}`,
34567
35465
  surface: block,
34568
35466
  messageKey: bubble?.dataset?.transcriptMessageKey || bubble?.dataset?.itemKey || "live:assistant",
34569
35467
  kind: "assistant-final",
34570
35468
  text,
35469
+ complete,
34571
35470
  stableBoundary: streamingMarkdownStableBoundary,
34572
35471
  renderInto: renderMarkdownInto,
35472
+ renderLiveTail: renderStreamingMarkdownLiveTail,
35473
+ appendLiveTail: appendStreamingMarkdownLiveTail,
34573
35474
  });
34574
35475
  restoreChatTextSelection(selectionSnapshot);
34575
35476
  if (streamIsolationDebugLedger) {
34576
- const { tailBytes, tailKind } = streamingMarkdownTailProfile(String(text || ""));
34577
- recordStreamProfileDiagnostic({ type: "markdown-commit", ms: performance.now() - profileStart, textBytes: streamDiagnosticBytes(text), tailBytes, tailKind });
35477
+ const tailBytes = Math.max(0, streamDiagnosticBytes(text) - (Number(result.boundary) || 0) * 2);
35478
+ recordStreamProfileDiagnostic({ type: "markdown-commit", ms: performance.now() - profileStart, textBytes: streamDiagnosticBytes(text), tailBytes, tailKind: result.tailKind, boundaryScannedChars: result.scannedChars, reusedTail: result.reusedTail, authoritative: complete || result.liveMode === "authoritative" });
35479
+ }
35480
+ }
35481
+
35482
+ // Minimal lightbox: click an inline/transcript image (or attachment thumbnail) to view it large.
35483
+ let imageLightbox = null;
35484
+ function openImageLightbox(src, alt = "") {
35485
+ if (!src) return;
35486
+ if (!imageLightbox) {
35487
+ imageLightbox = document.createElement("dialog");
35488
+ imageLightbox.className = "image-lightbox";
35489
+ imageLightbox.setAttribute("aria-label", "Image preview");
35490
+ const figure = document.createElement("figure");
35491
+ const image = document.createElement("img");
35492
+ const caption = document.createElement("figcaption");
35493
+ const close = document.createElement("button");
35494
+ close.type = "button";
35495
+ close.className = "image-lightbox-close";
35496
+ close.textContent = "×";
35497
+ close.setAttribute("aria-label", "Close image preview");
35498
+ close.addEventListener("click", () => imageLightbox.close());
35499
+ imageLightbox.addEventListener("click", (event) => {
35500
+ if (event.target === imageLightbox) imageLightbox.close();
35501
+ });
35502
+ figure.append(image, caption);
35503
+ imageLightbox.append(close, figure);
35504
+ document.body.append(imageLightbox);
34578
35505
  }
35506
+ const image = imageLightbox.querySelector("img");
35507
+ const caption = imageLightbox.querySelector("figcaption");
35508
+ image.src = src;
35509
+ image.alt = alt || "";
35510
+ caption.textContent = alt || "";
35511
+ caption.hidden = !alt;
35512
+ if (!imageLightbox.open) imageLightbox.showModal();
34579
35513
  }
34580
35514
 
34581
35515
  function appendImage(parent, part) {
@@ -34586,7 +35520,14 @@ function appendImage(parent, part) {
34586
35520
  img.style.maxWidth = "100%";
34587
35521
  img.style.borderRadius = "0.6rem";
34588
35522
  img.src = `data:${part.mimeType || "image/png"};base64,${part.data || part.content || ""}`;
34589
- wrapper.append(img);
35523
+ // Click/Enter opens the image at full size (transcript images used to be view-only thumbnails).
35524
+ const button = make("button", "image-block-button");
35525
+ button.type = "button";
35526
+ button.title = "Open image at full size";
35527
+ button.setAttribute("aria-label", "Open image at full size");
35528
+ button.append(img);
35529
+ button.addEventListener("click", () => openImageLightbox(img.src, "attached image"));
35530
+ wrapper.append(button);
34590
35531
  parent.append(wrapper);
34591
35532
  }
34592
35533
 
@@ -34664,7 +35605,7 @@ async function sendLiveActionFeedback(item) {
34664
35605
  if (isCurrentTabContext(tabContext)) addEvent(`sent ${ACTION_FEEDBACK_REACTIONS[item.reaction]?.icon || "feedback"} action feedback as live steering`);
34665
35606
  }
34666
35607
 
34667
- function setActionFeedback(message, messageIndex, reaction) {
35608
+ async function setActionFeedback(message, messageIndex, reaction) {
34668
35609
  const tabId = activeTabId;
34669
35610
  if (!tabId || !ACTION_FEEDBACK_REACTIONS[reaction]) return;
34670
35611
  const key = actionFeedbackKey(message, messageIndex);
@@ -34672,7 +35613,7 @@ function setActionFeedback(message, messageIndex, reaction) {
34672
35613
  const existing = map.get(key);
34673
35614
  let comment = existing?.comment || "";
34674
35615
  if (reaction === "down") {
34675
- const nextComment = window.prompt("Optional comment for Pi about what to avoid:", comment);
35616
+ const nextComment = await appPromptText({ title: "What should Pi avoid?", summary: "Optional note sent with the thumbs-down feedback.", defaultValue: comment, confirmLabel: "Send feedback" });
34676
35617
  if (nextComment === null) return;
34677
35618
  comment = nextComment.trim();
34678
35619
  }
@@ -34769,7 +35710,7 @@ function renderActionFeedbackControls(bubble, message, messageIndex) {
34769
35710
  button.addEventListener("click", (event) => {
34770
35711
  event.preventDefault();
34771
35712
  event.stopPropagation();
34772
- setActionFeedback(message, messageIndex, reaction);
35713
+ setActionFeedback(message, messageIndex, reaction).catch((error) => addEvent(error.message || String(error), "error"));
34773
35714
  });
34774
35715
  controls.append(button);
34775
35716
  }
@@ -34875,7 +35816,7 @@ function renderContent(parent, content, { markdown = false } = {}) {
34875
35816
 
34876
35817
  function messageTitle(message) {
34877
35818
  if (message.role === "assistant") return message.title || "final output";
34878
- if (message.title) return message.title;
35819
+ if (message.title) return message.repeatCount > 1 ? `${message.title} (×${message.repeatCount})` : message.title;
34879
35820
  if (message.role === "thinking") return "thinking";
34880
35821
  if (message.role === "toolCall") return `tool call: ${message.toolName || "unknown"}`;
34881
35822
  if (message.role === "toolExecution") return toolExecutionTitle(message);
@@ -34920,7 +35861,7 @@ function visibleThinkingText(text) {
34920
35861
  return value;
34921
35862
  }
34922
35863
 
34923
- function renderThinkingMarkdown(block, text) {
35864
+ function renderThinkingMarkdown(block, text, { complete = false } = {}) {
34924
35865
  if (!block) return;
34925
35866
  block._rawThinkingText = String(text || "");
34926
35867
  const selectionSnapshot = captureChatTextSelection(block);
@@ -34931,8 +35872,11 @@ function renderThinkingMarkdown(block, text) {
34931
35872
  messageKey: bubble?.dataset?.transcriptMessageKey || bubble?.dataset?.itemKey || "live:thinking",
34932
35873
  kind: "assistant-thinking",
34933
35874
  text: block._rawThinkingText,
35875
+ complete,
34934
35876
  stableBoundary: streamingMarkdownStableBoundary,
34935
35877
  renderInto: renderMarkdownInto,
35878
+ renderLiveTail: renderStreamingMarkdownLiveTail,
35879
+ appendLiveTail: appendStreamingMarkdownLiveTail,
34936
35880
  });
34937
35881
  restoreChatTextSelection(selectionSnapshot);
34938
35882
  }
@@ -35123,8 +36067,44 @@ function assistantFinalOutputPart(part) {
35123
36067
  return null;
35124
36068
  }
35125
36069
 
36070
+ function latestPersistedAssistantFailureTimestamp(messages = latestMessages) {
36071
+ const lastUserIndex = (messages || []).findLastIndex((message) => message?.role === "user");
36072
+ for (let index = (messages || []).length - 1; index > lastUserIndex; index -= 1) {
36073
+ const message = messages[index];
36074
+ if (message?.role === "assistant" && message.stopReason === "error") return messageTimestampMs(message) || Date.now();
36075
+ }
36076
+ return 0;
36077
+ }
36078
+
36079
+ function assistantFailureDisplayMessage(message, base) {
36080
+ if (message?.stopReason === "error") {
36081
+ return {
36082
+ ...base,
36083
+ role: "error",
36084
+ title: "assistant error",
36085
+ level: "error",
36086
+ content: describeAssistantFailure(String(message.errorMessage || "The assistant request failed without an error message.").trim()),
36087
+ persistedFailure: true,
36088
+ actions: assistantFailureActions(),
36089
+ };
36090
+ }
36091
+ if (message?.stopReason === "aborted") {
36092
+ return { ...base, role: "native", title: "aborted", level: "warn", content: "This turn was aborted before it finished.", persistedFailure: true };
36093
+ }
36094
+ return null;
36095
+ }
36096
+
35126
36097
  function assistantDisplayMessages(message) {
35127
36098
  if (message?.role !== "assistant") return [message];
36099
+ const failure = assistantFailureDisplayMessage(message, { timestamp: message.timestamp });
36100
+ if (failure) {
36101
+ const rest = assistantDisplayMessagesWithoutFailure({ ...message, stopReason: undefined });
36102
+ return [...rest, failure];
36103
+ }
36104
+ return assistantDisplayMessagesWithoutFailure(message);
36105
+ }
36106
+
36107
+ function assistantDisplayMessagesWithoutFailure(message) {
35128
36108
  const base = { timestamp: message.timestamp };
35129
36109
  const content = message.content;
35130
36110
  if (typeof content === "string") {
@@ -35662,7 +36642,6 @@ function cleanupLiveToolRunsForMessages(messages = latestMessages) {
35662
36642
  for (const id of liveToolRuns.keys()) {
35663
36643
  if (results.has(id)) {
35664
36644
  liveToolRuns.delete(id);
35665
- cancelQueuedLiveToolRunRender(id);
35666
36645
  }
35667
36646
  }
35668
36647
  }
@@ -36563,7 +37542,8 @@ function createMessageBubble(message, { streaming = false, messageIndex = -1, tr
36563
37542
  if (role === "user") bubble.dataset.userPrompt = "true";
36564
37543
  }
36565
37544
  if (itemKey) bubble.dataset.itemKey = itemKey;
36566
- const isCollapsibleOutput = compactThinkingAggregate || (!streaming && (message.role === "toolResult" || message.role === "bashExecution" || message.role === "compactionSummary"));
37545
+ const collapsibleThinking = !streaming && !compactTranscript && message.role === "thinking" && !compactThinkingAggregate;
37546
+ const isCollapsibleOutput = compactThinkingAggregate || collapsibleThinking || (!streaming && (message.role === "toolResult" || message.role === "bashExecution" || message.role === "compactionSummary"));
36567
37547
 
36568
37548
  const hideMessageHeader = message.role === "assistant" && !isCollapsibleOutput;
36569
37549
  if (hideMessageHeader) bubble.setAttribute("aria-label", messageTitle(message));
@@ -36605,6 +37585,15 @@ function createMessageBubble(message, { streaming = false, messageIndex = -1, tr
36605
37585
  const defaultExpanded = message.compactThinkingDefaultExpanded === true;
36606
37586
  details.open = compactThinkingDisclosureExpanded(message.compactThinkingKey, defaultExpanded);
36607
37587
  if (message.compactThinkingKey) details.addEventListener("toggle", () => setCompactThinkingDisclosureExpanded(message.compactThinkingKey, details.open, defaultExpanded));
37588
+ } else if (collapsibleThinking) {
37589
+ // Persisted thinking starts folded (a high-effort model can dominate the transcript with it);
37590
+ // each block remembers its own state per tab, like the compact-mode aggregate does.
37591
+ const thinkingKey = `thinking:${itemKey || messageIndex}:${segmentId}`;
37592
+ details.classList.add("thinking-disclosure");
37593
+ details.open = compactThinkingDisclosureExpanded(thinkingKey, false);
37594
+ details.addEventListener("toggle", () => setCompactThinkingDisclosureExpanded(thinkingKey, details.open, false));
37595
+ const previewText = String(message.thinking || textFromContent(message.content) || "").replace(/\s+/g, " ").trim().slice(0, 140);
37596
+ if (previewText) header.append(make("span", "thinking-disclosure-preview", previewText));
36608
37597
  } else if (shouldOpenMessageCollapseByDefault(message)) details.open = true;
36609
37598
  details.append(header, body);
36610
37599
  bubble.append(details);
@@ -36618,6 +37607,22 @@ function createMessageBubble(message, { streaming = false, messageIndex = -1, tr
36618
37607
  } else {
36619
37608
  bubble.append(header, body);
36620
37609
  }
37610
+ if (Array.isArray(message.actions) && message.actions.length) {
37611
+ const actions = make("div", "message-actions");
37612
+ for (const action of message.actions) {
37613
+ if (!action?.label) continue;
37614
+ const button = make("button", `message-action-button${action.primary ? " primary" : ""}`, action.label);
37615
+ button.type = "button";
37616
+ if (action.title) button.title = action.title;
37617
+ button.addEventListener("click", (event) => {
37618
+ event.preventDefault();
37619
+ event.stopPropagation();
37620
+ Promise.resolve(action.run?.()).catch((error) => addEvent(error?.message || String(error), "error"));
37621
+ });
37622
+ actions.append(button);
37623
+ }
37624
+ if (actions.childElementCount) (bubble.querySelector(":scope > .message-body") || bubble).after(actions);
37625
+ }
36621
37626
  ownTranscriptBubble(bubble, body, message, { itemKey, streaming, transient, segmentId });
36622
37627
  ensureToolInteractionDelegation();
36623
37628
  if (message.role !== "workflowStatusStack") attachMessageCopyButton(bubble, message, body);
@@ -36713,7 +37718,7 @@ function appendTranscriptMessage(message, { streaming = false, messageIndex = -1
36713
37718
  if (displayMessage.role === "toolCall" && displayMessage.toolCallId) {
36714
37719
  transcriptMessage = toolExecutionMessageFromCall(displayMessage);
36715
37720
  }
36716
- if (compactTranscript && transcriptMessage.role !== "assistant") return;
37721
+ if (compactTranscript && transcriptMessage.role !== "assistant" && !transcriptMessage.persistedFailure) return;
36717
37722
  if (transcriptMessage.role === "thinking" && !thinkingOutputVisible) return;
36718
37723
  const created = appendMessage(transcriptMessage, {
36719
37724
  streaming: false,
@@ -36848,7 +37853,11 @@ function createRunIndicatorBubble() {
36848
37853
  pulse.setAttribute("aria-hidden", "true");
36849
37854
  runIndicatorText = make("span", "run-indicator-text");
36850
37855
  runIndicatorMeta = make("span", "run-indicator-meta");
36851
- row.append(pulse, runIndicatorText, runIndicatorMeta);
37856
+ // Elapsed time ticks every second; keep it out of the accessibility tree so the polite live
37857
+ // region only announces real activity changes, not "run time 12s / 13s / …".
37858
+ runIndicatorElapsed = make("span", "run-indicator-elapsed");
37859
+ runIndicatorElapsed.setAttribute("aria-hidden", "true");
37860
+ row.append(pulse, runIndicatorText, runIndicatorMeta, runIndicatorElapsed);
36852
37861
  body.append(row);
36853
37862
  runIndicatorBubble.append(body);
36854
37863
  }
@@ -36865,8 +37874,10 @@ function updateRunIndicatorBubble() {
36865
37874
  const headline = runIndicatorHeadline();
36866
37875
  if (runIndicatorText.textContent !== headline) runIndicatorText.textContent = headline;
36867
37876
  const detail = runIndicatorDetail();
36868
- const meta = runIndicatorShowsElapsed() ? `${detail} · run time ${formatRunIndicatorElapsed()}` : detail;
37877
+ const meta = detail;
36869
37878
  if (runIndicatorMeta.textContent !== meta) runIndicatorMeta.textContent = meta;
37879
+ const elapsed = runIndicatorShowsElapsed() ? ` · run time ${formatRunIndicatorElapsed()}` : "";
37880
+ if (runIndicatorElapsed && runIndicatorElapsed.textContent !== elapsed) runIndicatorElapsed.textContent = elapsed;
36870
37881
  }
36871
37882
 
36872
37883
  function removeRunIndicatorBubble() {
@@ -36875,6 +37886,7 @@ function removeRunIndicatorBubble() {
36875
37886
  runIndicatorBubble = null;
36876
37887
  runIndicatorText = null;
36877
37888
  runIndicatorMeta = null;
37889
+ runIndicatorElapsed = null;
36878
37890
  }
36879
37891
 
36880
37892
  function renderRunIndicator({ scroll = false } = {}) {
@@ -37159,7 +38171,11 @@ function orderedTranscriptItems() {
37159
38171
  if (resultId && assistantToolCallIds.has(resultId)) return;
37160
38172
  items.push({ message, messageIndex: index, transient: false, timestampMs: messageTimestampMs(message), order: index });
37161
38173
  });
38174
+ const persistedFailureAt = latestPersistedAssistantFailureTimestamp(latestMessages);
37162
38175
  transientMessages.forEach((message, index) => {
38176
+ // Once Pi's authoritative transcript carries the failed assistant turn (stopReason error), the
38177
+ // live "Assistant error" cards for the same failure are redundant.
38178
+ if (persistedFailureAt && message?.role === "error" && message?.title === "Assistant error" && messageTimestampMs(message) <= persistedFailureAt + 5000) return;
37163
38179
  items.push({ message, messageIndex: index, transient: true, timestampMs: messageTimestampMs(message), order: latestMessages.length + index });
37164
38180
  });
37165
38181
  let liveOrder = latestMessages.length + transientMessages.length;
@@ -37590,7 +38606,11 @@ function applyNativeSlashCommandEffects(response, message, tabContext = activeTa
37590
38606
  if (warning) addEvent(String(warning), "warn");
37591
38607
  }
37592
38608
  for (const toast of data.toasts || []) {
37593
- if (toast?.message) addEvent(String(toast.message), toast.level || "info");
38609
+ if (!toast?.message) continue;
38610
+ const level = toast.level || "info";
38611
+ addEvent(String(toast.message), level);
38612
+ // Extensions asked for a toast explicitly; info/success levels are not auto-surfaced by addEvent.
38613
+ if (level !== "warn" && level !== "error") showNoticeToast(String(toast.message), level);
37594
38614
  }
37595
38615
 
37596
38616
  if (data.copyText) {
@@ -37646,12 +38666,29 @@ function applyNativeSlashCommandEffects(response, message, tabContext = activeTa
37646
38666
  if (refresh.includes("themes")) initializeThemes().catch((error) => addEvent(error.message || String(error), "error"));
37647
38667
  }
37648
38668
 
37649
- function addTransientMessage({ role = "notice", title, content, level = "info", ...details }) {
38669
+ function addTransientMessage({ role = "notice", title, content, level = "info", key = "", ...details }) {
38670
+ // `key` upserts (e.g. one live "auto retry" card that counts down instead of one card per
38671
+ // attempt); identical consecutive error/warn cards collapse into one with a repeat counter.
38672
+ const last = transientMessages[transientMessages.length - 1];
38673
+ if (key) {
38674
+ const existing = transientMessages.findLast((message) => message?.key === key);
38675
+ if (existing) {
38676
+ Object.assign(existing, { role, title, level, content, ...details, timestamp: Date.now() });
38677
+ renderAllMessages();
38678
+ return;
38679
+ }
38680
+ } else if (last && (level === "error" || level === "warn") && last.level === level && last.role === role && last.title === title && last.content === content && Date.now() - (last.timestamp || 0) < 120_000) {
38681
+ last.repeatCount = (last.repeatCount || 1) + 1;
38682
+ last.timestamp = Date.now();
38683
+ renderAllMessages();
38684
+ return;
38685
+ }
37650
38686
  transientMessages.push({
37651
38687
  role,
37652
38688
  title,
37653
38689
  level,
37654
38690
  content,
38691
+ key,
37655
38692
  ...details,
37656
38693
  timestamp: Date.now(),
37657
38694
  });
@@ -37659,11 +38696,37 @@ function addTransientMessage({ role = "notice", title, content, level = "info",
37659
38696
  renderAllMessages();
37660
38697
  }
37661
38698
 
37662
- function surfaceRuntimeDiagnostic(title, content, level = "error") {
38699
+ function surfaceRuntimeDiagnostic(title, content, level = "error", { actions = null } = {}) {
37663
38700
  const message = String(content || "").trim();
37664
38701
  if (!message) return;
37665
- addEvent(message, level);
37666
- addTransientMessage({ role: level === "error" ? "error" : "warn", title, content: message, level });
38702
+ addEvent(message, level, { notify: false }); // the transcript card below is the visible feedback
38703
+ addTransientMessage({ role: level === "error" ? "error" : "warn", title, content: message, level, ...(actions ? { actions } : {}) });
38704
+ }
38705
+
38706
+ // Recovery actions for a failed assistant turn: retry the last prompt as-is, or pick another model.
38707
+ function assistantFailureActions(tabId = activeTabId) {
38708
+ const entry = tabId ? lastUserPromptByTab.get(tabId) : null;
38709
+ const actions = [];
38710
+ if (entry?.text) {
38711
+ actions.push({
38712
+ label: "Retry",
38713
+ title: "Send the last prompt again",
38714
+ primary: true,
38715
+ run: () => sendPrompt("prompt", entry.text, { targetTabId: tabId }),
38716
+ });
38717
+ }
38718
+ actions.push({ label: "Change model…", title: "Choose another model for this tab (Ctrl/Cmd+L)", run: () => openNativeModelSelector() });
38719
+ return actions;
38720
+ }
38721
+
38722
+ // Provider errors are terse ("Connection error."). Add the model/provider so the user knows what
38723
+ // failed and where to look (LM Studio not running, wrong base URL, expired key, …).
38724
+ function describeAssistantFailure(message, state = currentState) {
38725
+ const model = state?.model;
38726
+ const text = String(message || "").trim();
38727
+ if (!model?.provider) return text;
38728
+ const where = `${model.provider}/${model.id || ""}`.replace(/\/$/, "");
38729
+ return text.includes(where) ? text : `${text} (model ${where})`;
37667
38730
  }
37668
38731
 
37669
38732
  function stderrDiagnosticLevel(content) {
@@ -37896,7 +38959,40 @@ async function sendBtwPromptFromButton() {
37896
38959
  await sendBtwQuestion(question, { clearComposerDraft: true });
37897
38960
  }
37898
38961
 
38962
+ // Hover/focus-opened composer menus need an explicit "dismissed" state: after Escape or an item
38963
+ // choice the pointer usually still rests on the trigger (and the trigger keeps focus), so without
38964
+ // this the panel would immediately pop open again and Escape would appear broken.
38965
+ function armComposerMenuDismissal(container) {
38966
+ if (!container?.classList) return;
38967
+ const hovering = container.matches(":hover");
38968
+ const clear = () => {
38969
+ container.classList.remove("menu-dismissed");
38970
+ container.removeEventListener("pointerleave", clear);
38971
+ container.removeEventListener("focusout", onFocusOut);
38972
+ };
38973
+ const onFocusOut = () => setTimeout(() => {
38974
+ // Still hovered: keep the dismissal until the pointer leaves as well.
38975
+ if (!container.contains(document.activeElement) && !container.matches(":hover")) clear();
38976
+ }, 0);
38977
+ const focusedInside = container.contains(document.activeElement);
38978
+ if (!hovering && !focusedInside) return; // nothing would reopen it; no need to suppress
38979
+ container.classList.add("menu-dismissed");
38980
+ container.addEventListener("pointerleave", () => {
38981
+ if (!container.contains(document.activeElement)) clear();
38982
+ }, { once: true });
38983
+ container.addEventListener("focusout", onFocusOut);
38984
+ }
38985
+
38986
+ function composerMenuDismissed(container) {
38987
+ return Boolean(container?.classList?.contains("menu-dismissed"));
38988
+ }
38989
+
38990
+ function clearComposerMenuDismissal(container) {
38991
+ container?.classList?.remove("menu-dismissed");
38992
+ }
38993
+
37899
38994
  function setPublishMenuOpen(open) {
38995
+ if (open && composerMenuDismissed(elements.publishButton?.parentElement)) return;
37900
38996
  if (open && followUpQueueOpen) setFollowUpQueueOpen(false);
37901
38997
  publishMenuOpen = !!open;
37902
38998
  elements.publishButton.setAttribute("aria-expanded", publishMenuOpen ? "true" : "false");
@@ -37907,6 +39003,7 @@ function setPublishMenuOpen(open) {
37907
39003
  }
37908
39004
 
37909
39005
  function setNativeCommandMenuOpen(open) {
39006
+ if (open && composerMenuDismissed(elements.nativeCommandMenuButton?.parentElement)) return;
37910
39007
  if (open && followUpQueueOpen) setFollowUpQueueOpen(false);
37911
39008
  nativeCommandMenuOpen = !!open;
37912
39009
  elements.nativeCommandMenuButton.setAttribute("aria-expanded", nativeCommandMenuOpen ? "true" : "false");
@@ -37917,6 +39014,7 @@ function setNativeCommandMenuOpen(open) {
37917
39014
  }
37918
39015
 
37919
39016
  function setAppRunnerMenuOpen(open) {
39017
+ if (open && composerMenuDismissed(elements.appRunnerMenuButton?.parentElement)) return;
37920
39018
  if (open && followUpQueueOpen) setFollowUpQueueOpen(false);
37921
39019
  appRunnerMenuOpen = !!open;
37922
39020
  elements.appRunnerMenuButton?.setAttribute("aria-expanded", appRunnerMenuOpen ? "true" : "false");
@@ -37927,6 +39025,7 @@ function setAppRunnerMenuOpen(open) {
37927
39025
  }
37928
39026
 
37929
39027
  function setOptionsMenuOpen(open) {
39028
+ if (open && composerMenuDismissed(elements.optionsMenuButton?.parentElement)) return;
37930
39029
  if (open && followUpQueueOpen) setFollowUpQueueOpen(false);
37931
39030
  optionsMenuOpen = !!open;
37932
39031
  elements.optionsMenuButton.setAttribute("aria-expanded", optionsMenuOpen ? "true" : "false");
@@ -38745,6 +39844,16 @@ function renderOptionalFeatureMigrationSurface() {
38745
39844
  ensureOptionalFeatureMigrationRenderTimer();
38746
39845
  return;
38747
39846
  }
39847
+ // A healthy "ready" audit is not actionable: don't cover the header with a banner on every
39848
+ // page load. The summary stays available in Optional features and the Events log; only a
39849
+ // deferred migration (restorable companions) still surfaces here.
39850
+ if (snapshot.phase === "ready" && !optionalFeatureRestartNotice && !(summary.migratable > 0) && !conflicts.length) {
39851
+ clearOptionalFeatureReadyDismissTimer();
39852
+ surface.replaceChildren();
39853
+ surface.hidden = true;
39854
+ ensureOptionalFeatureMigrationRenderTimer();
39855
+ return;
39856
+ }
38748
39857
  if (noticeDismissKey && optionalFeatureMigrationDismissedNoticeKey === noticeDismissKey) {
38749
39858
  surface.replaceChildren();
38750
39859
  surface.hidden = true;
@@ -39534,11 +40643,14 @@ function renderOptionalFeatureControls() {
39534
40643
  }
39535
40644
 
39536
40645
  const hasGitWorkflow = isOptionalFeatureEnabled("gitWorkflow");
39537
- elements.gitWorkflowButton.hidden = !hasGitWorkflow;
40646
+ // Committing/pushing is a core expectation: keep the entry point visible (disabled, with the
40647
+ // install hint) when the companion package is merely missing; hide it only when the user
40648
+ // explicitly disabled the feature.
40649
+ elements.gitWorkflowButton.hidden = !hasGitWorkflow && isOptionalFeatureDisabled("gitWorkflow");
39538
40650
  setOptionalControlState(
39539
40651
  elements.gitWorkflowButton,
39540
40652
  hasGitWorkflow,
39541
- optionalFeatureUnavailableMessage("gitWorkflow"),
40653
+ `${optionalFeatureUnavailableMessage("gitWorkflow")} Until then, stage and review changes from the Git panel or the CHANGES footer chip.`,
39542
40654
  );
39543
40655
 
39544
40656
  elements.releaseNpmButton.hidden = !isOptionalFeatureEnabled("releaseNpm");
@@ -40361,18 +41473,120 @@ function nativeSelectorMatches(item, query) {
40361
41473
  .some((value) => String(value).toLowerCase().includes(needle));
40362
41474
  }
40363
41475
 
41476
+ // Keyboard navigation for native selector dialogs (/model, /theme, /resume, …):
41477
+ // the search box owns focus, ArrowUp/Down move a visible highlight, Enter selects
41478
+ // the highlighted choice, Home/End jump. The highlight defaults to the current
41479
+ // choice (when unfiltered) so Enter is never destructive by surprise.
41480
+ let nativeSelectorHighlightIndex = -1;
41481
+
41482
+ function nativeSelectorItemButtons() {
41483
+ return Array.from(elements.nativeCommandBody.querySelectorAll(".native-selector-item:not([disabled])"));
41484
+ }
41485
+
41486
+ function syncNativeSelectorHighlight({ scroll = true } = {}) {
41487
+ const buttons = nativeSelectorItemButtons();
41488
+ if (!buttons.length) {
41489
+ nativeSelectorHighlightIndex = -1;
41490
+ elements.nativeCommandSearch.removeAttribute("aria-activedescendant");
41491
+ return null;
41492
+ }
41493
+ nativeSelectorHighlightIndex = Math.min(Math.max(nativeSelectorHighlightIndex, 0), buttons.length - 1);
41494
+ let highlighted = null;
41495
+ buttons.forEach((button, index) => {
41496
+ const on = index === nativeSelectorHighlightIndex;
41497
+ button.classList.toggle("keyboard-active", on);
41498
+ button.setAttribute("aria-selected", on ? "true" : "false");
41499
+ if (on) highlighted = button;
41500
+ });
41501
+ if (highlighted) {
41502
+ elements.nativeCommandSearch.setAttribute("aria-activedescendant", highlighted.id);
41503
+ if (scroll) highlighted.scrollIntoView({ block: "nearest" });
41504
+ }
41505
+ return highlighted;
41506
+ }
41507
+
41508
+ function moveNativeSelectorHighlight(delta, { absolute = false } = {}) {
41509
+ const buttons = nativeSelectorItemButtons();
41510
+ if (!buttons.length) return;
41511
+ const last = buttons.length - 1;
41512
+ let next = absolute ? delta : nativeSelectorHighlightIndex + delta;
41513
+ if (next < 0) next = absolute ? 0 : last;
41514
+ if (next > last) next = absolute ? last : 0;
41515
+ nativeSelectorHighlightIndex = next;
41516
+ syncNativeSelectorHighlight();
41517
+ }
41518
+
41519
+ function activateNativeSelectorHighlight() {
41520
+ const highlighted = syncNativeSelectorHighlight({ scroll: false });
41521
+ if (!highlighted) return false;
41522
+ highlighted.click();
41523
+ return true;
41524
+ }
41525
+
41526
+ function handleNativeSelectorSearchKeydown(event) {
41527
+ if (event.isComposing || elements.nativeCommandSearch.hidden) return;
41528
+ if (!nativeSelectorItemButtons().length) return;
41529
+ switch (event.key) {
41530
+ case "ArrowDown":
41531
+ event.preventDefault();
41532
+ moveNativeSelectorHighlight(1);
41533
+ return;
41534
+ case "ArrowUp":
41535
+ event.preventDefault();
41536
+ moveNativeSelectorHighlight(-1);
41537
+ return;
41538
+ case "Home":
41539
+ if (elements.nativeCommandSearch.value) return;
41540
+ event.preventDefault();
41541
+ moveNativeSelectorHighlight(0, { absolute: true });
41542
+ return;
41543
+ case "End":
41544
+ if (elements.nativeCommandSearch.value) return;
41545
+ event.preventDefault();
41546
+ moveNativeSelectorHighlight(Number.MAX_SAFE_INTEGER, { absolute: true });
41547
+ return;
41548
+ case "PageDown":
41549
+ event.preventDefault();
41550
+ moveNativeSelectorHighlight(8);
41551
+ return;
41552
+ case "PageUp":
41553
+ event.preventDefault();
41554
+ moveNativeSelectorHighlight(-8);
41555
+ return;
41556
+ case "Enter":
41557
+ if (event.shiftKey || event.altKey || event.ctrlKey || event.metaKey) return;
41558
+ event.preventDefault();
41559
+ activateNativeSelectorHighlight();
41560
+ return;
41561
+ default:
41562
+ }
41563
+ }
41564
+
40364
41565
  function renderNativeSelectorItems(items, { emptyText = "No choices.", onSelect, activeId, numbered = false } = {}) {
40365
41566
  const query = elements.nativeCommandSearch.value.trim();
40366
41567
  const filtered = items.filter((item) => nativeSelectorMatches(item, query));
40367
41568
  elements.nativeCommandBody.replaceChildren();
41569
+ elements.nativeCommandSearch.removeAttribute("aria-activedescendant");
40368
41570
  if (!filtered.length) {
41571
+ nativeSelectorHighlightIndex = -1;
40369
41572
  elements.nativeCommandBody.append(make("div", "native-command-empty muted", emptyText));
40370
41573
  return;
40371
41574
  }
40372
41575
  const list = make("div", "native-selector-list");
41576
+ list.setAttribute("role", "listbox");
41577
+ list.id = "nativeSelectorList";
41578
+ let lastGroup = null;
40373
41579
  for (const [index, item] of filtered.entries()) {
41580
+ if (item.group && item.group !== lastGroup && !item.badge) {
41581
+ const heading = make("div", "native-selector-group", item.group);
41582
+ heading.setAttribute("role", "presentation");
41583
+ list.append(heading);
41584
+ }
41585
+ if (item.group) lastGroup = item.group;
40374
41586
  const button = make("button", `native-selector-item${item.id === activeId ? " active" : ""}`);
40375
41587
  button.type = "button";
41588
+ button.id = `nativeSelectorItem-${index}`;
41589
+ button.setAttribute("role", "option");
40376
41590
  button.disabled = item.disabled === true;
40377
41591
  if (typeof item.pressed === "boolean") button.setAttribute("aria-pressed", String(item.pressed));
40378
41592
  button.addEventListener("click", () => onSelect?.(item));
@@ -40402,6 +41616,12 @@ function renderNativeSelectorItems(items, { emptyText = "No choices.", onSelect,
40402
41616
  list.append(button);
40403
41617
  }
40404
41618
  elements.nativeCommandBody.append(list);
41619
+ // Unfiltered: highlight (and reveal) the current choice; filtered: the best match on top.
41620
+ const enabled = nativeSelectorItemButtons();
41621
+ const currentIndex = query ? -1 : enabled.findIndex((button) => button.classList.contains("active"));
41622
+ nativeSelectorHighlightIndex = currentIndex >= 0 ? currentIndex : 0;
41623
+ const highlighted = syncNativeSelectorHighlight({ scroll: false });
41624
+ if (highlighted && !query && currentIndex >= 0) queueMicrotask(() => highlighted.scrollIntoView({ block: "center" }));
40405
41625
  }
40406
41626
 
40407
41627
  function setNativeActionBusy(button, busy, label = "Working…") {
@@ -40426,10 +41646,17 @@ async function openNativeModelSelector() {
40426
41646
  id: modelOptionLabel(model),
40427
41647
  label: modelOptionLabel(model),
40428
41648
  description: model.name || model.description || "",
40429
- meta: model.contextWindow ? `context ${model.contextWindow}` : model.provider,
41649
+ meta: [
41650
+ model.contextWindow ? `context ${formatFooterTokenCount(model.contextWindow)}` : "",
41651
+ model.reasoning ? "reasoning" : "",
41652
+ Array.isArray(model.input) && model.input.includes("image") ? "images" : "",
41653
+ ].filter(Boolean).join(" · ") || model.provider,
41654
+ group: model.provider,
40430
41655
  model,
40431
41656
  badge: modelOptionLabel(model) === activeId ? "current" : "",
40432
41657
  }));
41658
+ // The current model goes first so it is visible without scrolling through hundreds of rows.
41659
+ items.sort((a, b) => (b.badge === "current") - (a.badge === "current"));
40433
41660
  const render = () => renderNativeSelectorItems(items, {
40434
41661
  emptyText: "No models match this filter.",
40435
41662
  activeId,
@@ -41877,8 +43104,9 @@ function openNativeNameDialog() {
41877
43104
  });
41878
43105
  }
41879
43106
 
41880
- async function openNativeResumeSelector(scope = "current") {
41881
- openNativeCommandDialog({ title: "/resume", message: "Select a session, then resume, rename metadata, or delete it.", searchPlaceholder: "Filter sessions…" });
43107
+ async function openNativeResumeSelector(scope = "current", { query = "" } = {}) {
43108
+ openNativeCommandDialog({ title: "Resume a session", message: "Select a session, then resume, rename metadata, or delete it.", searchPlaceholder: "Filter sessions…" });
43109
+ if (query) elements.nativeCommandSearch.value = query;
41882
43110
  renderNativeLoading("Loading sessions…");
41883
43111
  const selectedScope = scope === "all" ? "all" : "current";
41884
43112
  let selectedItem = null;
@@ -41903,13 +43131,13 @@ async function openNativeResumeSelector(scope = "current") {
41903
43131
 
41904
43132
  const renameButton = addNativeCommandAction("Rename", async () => {
41905
43133
  if (!selectedItem) return;
41906
- const nextName = window.prompt("Session display name", selectedItem.session.name || selectedItem.label || "");
43134
+ const nextName = await appPromptText({ title: "Rename session", summary: "Display name stored in the session metadata.", defaultValue: selectedItem.session.name || selectedItem.label || "", confirmLabel: "Rename" });
41907
43135
  if (nextName === null) return;
41908
43136
  setNativeCommandError("");
41909
43137
  try {
41910
43138
  const result = await nativeCommandApi("/api/session-rename", { method: "POST", body: { sessionPath: selectedItem.session.path, name: nextName } });
41911
43139
  addTransientMessage({ role: "native", title: "/resume", content: result.data?.message || "Renamed session metadata.", level: "info" });
41912
- await openNativeResumeSelector(selectedScope);
43140
+ await openNativeResumeSelector(selectedScope, { query: elements.nativeCommandSearch.value });
41913
43141
  } catch (error) {
41914
43142
  setNativeCommandError(error.message || String(error));
41915
43143
  }
@@ -41928,7 +43156,7 @@ async function openNativeResumeSelector(scope = "current") {
41928
43156
  try {
41929
43157
  const result = await nativeCommandApi("/api/session-delete", { method: "POST", body: { sessionPath: selectedItem.session.path, confirmed: true } });
41930
43158
  addTransientMessage({ role: "native", title: "/resume", content: result.data?.message || "Session deleted.", level: "warn" });
41931
- await openNativeResumeSelector(selectedScope);
43159
+ await openNativeResumeSelector(selectedScope, { query: elements.nativeCommandSearch.value });
41932
43160
  } catch (error) {
41933
43161
  setNativeCommandError(error.message || String(error));
41934
43162
  resumeDeleteArmed = false;
@@ -41947,7 +43175,7 @@ async function openNativeResumeSelector(scope = "current") {
41947
43175
  id: session.path,
41948
43176
  label: session.name || session.firstMessage || session.id || session.path,
41949
43177
  description: session.firstMessage || "(no messages)",
41950
- meta: `${session.cwd || "unknown cwd"} · ${session.messageCount || 0} messages · ${session.modified || "unknown time"}`,
43178
+ meta: `${session.cwd || "unknown cwd"} · ${session.messageCount || 0} messages · ${session.modified ? formatRelativeDate(session.modified) : "unknown time"}`,
41951
43179
  badge: session.current ? "current" : "",
41952
43180
  disabled: session.current,
41953
43181
  session,
@@ -42797,6 +44025,7 @@ function acceptOutputModeAcknowledgement(event) {
42797
44025
  }
42798
44026
 
42799
44027
  function transitionNormalLiveOutputToCompact() {
44028
+ flushNormalStreamRenders("output-mode-transition");
42800
44029
  compactLiveState = seedFastOutputLiveState({ text: streamRawText, thinking: streamThinkingRawText });
42801
44030
  setStreamRawText("");
42802
44031
  setStreamThinkingRawText("");
@@ -42817,6 +44046,8 @@ function transitionCompactLiveOutputToNormal(tabContext = activeTabContext()) {
42817
44046
 
42818
44047
  function applyOutputModeControl(event, tabContext = activeTabContext()) {
42819
44048
  if (event?.protocolVersion !== 1 || !["normal", "compact-v1"].includes(event.activeMode)) return false;
44049
+ flushNormalStreamRenders("output-mode-change");
44050
+ fallbackStreamDerivedOutput("output-mode-change");
42820
44051
  const previousMode = activeOutputMode;
42821
44052
  if (previousMode === "normal" && event.activeMode === "compact-v1") {
42822
44053
  transitionNormalLiveOutputToCompact();
@@ -42844,23 +44075,67 @@ function removeStreamBubble() {
42844
44075
  renderRunIndicator({ scroll: false });
42845
44076
  }
42846
44077
 
42847
- function resetStreamDerivedTextCache() {
42848
- streamDerivedTextCache = { rawText: null, assistantText: "", thinkingFormat: null, finalText: "" };
44078
+ function ensureStreamDerivedOutputState() {
44079
+ const todoProgressDetected = isOptionalFeatureDetected("todoProgressWidget");
44080
+ if (!streamDerivedOutputState) {
44081
+ streamDerivedOutputState = createStreamDerivedOutputState({
44082
+ todoProgressDetected,
44083
+ shadow: !!streamIsolationDebugLedger,
44084
+ });
44085
+ } else {
44086
+ streamDerivedOutputState.setTodoProgressDetected(todoProgressDetected);
44087
+ }
44088
+ return streamDerivedOutputState;
44089
+ }
44090
+
44091
+ function recordStreamDerivedOutputDiagnostic(diagnostic, ms = 0) {
44092
+ if (!streamIsolationDebugLedger || (!diagnostic.scannedCodeUnits && !diagnostic.fallbackReason && !diagnostic.shadowMismatch)) return;
44093
+ const bytes = diagnostic.scannedCodeUnits * 2;
44094
+ recordStreamProfileDiagnostic({ type: "derive", ms, bytes });
44095
+ if (diagnostic.fallbackReason) recordStreamProfileDiagnostic({ type: "derive-fallback", reason: diagnostic.fallbackReason, bytes });
44096
+ if (diagnostic.shadowMismatch) recordStreamProfileDiagnostic({ type: "derive-shadow-mismatch", reason: diagnostic.fallbackReason || "shadow-mismatch" });
42849
44097
  }
42850
44098
 
42851
- function setStreamRawText(text) {
44099
+ function captureStreamDerivedOutputProfile(startedAt) {
44100
+ recordStreamDerivedOutputDiagnostic(
44101
+ ensureStreamDerivedOutputState().takeDiagnostics(),
44102
+ streamIsolationDebugLedger ? performance.now() - startedAt : 0,
44103
+ );
44104
+ }
44105
+
44106
+ function resetStreamDerivedOutputState(reason = "reset") {
44107
+ if (!streamDerivedOutputState) return;
44108
+ streamDerivedOutputState.reset({
44109
+ todoProgressDetected: isOptionalFeatureDetected("todoProgressWidget"),
44110
+ reason,
44111
+ });
44112
+ recordStreamDerivedOutputDiagnostic(streamDerivedOutputState.takeDiagnostics());
44113
+ }
44114
+
44115
+ function fallbackStreamDerivedOutput(reason) {
44116
+ if (!streamRawText || !streamDerivedOutputState) return;
44117
+ const profileStart = streamIsolationDebugLedger ? performance.now() : 0;
44118
+ ensureStreamDerivedOutputState().replace(streamRawText, { reason, force: true });
44119
+ captureStreamDerivedOutputProfile(profileStart);
44120
+ }
44121
+
44122
+ function setStreamRawText(text, { reason = "snapshot" } = {}) {
42852
44123
  const nextText = String(text || "");
42853
44124
  if (nextText === streamRawText) return false;
44125
+ const profileStart = streamIsolationDebugLedger ? performance.now() : 0;
42854
44126
  streamRawText = nextText;
42855
- resetStreamDerivedTextCache();
44127
+ ensureStreamDerivedOutputState().replace(nextText, { reason });
44128
+ captureStreamDerivedOutputProfile(profileStart);
42856
44129
  return true;
42857
44130
  }
42858
44131
 
42859
44132
  function appendStreamRawText(delta) {
42860
44133
  const text = String(delta || "");
42861
44134
  if (!text) return false;
44135
+ const profileStart = streamIsolationDebugLedger ? performance.now() : 0;
42862
44136
  streamRawText += text;
42863
- resetStreamDerivedTextCache();
44137
+ ensureStreamDerivedOutputState().append(text);
44138
+ captureStreamDerivedOutputProfile(profileStart);
42864
44139
  return true;
42865
44140
  }
42866
44141
 
@@ -42882,16 +44157,13 @@ function syncStreamRawTextFromUpdate(event, update) {
42882
44157
  }
42883
44158
 
42884
44159
  function streamDerivedText() {
42885
- if (streamDerivedTextCache.rawText === streamRawText) return streamDerivedTextCache;
42886
- const profileStart = streamIsolationDebugLedger ? performance.now() : 0;
42887
- const assistantText = stripTodoProgressLines(streamRawText, { streaming: true });
42888
- const thinkingFormat = splitThinkingFormatText(assistantText, { streaming: true });
42889
- const finalText = thinkingFormat?.hasThinkingFormat ? stripTodoProgressLines(thinkingFormat.finalText, { streaming: true }) : assistantText;
42890
- streamDerivedTextCache = { rawText: streamRawText, assistantText, thinkingFormat, finalText };
42891
- if (streamIsolationDebugLedger) {
42892
- recordStreamProfileDiagnostic({ type: "derive", ms: performance.now() - profileStart, bytes: streamDiagnosticBytes(streamRawText) });
44160
+ const state = ensureStreamDerivedOutputState();
44161
+ if (state.value().rawText !== streamRawText) {
44162
+ const profileStart = streamIsolationDebugLedger ? performance.now() : 0;
44163
+ state.replace(streamRawText, { reason: "state-divergence" });
44164
+ captureStreamDerivedOutputProfile(profileStart);
42893
44165
  }
42894
- return streamDerivedTextCache;
44166
+ return state.value();
42895
44167
  }
42896
44168
 
42897
44169
  function streamRenderableAssistantText() {
@@ -42966,27 +44238,28 @@ function scheduleStreamBubbleHide() {
42966
44238
  }, delayMs);
42967
44239
  }
42968
44240
 
42969
- function syncStreamingThinkingFormat() {
44241
+ function syncStreamingThinkingFormat({ complete = false } = {}) {
42970
44242
  const parsed = streamDerivedText().thinkingFormat;
42971
44243
  if (!parsed?.hasThinkingFormat) return null;
42972
44244
  const thinking = visibleThinkingText(parsed.thinkingText);
42973
- if (thinking) setStreamingThinkingText(thinking);
44245
+ if (thinking) setStreamingThinkingText(thinking, { complete: complete || parsed.complete });
42974
44246
  if (parsed.complete && streamThinkingBubble) streamThinkingBubble.classList.add("complete");
42975
44247
  return parsed;
42976
44248
  }
42977
44249
 
42978
- function renderStreamingAssistantText() {
42979
- const thinkingFormat = syncStreamingThinkingFormat();
44250
+ function renderStreamingAssistantText({ complete = false } = {}) {
44251
+ const thinkingFormat = syncStreamingThinkingFormat({ complete });
42980
44252
  const finalText = thinkingFormat?.hasThinkingFormat ? streamDerivedText().finalText : streamRenderableAssistantText();
42981
44253
  if (finalText) {
42982
44254
  ensureStreamBubble();
42983
- renderStreamingMarkdown(streamText, finalText);
44255
+ renderStreamingMarkdown(streamText, finalText, { complete });
42984
44256
  } else {
42985
44257
  scheduleStreamBubbleHide();
42986
44258
  }
42987
44259
  }
42988
44260
 
42989
44261
  function suppressStreamingAssistantTextBeforeToolCall() {
44262
+ flushNormalStreamRenders("tool-call-boundary");
42990
44263
  setStreamRawText("");
42991
44264
  removeStreamBubble();
42992
44265
  }
@@ -43081,14 +44354,14 @@ function showStreamingThinking(initialText = "") {
43081
44354
  }
43082
44355
 
43083
44356
  function resetStreamBubble({ preserveCompact = false } = {}) {
44357
+ cancelNormalStreamRenders();
43084
44358
  resetCompactLiveOutput({ remove: !preserveCompact });
43085
44359
  cancelStreamBubbleHide();
43086
44360
  streamBubble = null;
43087
44361
  streamText = null;
43088
44362
  streamRawText = "";
43089
44363
  streamThinkingRawText = "";
43090
- resetStreamDerivedTextCache();
43091
- streamMarkdownState = null;
44364
+ resetStreamDerivedOutputState("reset");
43092
44365
  streamBubbleVisibleSince = 0;
43093
44366
  streamToolCallSeen = false;
43094
44367
  resetStreamingToolCallState({ remove: true });
@@ -43254,11 +44527,11 @@ function assistantThinkingTextFromMessage(message, { streaming = false } = {}) {
43254
44527
  return parts.length ? parts.join("\n\n") : "";
43255
44528
  }
43256
44529
 
43257
- function setStreamingThinkingText(text) {
44530
+ function setStreamingThinkingText(text, { complete = false } = {}) {
43258
44531
  const thinking = visibleThinkingText(text);
43259
44532
  if (!thinkingOutputVisible || !thinking) return false;
43260
44533
  showStreamingThinking("");
43261
- if (streamThinking) renderThinkingMarkdown(streamThinking, thinking);
44534
+ if (streamThinking) renderThinkingMarkdown(streamThinking, thinking, { complete });
43262
44535
  return true;
43263
44536
  }
43264
44537
 
@@ -43283,16 +44556,17 @@ function appendStreamThinkingText(delta) {
43283
44556
  return true;
43284
44557
  }
43285
44558
 
43286
- function syncStreamingThinkingFromUpdate(event, update, { placeholder = "" } = {}) {
44559
+ function syncStreamingThinkingFromUpdate(event, update, { placeholder = "", render = true } = {}) {
43287
44560
  if (!thinkingOutputVisible) return true;
43288
44561
  const delta = thinkingDeltaText(update);
43289
44562
  if (update.type === "thinking_delta" && delta) {
43290
44563
  appendStreamThinkingText(delta);
43291
- return setStreamingThinkingText(streamThinkingRawText || placeholder);
44564
+ return render ? setStreamingThinkingText(streamThinkingRawText || placeholder) : true;
43292
44565
  }
43293
44566
  if (update.type === "thinking_start") {
43294
44567
  if (delta) setStreamThinkingRawText(delta);
43295
- return streamThinkingRawText ? setStreamingThinkingText(streamThinkingRawText || placeholder) : false;
44568
+ if (!streamThinkingRawText) return false;
44569
+ return render ? setStreamingThinkingText(streamThinkingRawText || placeholder) : true;
43296
44570
  }
43297
44571
  if (update.type === "thinking_end") {
43298
44572
  if (delta) setStreamThinkingRawText(delta, { reconcile: true });
@@ -43300,12 +44574,12 @@ function syncStreamingThinkingFromUpdate(event, update, { placeholder = "" } = {
43300
44574
  const fallback = streamingThinkingTextFallback(event);
43301
44575
  if (fallback !== null) setStreamThinkingRawText(fallback, { reconcile: true });
43302
44576
  }
43303
- return setStreamingThinkingText(streamThinkingRawText || placeholder);
44577
+ return render ? setStreamingThinkingText(streamThinkingRawText || placeholder, { complete: true }) : true;
43304
44578
  }
43305
44579
  const fallback = streamingThinkingTextFallback(event);
43306
44580
  if (fallback === null) return false;
43307
44581
  setStreamThinkingRawText(fallback);
43308
- return setStreamingThinkingText(streamThinkingRawText || placeholder);
44582
+ return render ? setStreamingThinkingText(streamThinkingRawText || placeholder) : true;
43309
44583
  }
43310
44584
 
43311
44585
  function assistantStreamErrorMessage(event, update = event?.assistantMessageEvent || {}) {
@@ -43322,20 +44596,20 @@ function assistantStreamErrorMessage(event, update = event?.assistantMessageEven
43322
44596
  function handleMessageUpdate(event) {
43323
44597
  if (compactOutputActive() && handleCompactMessageUpdate(event)) return;
43324
44598
  const update = event.assistantMessageEvent || {};
43325
- if (update.type === "thinking_start") {
43326
- syncStreamingThinkingFromUpdate(event, update);
43327
- } else if (update.type === "thinking_delta") {
43328
- const delta = thinkingDeltaText(update);
43329
- const synced = syncStreamingThinkingFromUpdate(event, update);
43330
- if (thinkingOutputVisible && delta && (!synced || !streamThinking?.textContent)) {
43331
- showStreamingThinking("");
43332
- if (streamThinking) renderThinkingMarkdown(streamThinking, `${streamThinking._rawThinkingText || ""}${delta}`);
43333
- }
44599
+ if (update.type === "thinking_start" || update.type === "thinking_delta") {
44600
+ syncStreamingThinkingFromUpdate(event, update, { render: false });
44601
+ if (thinkingOutputVisible && streamThinkingRawText) thinkingStreamRenderScheduler.request({ complete: false });
43334
44602
  } else if (update.type === "thinking_end") {
43335
- if (syncStreamingThinkingFromUpdate(event, update)) streamThinkingBubble?.classList.add("complete");
44603
+ syncStreamingThinkingFromUpdate(event, update, { render: false });
44604
+ if (thinkingOutputVisible && streamThinkingRawText) {
44605
+ thinkingStreamRenderScheduler.request({ complete: true });
44606
+ thinkingStreamRenderScheduler.flushNow("thinking_end");
44607
+ }
43336
44608
  } else if (update.type === "text_delta" || update.type === "text_end") {
43337
44609
  syncStreamRawTextFromUpdate(event, update);
43338
- renderStreamingAssistantText();
44610
+ if (update.type === "text_end") fallbackStreamDerivedOutput("settlement:text_end");
44611
+ assistantStreamRenderScheduler.request({ complete: update.type === "text_end" });
44612
+ if (update.type === "text_end") assistantStreamRenderScheduler.flushNow("text_end");
43339
44613
  } else if (update.type === "toolcall_start") {
43340
44614
  streamToolCallSeen = true;
43341
44615
  suppressStreamingAssistantTextBeforeToolCall();
@@ -43793,6 +45067,7 @@ function renderModelSearchResults(models = []) {
43793
45067
  );
43794
45068
  button.addEventListener("click", () => {
43795
45069
  if (elements.modelSelect) elements.modelSelect.value = value;
45070
+ setControlsPendingModel(value);
43796
45071
  renderModelSearchResults(models);
43797
45072
  });
43798
45073
  button.addEventListener("dblclick", () => elements.setModelButton?.click());
@@ -43856,9 +45131,23 @@ function hideModelSearchInput() {
43856
45131
  scheduleDeferredUiFlushAfterDropdownClose();
43857
45132
  }
43858
45133
 
45134
+ function setControlsPendingModel(value) {
45135
+ controlsPendingModelValue = value || "";
45136
+ elements.setModelButton?.classList.toggle("pending", Boolean(controlsPendingModelValue));
45137
+ if (elements.setModelButton) elements.setModelButton.title = controlsPendingModelValue ? "Apply the selected model (not applied yet)" : "Apply selected model";
45138
+ }
45139
+
45140
+ function setControlsPendingThinking(value) {
45141
+ controlsPendingThinkingValue = value || "";
45142
+ elements.setThinkingButton?.classList.toggle("pending", Boolean(controlsPendingThinkingValue));
45143
+ if (elements.setThinkingButton) elements.setThinkingButton.title = controlsPendingThinkingValue ? "Apply the selected thinking effort (not applied yet)" : "Apply selected thinking effort";
45144
+ }
45145
+
43859
45146
  function syncModelSelectToState() {
43860
45147
  if (!currentState?.model || !elements.modelSelect.options.length) return;
43861
45148
  const value = JSON.stringify({ provider: currentState.model.provider, modelId: currentState.model.id });
45149
+ if (controlsPendingModelValue && controlsPendingModelValue === value) setControlsPendingModel("");
45150
+ if (controlsPendingModelValue) return; // keep the user's unapplied choice visible
43862
45151
  for (const option of elements.modelSelect.options) {
43863
45152
  if (option.value === value) {
43864
45153
  elements.modelSelect.value = value;
@@ -43986,6 +45275,8 @@ function getCommandTrigger() {
43986
45275
  if (!match) return null;
43987
45276
 
43988
45277
  const query = match[2] || "";
45278
+ // "/etc/hosts" or "/tmp/x.txt" mid-sentence is a path, not a slash command.
45279
+ if (query.includes("/")) return null;
43989
45280
  return {
43990
45281
  start: cursor - query.length - 1,
43991
45282
  end: cursor,
@@ -44094,6 +45385,15 @@ function cancelBangSuggestionRequest() {
44094
45385
  function showCommandSuggestionList() {
44095
45386
  elements.commandSuggest.hidden = false;
44096
45387
  elements.promptInput?.setAttribute("aria-expanded", "true");
45388
+ const hasChoices = elements.commandSuggest.querySelector(".command-suggest-item") !== null;
45389
+ let hint = elements.commandSuggest.querySelector(".command-suggest-hint");
45390
+ if (hasChoices && !hint) {
45391
+ hint = make("div", "command-suggest-hint", "↑↓ navigate · Enter or Tab accept · Esc close");
45392
+ hint.setAttribute("aria-hidden", "true");
45393
+ elements.commandSuggest.append(hint);
45394
+ } else if (!hasChoices && hint) {
45395
+ hint.remove();
45396
+ }
44097
45397
  }
44098
45398
 
44099
45399
  function hideCommandSuggestions() {
@@ -44257,6 +45557,9 @@ async function renderPathSuggestions(trigger, { keepIndex = false } = {}) {
44257
45557
  elements.commandSuggest.setAttribute("aria-busy", "true");
44258
45558
 
44259
45559
  try {
45560
+ // Debounce keystrokes: one directory scan per pause instead of one per character.
45561
+ await new Promise((resolve) => setTimeout(resolve, PATH_SUGGEST_DEBOUNCE_MS));
45562
+ if (requestSerial !== pathSuggestRequestSerial || controller.signal.aborted) return;
44260
45563
  const response = await api(`/api/path-suggestions?query=${encodeURIComponent(trigger.query)}`, { signal: controller.signal });
44261
45564
  if (requestSerial !== pathSuggestRequestSerial || document.activeElement !== elements.promptInput) return;
44262
45565
  pathSuggestions = normalizePathSuggestions(response.data?.suggestions || []);
@@ -44546,6 +45849,16 @@ function commandPaletteCoreItems() {
44546
45849
  { kind: "Pi", label: "/scoped-models", description: "Manage model cycling scope", keywords: "models cycle ctrl p", run: () => runNativeCommandMenu("/scoped-models") },
44547
45850
  { kind: "Pi", label: "/tools", description: "Manage active tools", keywords: "capabilities", run: () => runNativeCommandMenu("/tools") },
44548
45851
  { kind: "Pi", label: "/skills", description: "Manage active skills", keywords: "system prompt", run: () => runNativeCommandMenu("/skills") },
45852
+ { kind: "Pi", label: "/theme", description: "Choose the Web UI theme", keywords: "dark light colors appearance", run: () => openNativeThemeSelector() },
45853
+ { kind: "Git", label: "Guided Git workflow", description: "Stage, commit, push, or open a pull request step by step", keywords: "git commit push pr publish", run: () => startGitWorkflow() },
45854
+ { kind: "Git", label: "Git changes", description: "Review and stage local changes with diffs", keywords: "git diff stage unstage discard status", run: () => openGitChangesDialog() },
45855
+ { kind: "Action", label: "Files panel", description: "Open the Files section of the Control Deck", keywords: "tree browse project explorer", run: () => revealSidePanelSectionById("files") },
45856
+ { kind: "Action", label: "Git panel", description: "Open the Git section of the Control Deck", keywords: "repository status history", run: () => revealSidePanelSectionById("git") },
45857
+ { kind: "Action", label: "Events log", description: "Open the Events section of the Control Deck", keywords: "errors warnings log diagnostics", run: () => revealEventsSection() },
45858
+ { kind: "Action", label: thinkingOutputVisible ? "Hide thinking output" : "Show thinking output", description: "Toggle thinking cards in the transcript (Ctrl/Cmd+T in the composer)", keywords: "reasoning thinking toggle", run: () => setThinkingOutputVisible(!thinkingOutputVisible, { announce: true }) },
45859
+ { kind: "Action", label: toolOutputGloballyExpanded ? "Collapse tool output" : "Expand tool output", description: "Toggle tool result cards (Ctrl/Cmd+O in the composer)", keywords: "tools results collapse expand", run: () => setToolOutputGloballyExpanded(!toolOutputGloballyExpanded, { announce: true }) },
45860
+ { kind: "Action", label: "Show all controls", description: "Restore every hidden button and input tag", keywords: "visibility hidden restore controls buttons", run: () => showAllControls() },
45861
+ { kind: "Action", label: "Reset control visibility", description: "Return hidden/visible controls to the defaults", keywords: "visibility defaults controls buttons", run: () => resetControlVisibilityDefaults() },
44549
45862
  ];
44550
45863
  if (tabs.length) {
44551
45864
  items.push({ kind: "Workspace", label: "Workspace: Save", description: "Capture all open tabs, sessions, groups, and the active tab", keywords: "workspace snapshot save sessions groups", run: () => saveWebuiWorkspace({ triggerButton: elements.commandPaletteButton }) });
@@ -44604,10 +45917,32 @@ function buildCommandPaletteItems() {
44604
45917
  ];
44605
45918
  }
44606
45919
 
45920
+ // Ranking: label prefix > label word-start > label contains > description/keywords only.
45921
+ // Ties keep catalog order (actions, tabs, models, commands), so results stay predictable.
45922
+ function paletteItemScore(item, query) {
45923
+ const label = paletteText(item.label);
45924
+ const tokens = query.split(/\s+/).filter(Boolean);
45925
+ let score = 0;
45926
+ for (const token of tokens) {
45927
+ if (label.startsWith(token)) score += 40;
45928
+ else if (label.replace(/^\//, "").startsWith(token)) score += 36;
45929
+ else if (new RegExp(`(^|[\\s/_-])${token.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`).test(label)) score += 24;
45930
+ else if (label.includes(token)) score += 12;
45931
+ else score += 1;
45932
+ }
45933
+ return score;
45934
+ }
45935
+
44607
45936
  function filteredCommandPaletteItems() {
44608
45937
  const query = paletteText(elements.commandPaletteInput?.value || "").trim();
44609
45938
  const items = buildCommandPaletteItems();
44610
- return (query ? items.filter((item) => paletteItemMatches(item, query)) : items).slice(0, 80);
45939
+ if (!query) return items.slice(0, 80);
45940
+ return items
45941
+ .map((item, index) => ({ item, index, score: paletteItemMatches(item, query) ? paletteItemScore(item, query) : -1 }))
45942
+ .filter((entry) => entry.score >= 0)
45943
+ .sort((a, b) => b.score - a.score || a.index - b.index)
45944
+ .slice(0, 80)
45945
+ .map((entry) => entry.item);
44611
45946
  }
44612
45947
 
44613
45948
  function setCommandPaletteIndex(index) {
@@ -44711,6 +46046,7 @@ function reportRefreshFailures(results, prefix = "") {
44711
46046
 
44712
46047
  async function refreshAll(tabContext = activeTabContext()) {
44713
46048
  if (!tabContext.tabId) return;
46049
+ noteRecentFullRefresh();
44714
46050
  const results = await Promise.allSettled([
44715
46051
  refreshState(tabContext),
44716
46052
  refreshMessages(tabContext),
@@ -44802,7 +46138,16 @@ async function reconcileForegroundState(reason = "resume") {
44802
46138
  renderMobilePhoneExperience();
44803
46139
  }
44804
46140
 
46141
+ // A tab activation/boot just ran the full refresh; the immediately following "event stream
46142
+ // reconnect" and "page show" signals would otherwise repeat every catalog fetch a second time.
46143
+ let recentFullRefreshFreshUntil = 0;
46144
+
46145
+ function noteRecentFullRefresh() {
46146
+ recentFullRefreshFreshUntil = performance.now() + 3_000;
46147
+ }
46148
+
44805
46149
  function scheduleForegroundReconcile(reason = "resume", delay = FOREGROUND_RECONCILE_DELAY_MS) {
46150
+ if ((reason === "event stream reconnect" || reason === "page show") && performance.now() < recentFullRefreshFreshUntil && !foregroundTranscriptCatchUpRequired) return;
44806
46151
  clearTimeout(foregroundReconcileTimer);
44807
46152
  foregroundReconcileTimer = setTimeout(() => {
44808
46153
  foregroundReconcileTimer = null;
@@ -45057,10 +46402,31 @@ function clearPromptFromShortcut() {
45057
46402
  if (document.activeElement !== input) return false;
45058
46403
  if (input.selectionStart !== input.selectionEnd) return false;
45059
46404
  if (!input.value) return false;
45060
- input.value = "";
46405
+ const previous = input.value;
46406
+ // Go through the editing command so the browser's own Ctrl+Z can bring the text back.
46407
+ let cleared = false;
46408
+ try {
46409
+ input.select();
46410
+ cleared = document.execCommand("delete");
46411
+ } catch {
46412
+ cleared = false;
46413
+ }
46414
+ if (!cleared || input.value) input.value = "";
45061
46415
  resizePromptInput();
45062
46416
  renderCommandSuggestions();
45063
46417
  addEvent("prompt cleared", "info");
46418
+ offerUndo({
46419
+ message: "Prompt cleared (Ctrl/Cmd+C with nothing selected).",
46420
+ undo: () => {
46421
+ input.value = previous;
46422
+ resizePromptInput();
46423
+ renderCommandSuggestions();
46424
+ input.focus({ preventScroll: true });
46425
+ input.setSelectionRange(previous.length, previous.length);
46426
+ },
46427
+ successMessage: "Prompt restored.",
46428
+ timeoutMs: 8000,
46429
+ });
45064
46430
  return true;
45065
46431
  }
45066
46432
 
@@ -45437,13 +46803,15 @@ function handleExtensionUiRequest(request) {
45437
46803
  if (request.statusText) {
45438
46804
  statusEntries.set(statusKey, request.statusText);
45439
46805
  if (statusKey === GIT_FOOTER_WEBUI_STATUS_KEY) {
45440
- const validPayload = !!parseGitFooterWebuiPayloadRaw(request.statusText);
46806
+ const footerPayload = parseGitFooterWebuiPayloadRaw(request.statusText);
46807
+ const validPayload = !!footerPayload;
45441
46808
  cacheGitFooterWebuiPayload(request.statusText, request.tabId);
45442
46809
  settleGitFooterPayload(
45443
46810
  request.tabId || activeTabId,
45444
46811
  validPayload ? "ready" : "failed",
45445
46812
  validPayload ? "" : "Git footer returned invalid status data — refresh to retry",
45446
46813
  );
46814
+ if (footerPayload) syncClaudeUsageFromGitFooterPayload(footerPayload);
45447
46815
  }
45448
46816
  } else {
45449
46817
  statusEntries.delete(statusKey);
@@ -45950,7 +47318,7 @@ function scheduleSupervisorContinuityRefresh(event, { gap = false } = {}) {
45950
47318
 
45951
47319
  if (gap && !supervisorGapWarnings.has(key)) {
45952
47320
  supervisorGapWarnings.add(key);
45953
- addEvent("Buffered live output may be incomplete; refreshing tabs, state, and transcript from Pi.", "warn");
47321
+ addEvent("Buffered live output may be incomplete; refreshing tabs, state, and transcript from Pi.", "info");
45954
47322
  }
45955
47323
  if (supervisorContinuityRefreshes.has(key)) return;
45956
47324
 
@@ -46022,6 +47390,7 @@ const TRANSCRIPT_STREAM_BARRIER_EVENT_TYPES = new Set([
46022
47390
  function beginForegroundTranscriptCatchUp() {
46023
47391
  foregroundTranscriptCatchUpRequired = true;
46024
47392
  backgroundReconnectSnapshotFresh = false;
47393
+ flushNormalStreamRenders("visibility-hidden");
46025
47394
  streamOutputController.cancel();
46026
47395
  if (!eventSource) return;
46027
47396
  eventStreamPausedForBackground = true;
@@ -46046,6 +47415,10 @@ function dispatchTranscriptStreamEvent(event) {
46046
47415
  function flushTranscriptStreamBarrier(event) {
46047
47416
  if (!TRANSCRIPT_STREAM_BARRIER_EVENT_TYPES.has(event?.type)) return;
46048
47417
  streamOutputController.barrier(event.type);
47418
+ if (["message_end", "agent_end", "agent_settled", "compaction_end", "pi_process_exit", "pi_process_error"].includes(event.type)) {
47419
+ fallbackStreamDerivedOutput(`settlement:${event.type}`);
47420
+ }
47421
+ flushNormalStreamRenders(event.type);
46049
47422
  reconcileUnknownTranscriptEvidenceAtBarrier(event);
46050
47423
  if (event.type === "pi_process_exit" || event.type === "pi_process_error") streamOutputController.cancel();
46051
47424
  }
@@ -46172,12 +47545,18 @@ function handleEvent(event) {
46172
47545
  }
46173
47546
  break;
46174
47547
  }
46175
- case "webui_app_runner_update":
46176
- setAppRunnerData(event.tabId || activeTabId, { cwd: event.cwd, activeRun: event.activeRun });
47548
+ case "webui_app_runner_update": {
47549
+ const runTabId = event.tabId || activeTabId;
47550
+ const previousRun = appRunnerDataByTab.get(runTabId)?.activeRun || null;
47551
+ setAppRunnerData(runTabId, { cwd: event.cwd, activeRun: event.activeRun });
46177
47552
  renderAppRunnerControls();
46178
- renderWidgets();
46179
- renderTabs();
47553
+ // A chatty dev server sends several updates per second; append only the new lines to the
47554
+ // existing widget instead of rebuilding every widget and the tab strip each time.
47555
+ if (!patchAppRunnerWidgetInPlace(runTabId, previousRun, event.activeRun)) renderWidgets();
47556
+ const runningChanged = Boolean(previousRun && appRunnerIsRunning(previousRun)) !== Boolean(event.activeRun && appRunnerIsRunning(event.activeRun));
47557
+ if (!previousRun !== !event.activeRun || runningChanged || previousRun?.id !== event.activeRun?.id) renderTabs();
46180
47558
  break;
47559
+ }
46181
47560
  case "webui_git_changed":
46182
47561
  invalidateGitPanelRepository(event.root);
46183
47562
  break;
@@ -46276,7 +47655,7 @@ function handleEvent(event) {
46276
47655
  if (!assistantErrorSurfacedThisRun && event.willRetry !== true) {
46277
47656
  const message = assistantErrorFromAgentEnd(event);
46278
47657
  if (message) {
46279
- surfaceRuntimeDiagnostic("Assistant error", message);
47658
+ surfaceRuntimeDiagnostic("Assistant error", describeAssistantFailure(message), "error", { actions: assistantFailureActions(event.tabId || activeTabId) });
46280
47659
  assistantErrorSurfacedThisRun = true;
46281
47660
  }
46282
47661
  }
@@ -46296,7 +47675,7 @@ function handleEvent(event) {
46296
47675
  streamMessageActive = false;
46297
47676
  if (event.message?.role === "assistant" && event.message.stopReason === "error") {
46298
47677
  const message = String(event.message.errorMessage || streamProviderErrorText || "The assistant request failed without an error message.").trim();
46299
- surfaceRuntimeDiagnostic("Assistant error", message);
47678
+ surfaceRuntimeDiagnostic("Assistant error", describeAssistantFailure(message), "error", { actions: assistantFailureActions(event.tabId || activeTabId) });
46300
47679
  assistantErrorSurfacedThisRun = true;
46301
47680
  }
46302
47681
  streamProviderErrorText = "";
@@ -46399,22 +47778,24 @@ function handleEvent(event) {
46399
47778
  const seconds = Math.max(0, Math.ceil(Number(event.delayMs || 0) / 1000));
46400
47779
  const retryText = `Retrying (${event.attempt || "?"}/${event.maxAttempts || "?"}) in ${seconds}s after: ${event.errorMessage || "model/provider error"}`;
46401
47780
  setRunIndicatorActivity(retryText);
46402
- addEvent(retryText, "warn");
46403
- addTransientMessage({ role: "warn", title: "auto retry", content: retryText, level: "warn" });
47781
+ addEvent(retryText, "warn", { notify: false });
47782
+ addTransientMessage({ role: "warn", title: "auto retry", content: retryText, level: "warn", key: "auto-retry" });
46404
47783
  break;
46405
47784
  }
46406
47785
  case "auto_retry_end":
46407
47786
  if (event.success === false) {
46408
47787
  const retryError = `Retry failed after ${event.attempt || "?"} attempt(s): ${event.finalError || "Unknown error"}`;
46409
- addEvent(retryError, "error");
46410
- addTransientMessage({ role: "error", title: "auto retry failed", content: retryError, level: "error" });
47788
+ addEvent(retryError, "error", { notify: false });
47789
+ addTransientMessage({ role: "error", title: "auto retry failed", content: describeAssistantFailure(retryError), level: "error", key: "auto-retry", actions: assistantFailureActions(event.tabId || activeTabId) });
46411
47790
  } else {
46412
47791
  addEvent(`retry recovered after ${event.attempt || "?"} attempt(s)`);
47792
+ transientMessages = transientMessages.filter((message) => message?.key !== "auto-retry");
47793
+ renderAllMessages();
46413
47794
  }
46414
47795
  break;
46415
47796
  case "extension_error": {
46416
47797
  const message = `${event.extensionPath || "extension"}${event.event ? ` during ${event.event}` : ""}: ${event.error || "unknown extension error"}`;
46417
- addEvent(message, "error");
47798
+ addEvent(message, "error", { notify: false });
46418
47799
  addTransientMessage({ role: "error", title: "extension error", content: message, level: "error" });
46419
47800
  break;
46420
47801
  }
@@ -46452,9 +47833,12 @@ function handleEvent(event) {
46452
47833
  }
46453
47834
 
46454
47835
  function connectEvents(tabContext = activeTabContext(), { requestedMode = "auto", fallbackAttempted = false } = {}) {
47836
+ flushNormalStreamRenders("reconnect");
47837
+ cancelNormalStreamRenders();
46455
47838
  eventSource?.close();
46456
47839
  eventSource = null;
46457
47840
  streamOutputController.cancel();
47841
+ fallbackStreamDerivedOutput("reconnect");
46458
47842
  resetCompactLiveOutput();
46459
47843
  activeOutputMode = "normal";
46460
47844
  outputModeAcknowledged = false;
@@ -46486,7 +47870,9 @@ function connectEvents(tabContext = activeTabContext(), { requestedMode = "auto"
46486
47870
  source.onerror = () => {
46487
47871
  if (eventSource !== source || !isCurrentTabContext(tabContext)) return;
46488
47872
  streamOutputController.flush();
47873
+ flushNormalStreamRenders("disconnect");
46489
47874
  streamOutputController.cancel();
47875
+ fallbackStreamDerivedOutput("disconnect");
46490
47876
  if (compactOutputActive()) compactLiveScheduler.flushNow();
46491
47877
  addEvent("event stream disconnected; browser will retry", "warn");
46492
47878
  fetch("/api/health", { cache: "no-store" }).catch((error) => setBackendOffline(true, error));
@@ -46515,12 +47901,22 @@ elements.promptListSaveButton?.addEventListener("click", saveDisplayedPromptList
46515
47901
  elements.promptListRunListButton?.addEventListener("click", () => runDisplayedPromptList());
46516
47902
  elements.promptListCloseButton?.addEventListener("click", () => elements.promptListDialog?.close());
46517
47903
  elements.promptListDialog?.querySelector("form")?.addEventListener("submit", (event) => event.preventDefault());
46518
- elements.attachmentTextCancelButton?.addEventListener("click", closeTextAttachmentEditor);
47904
+ elements.attachmentTextCancelButton?.addEventListener("click", () => closeTextAttachmentEditor());
46519
47905
  elements.attachmentTextSaveButton?.addEventListener("click", saveTextAttachmentEdit);
46520
47906
  elements.attachmentTextEditor?.addEventListener("input", () => {
47907
+ if (activeTextAttachmentEditor) activeTextAttachmentEditor.dirty = true;
46521
47908
  renderTextAttachmentEditorMeta();
46522
47909
  setAttachmentTextStatus("Unsaved attachment edits.", "warn");
46523
47910
  });
47911
+ elements.attachmentTextDialog?.addEventListener("cancel", (event) => {
47912
+ if (!activeTextAttachmentEditor?.dirty) return;
47913
+ event.preventDefault();
47914
+ confirmDiscardEdits({ what: "unsaved attachment edits", target: "The attachment text" }).then((confirmed) => {
47915
+ if (!confirmed) return;
47916
+ if (activeTextAttachmentEditor) activeTextAttachmentEditor.dirty = false;
47917
+ elements.attachmentTextDialog.close();
47918
+ });
47919
+ });
46524
47920
  elements.attachmentTextDialog?.addEventListener("close", () => {
46525
47921
  activeTextAttachmentEditor = null;
46526
47922
  if (elements.attachmentTextEditor) elements.attachmentTextEditor.value = "";
@@ -46532,9 +47928,21 @@ elements.attachmentTextDialog?.addEventListener("keydown", (event) => {
46532
47928
  if (!elements.attachmentTextSaveButton?.disabled) saveTextAttachmentEdit();
46533
47929
  });
46534
47930
  elements.attachmentTextDialog?.querySelector("form")?.addEventListener("submit", (event) => event.preventDefault());
46535
- elements.skillEditorCancelButton?.addEventListener("click", closeSkillEditor);
47931
+ elements.skillEditorCancelButton?.addEventListener("click", () => closeSkillEditor());
46536
47932
  elements.skillEditorSaveButton?.addEventListener("click", saveSkillEditor);
46537
- elements.skillEditorText?.addEventListener("input", () => setSkillEditorStatus("Unsaved skill edits.", "warn"));
47933
+ elements.skillEditorText?.addEventListener("input", () => {
47934
+ if (activeSkillEditor) activeSkillEditor.dirty = true;
47935
+ setSkillEditorStatus("Unsaved skill edits.", "warn");
47936
+ });
47937
+ elements.skillEditorDialog?.addEventListener("cancel", (event) => {
47938
+ if (!activeSkillEditor?.dirty) return;
47939
+ event.preventDefault();
47940
+ confirmDiscardEdits({ what: "unsaved skill edits", target: activeSkillEditor?.path || activeSkillEditor?.name || "SKILL.md" }).then((confirmed) => {
47941
+ if (!confirmed) return;
47942
+ if (activeSkillEditor) activeSkillEditor.dirty = false;
47943
+ elements.skillEditorDialog.close();
47944
+ });
47945
+ });
46538
47946
  elements.skillEditorDialog?.addEventListener("close", () => {
46539
47947
  activeSkillEditor = null;
46540
47948
  if (elements.skillEditorText) elements.skillEditorText.value = "";
@@ -46626,6 +48034,18 @@ elements.btwButton?.addEventListener("click", () => sendBtwPromptFromButton());
46626
48034
  elements.terminalTabsToggleButton.addEventListener("click", () => {
46627
48035
  setMobileTabsExpanded(!document.body.classList.contains("mobile-tabs-expanded"), { restoreFocus: true });
46628
48036
  });
48037
+ // Tablist keyboard semantics: Left/Right/Home/End move focus between terminal tabs.
48038
+ elements.tabBar?.addEventListener("keydown", (event) => {
48039
+ if (!["ArrowLeft", "ArrowRight", "Home", "End"].includes(event.key) || event.altKey || event.ctrlKey || event.metaKey) return;
48040
+ const tabsInStrip = [...elements.tabBar.querySelectorAll('[role="tab"]')].filter((node) => !node.disabled && node.offsetParent !== null);
48041
+ const index = tabsInStrip.indexOf(document.activeElement);
48042
+ if (index === -1) return;
48043
+ event.preventDefault();
48044
+ const next = event.key === "Home" ? 0
48045
+ : event.key === "End" ? tabsInStrip.length - 1
48046
+ : (index + (event.key === "ArrowRight" ? 1 : -1) + tabsInStrip.length) % tabsInStrip.length;
48047
+ tabsInStrip[next]?.focus({ preventScroll: false });
48048
+ });
46629
48049
  elements.newTabButton.addEventListener("click", (event) => {
46630
48050
  event.stopPropagation();
46631
48051
  openNewTabMenu();
@@ -46679,6 +48099,7 @@ elements.gitWorkflowButton.addEventListener("click", () => {
46679
48099
  });
46680
48100
  const publishMenuContainer = elements.publishButton.parentElement;
46681
48101
  elements.publishButton.addEventListener("click", () => {
48102
+ clearComposerMenuDismissal(elements.publishButton.parentElement);
46682
48103
  setNativeCommandMenuOpen(false);
46683
48104
  setAppRunnerMenuOpen(false);
46684
48105
  setOptionsMenuOpen(false);
@@ -46704,6 +48125,7 @@ publishMenuContainer?.addEventListener("focusout", () => {
46704
48125
  });
46705
48126
  const nativeCommandMenuContainer = elements.nativeCommandMenuButton.parentElement;
46706
48127
  elements.nativeCommandMenuButton.addEventListener("click", () => {
48128
+ clearComposerMenuDismissal(elements.nativeCommandMenuButton.parentElement);
46707
48129
  setPublishMenuOpen(false);
46708
48130
  setAppRunnerMenuOpen(false);
46709
48131
  setOptionsMenuOpen(false);
@@ -46771,6 +48193,7 @@ appRunnerMenuContainer?.addEventListener("focusout", () => {
46771
48193
  });
46772
48194
  const optionsMenuContainer = elements.optionsMenuButton.parentElement;
46773
48195
  elements.optionsMenuButton.addEventListener("click", () => {
48196
+ clearComposerMenuDismissal(elements.optionsMenuButton.parentElement);
46774
48197
  setPublishMenuOpen(false);
46775
48198
  setNativeCommandMenuOpen(false);
46776
48199
  setAppRunnerMenuOpen(false);
@@ -46945,6 +48368,13 @@ elements.nativeCommandDialog.addEventListener("cancel", (event) => {
46945
48368
  event.preventDefault();
46946
48369
  closeNativeCommandDialog();
46947
48370
  });
48371
+ // The dialog form uses method="dialog"; without this, Enter inside the filter box (or any
48372
+ // settings text field) implicitly submits and closes the dialog without choosing anything.
48373
+ elements.nativeCommandDialog.querySelector("form")?.addEventListener("submit", (event) => {
48374
+ event.preventDefault();
48375
+ if (document.activeElement === elements.nativeCommandSearch) activateNativeSelectorHighlight();
48376
+ });
48377
+ elements.nativeCommandSearch.addEventListener("keydown", handleNativeSelectorSearchKeydown);
46948
48378
  elements.nativeCommandDialog.addEventListener("close", () => {
46949
48379
  elements.nativeCommandSearch.oninput = null;
46950
48380
  nativeSettingsDirty = false;
@@ -46952,6 +48382,18 @@ elements.nativeCommandDialog.addEventListener("close", () => {
46952
48382
  });
46953
48383
  elements.undoToastButton?.addEventListener("click", () => runOfferedUndo());
46954
48384
  elements.undoToastDismissButton?.addEventListener("click", dismissUndoToast);
48385
+ elements.textPromptDialog?.querySelector("form")?.addEventListener("submit", (event) => {
48386
+ event.preventDefault();
48387
+ submitTextPrompt();
48388
+ });
48389
+ elements.textPromptCancelButton?.addEventListener("click", () => finishTextPrompt(null));
48390
+ elements.textPromptDialog?.addEventListener("cancel", (event) => {
48391
+ event.preventDefault();
48392
+ finishTextPrompt(null);
48393
+ });
48394
+ elements.textPromptDialog?.addEventListener("close", () => {
48395
+ if (activeTextPromptResolve) finishTextPrompt(null);
48396
+ });
46955
48397
  elements.confirmationCancelButton?.addEventListener("click", () => finishApplicationConfirmation(false));
46956
48398
  elements.confirmationConfirmButton?.addEventListener("click", () => finishApplicationConfirmation(true));
46957
48399
  elements.gitPullErrorMergeButton?.addEventListener("click", () => integrateGitPullDivergence("merge"));
@@ -47049,7 +48491,21 @@ function abortButtonHoldSeconds() {
47049
48491
  }
47050
48492
 
47051
48493
  function abortButtonReadyTitle() {
47052
- return `Hold Esc or the Abort button for ${abortButtonHoldSeconds()} seconds to abort the active Pi run`;
48494
+ return `Hold Esc or the Abort button for about ${abortButtonHoldSeconds()} second to abort the active Pi run`;
48495
+ }
48496
+
48497
+ // A quick tap/click on Abort deliberately does nothing (the hold prevents accidental aborts), but
48498
+ // silently doing nothing reads as "broken". Show what to do for a moment instead.
48499
+ function showAbortTapHint() {
48500
+ if (!isAbortAvailable() || isAbortLongPressActive() || abortRequestInFlight) return;
48501
+ clearTimeout(abortTapHintTimer);
48502
+ elements.abortButton.classList.add("tap-hint");
48503
+ elements.abortButton.textContent = "Hold to abort";
48504
+ abortTapHintTimer = setTimeout(() => {
48505
+ abortTapHintTimer = null;
48506
+ elements.abortButton.classList.remove("tap-hint");
48507
+ if (!isAbortLongPressActive() && !abortRequestInFlight) elements.abortButton.textContent = "Abort";
48508
+ }, ABORT_TAP_HINT_MS);
47053
48509
  }
47054
48510
 
47055
48511
  function suppressEmptyPromptEscapeAction({ untilKeyup = false, graceMs = EMPTY_PROMPT_ESCAPE_AFTER_ABORT_GRACE_MS } = {}) {
@@ -47157,7 +48613,7 @@ function resetAbortLongPressAffordance() {
47157
48613
  abortLongPressReleasePending = false;
47158
48614
  elements.abortButton.classList.remove("long-pressing");
47159
48615
  elements.abortButton.style.removeProperty("--abort-long-press-duration");
47160
- if (!abortRequestInFlight) {
48616
+ if (!abortRequestInFlight && !abortTapHintTimer) {
47161
48617
  elements.abortButton.textContent = "Abort";
47162
48618
  elements.abortButton.title = isAbortAvailable() ? abortButtonReadyTitle() : "Abort is available while Pi is running";
47163
48619
  elements.abortButton.setAttribute("aria-label", elements.abortButton.title);
@@ -47168,6 +48624,7 @@ async function abortActiveRun({ source = "button" } = {}) {
47168
48624
  if (abortRequestInFlight || !isAbortAvailable()) return;
47169
48625
  const tabContext = activeTabContext();
47170
48626
  streamOutputController.barrier("user-abort");
48627
+ flushNormalStreamRenders("user-abort");
47171
48628
  reconcileUnknownTranscriptEvidenceAtBarrier({ type: "user_abort", tabId: tabContext.tabId });
47172
48629
  abortRequestInFlight = true;
47173
48630
  resetAbortLongPressAffordance();
@@ -47237,7 +48694,11 @@ elements.abortButton.addEventListener("keyup", (event) => {
47237
48694
  });
47238
48695
  elements.abortButton.addEventListener("click", (event) => {
47239
48696
  event.preventDefault();
47240
- if (abortLongPressHandled) abortLongPressHandled = false;
48697
+ if (abortLongPressHandled) {
48698
+ abortLongPressHandled = false;
48699
+ return;
48700
+ }
48701
+ showAbortTapHint();
47241
48702
  });
47242
48703
  elements.newSessionButton.addEventListener("click", async () => {
47243
48704
  setComposerActionsOpen(false);
@@ -47300,6 +48761,8 @@ elements.modelSearchInput?.addEventListener("keydown", (event) => {
47300
48761
  elements.modelSearchInput.focus();
47301
48762
  }
47302
48763
  });
48764
+ elements.modelSelect?.addEventListener("change", () => setControlsPendingModel(elements.modelSelect.value));
48765
+ elements.thinkingSelect?.addEventListener("change", () => setControlsPendingThinking(elements.thinkingSelect.value));
47303
48766
  elements.setModelButton.addEventListener("click", async () => {
47304
48767
  if (!elements.modelSelect.value) return;
47305
48768
  const tabContext = activeTabContext();
@@ -47307,6 +48770,7 @@ elements.setModelButton.addEventListener("click", async () => {
47307
48770
  const selected = JSON.parse(elements.modelSelect.value);
47308
48771
  const response = await api("/api/model", { method: "POST", body: selected, tabId: tabContext.tabId });
47309
48772
  if (isCurrentTabContext(tabContext)) {
48773
+ setControlsPendingModel("");
47310
48774
  applyOptimisticModelSelection(response.data || selected, tabContext);
47311
48775
  await refreshState(tabContext);
47312
48776
  }
@@ -47319,13 +48783,15 @@ elements.setThinkingButton.addEventListener("click", async () => {
47319
48783
  try {
47320
48784
  const response = await api("/api/thinking", { method: "POST", body: { level: elements.thinkingSelect.value }, tabId: tabContext.tabId });
47321
48785
  if (isCurrentTabContext(tabContext)) {
48786
+ setControlsPendingThinking("");
47322
48787
  applyOptimisticThinkingSelection(response.data, tabContext);
47323
48788
  if (response.data?.pending) {
47324
48789
  addEvent(response.data.message || `Thinking level ${response.data.level} will apply to the next prompt.`, "info");
47325
48790
  } else if (response.data?.level) {
47326
48791
  const requested = response.data.requestedLevel;
47327
48792
  const effective = response.data.level;
47328
- addEvent(requested && requested !== effective ? `Thinking level set to ${effective} (requested ${requested}).` : `Thinking level set to ${effective}.`, "info");
48793
+ if (requested && requested !== effective) addEvent(`Thinking level set to ${effective}: the active model does not support ${requested}.`, "warn");
48794
+ else addEvent(`Thinking level set to ${effective}.`, "info");
47329
48795
  }
47330
48796
  await refreshState(tabContext);
47331
48797
  }
@@ -47676,6 +49142,13 @@ function shouldHandleNativeAppShortcut(event) {
47676
49142
  return event.target === elements.promptInput || !isTextEntryTarget(event.target);
47677
49143
  }
47678
49144
 
49145
+ // TUI-parity chords (Ctrl+P model cycle, Ctrl+T thinking output, Ctrl+O tool output, Ctrl+C
49146
+ // clear, Shift+Tab thinking level) only apply while the composer has focus. Elsewhere they must
49147
+ // keep their browser meaning (print, reverse Tab navigation, copy, …).
49148
+ function isComposerScopedShortcutTarget(event) {
49149
+ return event.target === elements.promptInput;
49150
+ }
49151
+
47679
49152
  function handleNativeAppShortcut(event) {
47680
49153
  if (!shouldHandleNativeAppShortcut(event)) return;
47681
49154
  const key = event.key;
@@ -47692,6 +49165,17 @@ function handleNativeAppShortcut(event) {
47692
49165
  openNativeModelSelector();
47693
49166
  return;
47694
49167
  }
49168
+ if (!ctrlOrMeta && !event.metaKey && event.altKey && key === "Enter") {
49169
+ event.preventDefault();
49170
+ if (hasComposerPayload()) sendPrompt("follow-up");
49171
+ return;
49172
+ }
49173
+ if (!ctrlOrMeta && event.altKey && key === "ArrowUp") {
49174
+ event.preventDefault();
49175
+ restoreQueuedMessagesToComposerFromShortcut();
49176
+ return;
49177
+ }
49178
+ if (!isComposerScopedShortcutTarget(event)) return;
47695
49179
  if (ctrlOrMeta && !event.altKey && lowerKey === "p") {
47696
49180
  event.preventDefault();
47697
49181
  cycleModelFromShortcut(event.shiftKey ? "backward" : "forward");
@@ -47714,16 +49198,6 @@ function handleNativeAppShortcut(event) {
47714
49198
  if (!event.ctrlKey && !event.metaKey && !event.altKey && event.shiftKey && key === "Tab") {
47715
49199
  event.preventDefault();
47716
49200
  cycleThinkingFromShortcut();
47717
- return;
47718
- }
47719
- if (!event.ctrlKey && !event.metaKey && event.altKey && key === "Enter") {
47720
- event.preventDefault();
47721
- if (hasComposerPayload()) sendPrompt("follow-up");
47722
- return;
47723
- }
47724
- if (!event.ctrlKey && !event.metaKey && event.altKey && key === "ArrowUp") {
47725
- event.preventDefault();
47726
- restoreQueuedMessagesToComposerFromShortcut();
47727
49201
  }
47728
49202
  }
47729
49203
 
@@ -47884,6 +49358,8 @@ elements.chatSearchNextButton?.addEventListener("click", () => stepChatSearch(1)
47884
49358
  elements.chatSearchCloseButton?.addEventListener("click", closeChatSearch);
47885
49359
  window.addEventListener("keydown", (event) => {
47886
49360
  if ((event.ctrlKey || event.metaKey) && !event.altKey && !event.shiftKey && event.key.toLowerCase() === "f") {
49361
+ // Inside a modal dialog (settings, palette, pickers) leave the browser's own find alone.
49362
+ if (document.querySelector("dialog[open]")) return;
47887
49363
  event.preventDefault();
47888
49364
  if (activeFileViewer && elements.fileViewerPane?.contains(event.target)) openFileViewerSearch();
47889
49365
  else openChatSearch();
@@ -47893,6 +49369,7 @@ window.addEventListener("keydown", (event) => {
47893
49369
  window.addEventListener("keydown", handleNativeAppShortcut, { capture: true });
47894
49370
  document.addEventListener("visibilitychange", () => {
47895
49371
  if (document.visibilityState === "visible") {
49372
+ flushNormalStreamRenders("visibility-recovery");
47896
49373
  scheduleForegroundReconcile("visibility resume", 0);
47897
49374
  refreshSubagents().finally(() => scheduleRefreshSubagents());
47898
49375
  } else {
@@ -47994,18 +49471,26 @@ window.addEventListener("keydown", (event) => {
47994
49471
  }
47995
49472
  if (publishMenuOpen) {
47996
49473
  setPublishMenuOpen(false);
49474
+ armComposerMenuDismissal(elements.publishButton?.parentElement);
49475
+ elements.publishButton?.focus({ preventScroll: true });
47997
49476
  return;
47998
49477
  }
47999
49478
  if (nativeCommandMenuOpen) {
48000
49479
  setNativeCommandMenuOpen(false);
49480
+ armComposerMenuDismissal(elements.nativeCommandMenuButton?.parentElement);
49481
+ elements.nativeCommandMenuButton?.focus({ preventScroll: true });
48001
49482
  return;
48002
49483
  }
48003
49484
  if (appRunnerMenuOpen) {
48004
49485
  setAppRunnerMenuOpen(false);
49486
+ armComposerMenuDismissal(elements.appRunnerMenuButton?.parentElement);
49487
+ elements.appRunnerMenuButton?.focus({ preventScroll: true });
48005
49488
  return;
48006
49489
  }
48007
49490
  if (optionsMenuOpen) {
48008
49491
  setOptionsMenuOpen(false);
49492
+ armComposerMenuDismissal(elements.optionsMenuButton?.parentElement);
49493
+ elements.optionsMenuButton?.focus({ preventScroll: true });
48009
49494
  return;
48010
49495
  }
48011
49496
  if (conversationVoiceMenuOpen) {
@@ -48117,7 +49602,7 @@ elements.refreshCodexUsageButton?.addEventListener("click", () => {
48117
49602
  refreshCodexUsage({ forceAuthRefresh: true }).finally(() => scheduleRefreshCodexUsage());
48118
49603
  });
48119
49604
  elements.refreshClaudeUsageButton?.addEventListener("click", () => {
48120
- refreshClaudeUsage().finally(() => scheduleRefreshClaudeUsage());
49605
+ refreshClaudeUsage({ forceCli: true }).finally(() => scheduleRefreshClaudeUsage());
48121
49606
  });
48122
49607
  elements.fileTreeRefreshButton?.addEventListener("click", () => refreshFileTreeRoot().catch((error) => addEvent(error.message || String(error), "error")));
48123
49608
  elements.fileTreeRoot?.addEventListener("keydown", handleFileTreeKeydown);
@@ -48211,8 +49696,16 @@ elements.visibilityContextMenu?.addEventListener("click", (event) => {
48211
49696
  const action = button.dataset.visibilityMenuAction;
48212
49697
  if (action === "hide") {
48213
49698
  const entryId = visibilityContextMenuState?.entryId;
48214
- if (entryId) setControlVisibilityHidden(entryId, true);
48215
49699
  closeVisibilityContextMenu();
49700
+ if (entryId) {
49701
+ const label = CONTROL_VISIBILITY_REGISTRY.get(entryId)?.label || "control";
49702
+ setControlVisibilityHidden(entryId, true);
49703
+ offerUndo({
49704
+ message: `Hid ${label}. Right-click a toolbar area (or use the command palette) to show hidden controls again.`,
49705
+ undo: () => setControlVisibilityHidden(entryId, false),
49706
+ successMessage: `${label} is visible again.`,
49707
+ });
49708
+ }
48216
49709
  } else if (action === "show-all") {
48217
49710
  closeVisibilityContextMenu();
48218
49711
  showAllControls();
@@ -48245,6 +49738,7 @@ elements.gitFooterContextMenu?.addEventListener("click", (event) => {
48245
49738
  if (action === "disable") void disableGitFooterContextChip(state.key, state.label);
48246
49739
  else if (action === "visibility") openGitFooterVisibilityDialog();
48247
49740
  });
49741
+ elements.fileTreeNewFileButton?.addEventListener("click", () => createFileTreeEntry(null, "file").catch((error) => addEvent(error.message || String(error), "error")));
48248
49742
  elements.fileContextMenu?.addEventListener("click", (event) => {
48249
49743
  const button = event.target?.closest?.("[data-file-menu-action]");
48250
49744
  if (!button) return;
@@ -48255,6 +49749,8 @@ elements.fileContextMenu?.addEventListener("click", (event) => {
48255
49749
  if (action === "open-default") openPathInDefaultEditor(entry.path).catch((error) => addEvent(error.message || String(error), "error"));
48256
49750
  else if (action === "open-webui") openFileTreeEntryInWebui(entry).catch((error) => addEvent(error.message || String(error), "error"));
48257
49751
  else if (action === "move") moveFileTreeEntry(entry).catch((error) => addEvent(error.message || String(error), "error"));
49752
+ else if (action === "new-file") createFileTreeEntry(entry, "file").catch((error) => addEvent(error.message || String(error), "error"));
49753
+ else if (action === "new-folder") createFileTreeEntry(entry, "directory").catch((error) => addEvent(error.message || String(error), "error"));
48258
49754
  else if (action === "delete") deleteFileTreeEntry(entry).catch((error) => addEvent(error.message || String(error), "error"));
48259
49755
  });
48260
49756
  elements.fileViewerOpenDefaultButton?.addEventListener("click", () => openPathInDefaultEditor(currentFileViewerPath()));
@@ -48267,7 +49763,20 @@ elements.terminalTabsResizeHandle?.addEventListener("keydown", handleTerminalTab
48267
49763
  elements.fileViewerResizeHandle?.addEventListener("pointerdown", beginFileViewerResize);
48268
49764
  elements.fileViewerResizeHandle?.addEventListener("keydown", handleFileViewerResizeKeydown);
48269
49765
  elements.fileViewerSaveButton?.addEventListener("click", () => saveActiveFileViewer());
48270
- elements.fileViewerCloseButton?.addEventListener("click", closeFileViewer);
49766
+ elements.fileViewerCloseButton?.addEventListener("click", async () => {
49767
+ if (activeFileViewer?.dirty && !(await confirmDiscardEdits({ what: "unsaved file edits", target: activeFileViewer.path }))) return;
49768
+ closeFileViewer();
49769
+ });
49770
+ // Reload/close with unsaved file edits or a non-empty composer asks first (browser-native prompt).
49771
+ window.addEventListener("pagehide", () => persistDesktopDrafts());
49772
+ window.addEventListener("beforeunload", (event) => {
49773
+ persistDesktopDrafts();
49774
+ // Text drafts are persisted above; only unsaved file edits and file attachments would be lost.
49775
+ const attachmentsPending = activeTabId ? attachmentsForTab(activeTabId).some((attachment) => attachment?.file) : false;
49776
+ if (!activeFileViewer?.dirty && !attachmentsPending) return;
49777
+ event.preventDefault();
49778
+ event.returnValue = "";
49779
+ });
48271
49780
  elements.fileViewerChangesModeButton?.addEventListener("click", () => setFileViewerMode("changes"));
48272
49781
  elements.fileViewerSourceModeButton?.addEventListener("click", () => setFileViewerMode("source"));
48273
49782
  elements.fileViewerPreviewModeButton?.addEventListener("click", () => setFileViewerMode("preview"));
@@ -48367,9 +49876,60 @@ elements.promptInput.addEventListener("paste", handleAttachmentPaste);
48367
49876
  elements.composer.addEventListener("dragover", handleComposerDragOver);
48368
49877
  elements.composer.addEventListener("dragleave", handleComposerDragLeave);
48369
49878
  elements.composer.addEventListener("drop", handleComposerDrop);
49879
+ // A file dropped anywhere else (transcript, panels, empty chrome) must never navigate the tab
49880
+ // away from the app; treat the whole window as an attachment drop zone unless a more specific
49881
+ // target (composer, file tree) already handled it.
49882
+ window.addEventListener("dragover", (event) => {
49883
+ if (event.defaultPrevented || !isFileDrag(event)) return;
49884
+ event.preventDefault();
49885
+ if (event.dataTransfer) event.dataTransfer.dropEffect = "copy";
49886
+ });
49887
+ window.addEventListener("drop", (event) => {
49888
+ if (event.defaultPrevented || !isFileDrag(event)) return;
49889
+ event.preventDefault();
49890
+ elements.composer.classList.remove("drag-over");
49891
+ addAttachmentFiles(event.dataTransfer?.files, "drop");
49892
+ });
49893
+
49894
+ // Enter accepts the highlighted suggestion (like Tab) unless the token already equals it,
49895
+ // in which case Enter falls through to send. Ctrl/Cmd+Enter always sends.
49896
+ function highlightedSuggestionAlreadyTyped() {
49897
+ const index = commandSuggestIndex;
49898
+ if (suggestionMode === "path") {
49899
+ const suggestion = pathSuggestions[index];
49900
+ const trigger = getPathTrigger();
49901
+ if (!suggestion || !trigger) return true;
49902
+ const typed = String(trigger.query || "").replace(/\\/g, "/");
49903
+ const target = String(suggestion.path || "").replace(/\\/g, "/");
49904
+ return typed === target || typed === target.replace(/\/$/, "");
49905
+ }
49906
+ if (suggestionMode === "bang") {
49907
+ const suggestion = bangSuggestions[index];
49908
+ const trigger = getBangTrigger();
49909
+ if (!suggestion || !trigger) return true;
49910
+ const typed = `${trigger.bangPrefix || ""}${trigger.query || ""}`;
49911
+ return typed === String(suggestion.insertText || "");
49912
+ }
49913
+ const command = commandSuggestions[index];
49914
+ const trigger = getCommandTrigger();
49915
+ if (!command || !trigger) return true;
49916
+ const typed = String(trigger.query || "").toLowerCase();
49917
+ return typed === String(command.name || "").toLowerCase() || typed === String(command.invokeName || "").toLowerCase();
49918
+ }
49919
+
49920
+ function shouldAcceptSuggestionFromEnter(event) {
49921
+ if (event.key !== "Enter" || event.shiftKey || event.ctrlKey || event.metaKey || event.altKey || event.isComposing) return false;
49922
+ if (elements.commandSuggest.hidden || activeSuggestionCount() === 0) return false;
49923
+ return !highlightedSuggestionAlreadyTyped();
49924
+ }
48370
49925
 
48371
49926
  elements.promptInput.addEventListener("keydown", (event) => {
48372
49927
  if (event.defaultPrevented || insertNumpadDecimal(event)) return;
49928
+ if (shouldAcceptSuggestionFromEnter(event)) {
49929
+ event.preventDefault();
49930
+ insertCommandSuggestion();
49931
+ return;
49932
+ }
48373
49933
  if (shouldSendPromptFromEnter(event)) {
48374
49934
  event.preventDefault();
48375
49935
  hideCommandSuggestions();
@@ -48378,12 +49938,12 @@ elements.promptInput.addEventListener("keydown", (event) => {
48378
49938
  }
48379
49939
 
48380
49940
  if (!elements.commandSuggest.hidden) {
48381
- if (event.key === "ArrowDown") {
49941
+ if (event.key === "ArrowDown" && activeSuggestionCount() > 0) {
48382
49942
  event.preventDefault();
48383
49943
  setActiveCommandSuggestion(commandSuggestIndex + 1);
48384
49944
  return;
48385
49945
  }
48386
- if (event.key === "ArrowUp") {
49946
+ if (event.key === "ArrowUp" && activeSuggestionCount() > 0) {
48387
49947
  event.preventDefault();
48388
49948
  setActiveCommandSuggestion(commandSuggestIndex - 1);
48389
49949
  return;
@@ -48410,7 +49970,8 @@ elements.promptInput.addEventListener("keydown", (event) => {
48410
49970
 
48411
49971
  elements.promptInput.addEventListener("input", () => {
48412
49972
  resetPromptHistoryNavigation();
48413
- if (moveLongPromptInputToAttachment()) return;
49973
+ // Typed text always stays editable in the composer; only large pastes become attachments
49974
+ // (handleAttachmentPaste). Ripping a prompt out mid-typing was surprising and lossy.
48414
49975
  resizePromptInput();
48415
49976
  renderCommandSuggestions();
48416
49977
  scheduleMobileContinuityPersist();