@firstpick/pi-package-webui 0.9.5 → 0.9.7
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.
- package/README.md +11 -5
- package/bin/pi-webui.mjs +457 -77
- package/lib/git-workflow-preferences.mjs +21 -1
- package/lib/optional-feature-catalog.mjs +1 -1
- package/lib/session-actions.mjs +20 -2
- package/lib/session-tree-event-targets.mjs +70 -0
- package/lib/subagent-launch-policy.mjs +375 -0
- package/lib/subagent-launch-slots.mjs +2 -1
- package/package.json +1 -1
- package/public/app.js +2539 -292
- package/public/index.html +87 -31
- package/public/service-worker.js +4 -1
- package/public/stream-derived-output.mjs +799 -0
- package/public/stream-markdown-tail.mjs +204 -0
- package/public/stream-output-controller.mjs +193 -51
- package/public/stream-render-scheduler.mjs +85 -0
- package/public/styles.css +501 -19
- package/public/transcript-renderer.mjs +73 -24
- package/tests/boot-failure-diagnostics.test.mjs +3 -3
- package/tests/browser/composer-action-grid-reorder.spec.mjs +114 -31
- package/tests/browser/control-visibility.spec.mjs +141 -2
- package/tests/browser/events-tree-context-menu.spec.mjs +240 -0
- package/tests/browser/guided-git-fallback.spec.mjs +153 -0
- package/tests/browser/mobile-foundation.spec.mjs +28 -0
- package/tests/browser/stream-output-isolation.spec.mjs +308 -3
- package/tests/browser/user-noticeable-fixes.spec.mjs +204 -0
- package/tests/codex-fast-mode-static.test.mjs +2 -2
- package/tests/compact-sections-static.test.mjs +4 -0
- package/tests/composer-action-grid-reorder-static.test.mjs +8 -7
- package/tests/control-visibility-static.test.mjs +66 -3
- package/tests/controls-layout-static.test.mjs +3 -3
- package/tests/cwd-footer-reliability-static.test.mjs +1 -1
- package/tests/events-tree-context-menu-static.test.mjs +131 -0
- package/tests/fast-mode-client-static.test.mjs +5 -2
- package/tests/feature-decision-output-popup-static.test.mjs +2 -2
- package/tests/file-viewer-image-static.test.mjs +3 -3
- package/tests/fixtures/fake-pi.mjs +57 -10
- package/tests/fixtures/streaming-workloads.mjs +36 -0
- package/tests/footer-provider-usage-visual-static.test.mjs +15 -0
- package/tests/foreground-transcript-catch-up-static.test.mjs +7 -1
- package/tests/git-workflow-preferences.test.mjs +30 -1
- package/tests/guided-git-fallback-runtime.test.mjs +418 -0
- package/tests/guided-git-fallback-ui-static.test.mjs +60 -0
- package/tests/guided-git-message-reliability-static.test.mjs +8 -7
- package/tests/interaction-state-stability-static.test.mjs +3 -1
- package/tests/intercom-conversation-viewer-static.test.mjs +3 -3
- package/tests/intercom-conversations-http.test.mjs +16 -0
- package/tests/main-output-loading-static.test.mjs +3 -3
- package/tests/middle-button-drag-scroll-static.test.mjs +3 -3
- package/tests/mobile-continuity-tablet-static.test.mjs +3 -3
- package/tests/mobile-foundation-static.test.mjs +3 -3
- package/tests/mobile-phone-experience-static.test.mjs +1 -1
- package/tests/mobile-static.test.mjs +80 -67
- package/tests/open-issue-wizard-static.test.mjs +1 -1
- package/tests/persistent-ui-layout-static.test.mjs +4 -4
- package/tests/prompt-input-vertical-scroll-static.test.mjs +26 -0
- package/tests/questionnaire-dialog.test.mjs +3 -3
- package/tests/remote-auth-settings-harness.test.mjs +23 -0
- package/tests/resource-defaults-helper.test.mjs +12 -0
- package/tests/runtime-error-visibility.test.mjs +3 -3
- package/tests/session-auth-harness.test.mjs +26 -1
- package/tests/session-sampling-helper.test.mjs +1 -0
- package/tests/session-sampling-ui-static.test.mjs +3 -3
- package/tests/session-tree-event-targets.test.mjs +106 -0
- package/tests/side-panel-section-height-removal-static.test.mjs +3 -3
- package/tests/stream-derived-output.test.mjs +121 -0
- package/tests/stream-markdown-tail.test.mjs +218 -0
- package/tests/stream-output-controller.test.mjs +119 -4
- package/tests/stream-output-isolation-static.test.mjs +27 -6
- package/tests/stream-output-workloads.test.mjs +40 -3
- package/tests/stream-render-scheduler.test.mjs +115 -0
- package/tests/streaming-ui-coupling.test.mjs +1 -1
- package/tests/subagent-launch-policy.test.mjs +532 -0
- package/tests/subagent-observability-static.test.mjs +2 -2
- package/tests/subagents-helper.test.mjs +211 -1
- package/tests/syntax-highlighting-static.test.mjs +3 -3
- package/tests/tab-close-continuity-static.test.mjs +23 -0
- package/tests/theme-customizer-static.test.mjs +1 -1
- package/tests/thinking-format-parser.test.mjs +15 -0
- package/tests/todo-filter-static.test.mjs +148 -0
- package/tests/transcript-markdown-tail.test.mjs +137 -0
- package/webui-rpc-helper.mjs +220 -3
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"),
|
|
@@ -352,6 +358,14 @@ const elements = {
|
|
|
352
358
|
sidePanelContextMenu: $("#sidePanelContextMenu"),
|
|
353
359
|
visibilityContextMenu: $("#visibilityContextMenu"),
|
|
354
360
|
gitFooterContextMenu: $("#gitFooterContextMenu"),
|
|
361
|
+
eventTreeContextMenu: $("#eventTreeContextMenu"),
|
|
362
|
+
eventFilterSelect: $("#eventFilterSelect"),
|
|
363
|
+
eventFilterStatus: $("#eventFilterStatus"),
|
|
364
|
+
eventFilterEmpty: $("#eventFilterEmpty"),
|
|
365
|
+
eventDisplayDetailedAction: $("#eventDisplayDetailedAction"),
|
|
366
|
+
eventDisplayCompactAction: $("#eventDisplayCompactAction"),
|
|
367
|
+
eventTreeContextMenuAction: $("#eventTreeContextMenuAction"),
|
|
368
|
+
eventTreeContextMenuStatus: $("#eventTreeContextMenuStatus"),
|
|
355
369
|
sidePanelResizeHandle: $("#sidePanelResizeHandle"),
|
|
356
370
|
sidePanelResizeHandleLeft: $("#sidePanelLeftResizeHandle"),
|
|
357
371
|
sidePanelLeftExpandButton: $("#sidePanelLeftExpandButton"),
|
|
@@ -459,6 +473,13 @@ const elements = {
|
|
|
459
473
|
undoToastButton: $("#undoToastButton"),
|
|
460
474
|
undoToastDismissButton: $("#undoToastDismissButton"),
|
|
461
475
|
confirmationDialog: $("#confirmationDialog"),
|
|
476
|
+
textPromptDialog: $("#textPromptDialog"),
|
|
477
|
+
textPromptTitle: $("#textPromptTitle"),
|
|
478
|
+
textPromptSummary: $("#textPromptSummary"),
|
|
479
|
+
textPromptInput: $("#textPromptInput"),
|
|
480
|
+
textPromptError: $("#textPromptError"),
|
|
481
|
+
textPromptCancelButton: $("#textPromptCancelButton"),
|
|
482
|
+
textPromptConfirmButton: $("#textPromptConfirmButton"),
|
|
462
483
|
confirmationTitle: $("#confirmationTitle"),
|
|
463
484
|
confirmationSummary: $("#confirmationSummary"),
|
|
464
485
|
confirmationAffected: $("#confirmationAffected"),
|
|
@@ -553,6 +574,12 @@ const elements = {
|
|
|
553
574
|
appRunnerInfoDialog: $("#appRunnerInfoDialog"),
|
|
554
575
|
appRunnerInfoBody: $("#appRunnerInfoBody"),
|
|
555
576
|
appRunnerInfoCloseButton: $("#appRunnerInfoCloseButton"),
|
|
577
|
+
controlVisibilitySetupDialog: $("#controlVisibilitySetupDialog"),
|
|
578
|
+
controlVisibilitySetupBody: $("#controlVisibilitySetupBody"),
|
|
579
|
+
controlVisibilitySetupStatus: $("#controlVisibilitySetupStatus"),
|
|
580
|
+
controlVisibilitySetupShowAllButton: $("#controlVisibilitySetupShowAllButton"),
|
|
581
|
+
controlVisibilitySetupResetButton: $("#controlVisibilitySetupResetButton"),
|
|
582
|
+
controlVisibilitySetupCloseButton: $("#controlVisibilitySetupCloseButton"),
|
|
556
583
|
gitFooterVisibilityDialog: $("#gitFooterVisibilityDialog"),
|
|
557
584
|
gitFooterVisibilityBody: $("#gitFooterVisibilityBody"),
|
|
558
585
|
gitFooterVisibilityStatus: $("#gitFooterVisibilityStatus"),
|
|
@@ -580,6 +607,9 @@ const transcriptRenderer = createTranscriptRenderer({
|
|
|
580
607
|
});
|
|
581
608
|
|
|
582
609
|
const PI_WEBUI_NPM_URL = "https://www.npmjs.com/package/@firstpick/pi-package-webui";
|
|
610
|
+
const EVENT_DISPLAY_MODE_STORAGE_KEY = "pi-webui-event-display-mode-v1";
|
|
611
|
+
const EVENT_FILTER_STORAGE_KEY = "pi-webui-event-filter-v1";
|
|
612
|
+
const EVENT_FILTER_VALUES = new Set(["all", "errors", "warnings", "tools", "tree"]);
|
|
583
613
|
|
|
584
614
|
let currentState = null;
|
|
585
615
|
let tabStateCache = new Map();
|
|
@@ -613,6 +643,10 @@ let fileViewerSearchTimer = null;
|
|
|
613
643
|
let fileContextMenuState = null;
|
|
614
644
|
let sidePanelContextMenuState = null;
|
|
615
645
|
let gitFooterContextMenuState = null;
|
|
646
|
+
let eventTreeContextMenuState = null;
|
|
647
|
+
let eventDisplayMode = readStoredEventDisplayMode();
|
|
648
|
+
let eventFilter = readStoredEventFilter();
|
|
649
|
+
const toolEventStartedAt = new Map();
|
|
616
650
|
let sidePanelSectionEditMode = false;
|
|
617
651
|
let sidePanelSectionPointerDrag = null;
|
|
618
652
|
let sidePanelSectionLastDragOverKey = "";
|
|
@@ -637,9 +671,18 @@ const promptRoutingTabs = new Set();
|
|
|
637
671
|
let tabSeenCompletionSerials = new Map();
|
|
638
672
|
let streamBubble = null;
|
|
639
673
|
let streamText = null;
|
|
674
|
+
// Controls-panel Model / Thinking selections the user has made but not applied yet. While set,
|
|
675
|
+
// status refreshes must not snap the selects back to the live value.
|
|
676
|
+
let controlsPendingModelValue = "";
|
|
677
|
+
let controlsPendingThinkingValue = "";
|
|
678
|
+
const PATH_SUGGEST_DEBOUNCE_MS = 120;
|
|
679
|
+
const NOTICE_TOAST_LIMIT = 3;
|
|
680
|
+
const NOTICE_TOAST_TIMEOUT_MS = { info: 5000, success: 5000, warn: 6000, error: 10000 };
|
|
681
|
+
const noticeToasts = [];
|
|
682
|
+
let eventsUnreadCount = 0;
|
|
640
683
|
let streamRawText = "";
|
|
641
684
|
let streamThinkingRawText = "";
|
|
642
|
-
let
|
|
685
|
+
let streamDerivedOutputState = null;
|
|
643
686
|
let streamBubbleVisibleSince = 0;
|
|
644
687
|
let streamBubbleHideTimer = null;
|
|
645
688
|
let streamToolCallSeen = false;
|
|
@@ -700,6 +743,10 @@ const streamIsolationDebugLedger = STREAM_ISOLATION_DEBUG_ENABLED ? {
|
|
|
700
743
|
longAnimationFrames: 0,
|
|
701
744
|
focusLossNearStreamBatch: 0,
|
|
702
745
|
detachedScrollMoves: 0,
|
|
746
|
+
renderSchedulerFlushes: 0,
|
|
747
|
+
renderSchedulerDefers: 0,
|
|
748
|
+
pressureDeferred: 0,
|
|
749
|
+
pressureSynchronousFallbacks: 0,
|
|
703
750
|
},
|
|
704
751
|
lastBatchAppliedAt: 0,
|
|
705
752
|
lastChatScrollTop: undefined,
|
|
@@ -746,6 +793,12 @@ function recordStreamIsolationDiagnostic(record) {
|
|
|
746
793
|
counters.overflows += 1;
|
|
747
794
|
} else if (record.type === "stale") {
|
|
748
795
|
counters.staleEvents += 1;
|
|
796
|
+
} else if (record.type === "render-scheduler") {
|
|
797
|
+
if (record.action === "flush") counters.renderSchedulerFlushes += 1;
|
|
798
|
+
else if (record.action === "defer") counters.renderSchedulerDefers += 1;
|
|
799
|
+
} else if (record.type === "pressure") {
|
|
800
|
+
if (record.action === "deferred") counters.pressureDeferred += 1;
|
|
801
|
+
else if (record.action === "synchronous-fallback") counters.pressureSynchronousFallbacks += 1;
|
|
749
802
|
}
|
|
750
803
|
if (record.type === "queued") {
|
|
751
804
|
counters.highWaterPendingCount = Math.max(counters.highWaterPendingCount, Number(record.pendingCount) || 0);
|
|
@@ -873,6 +926,54 @@ if (streamIsolationDebugLedger) {
|
|
|
873
926
|
}, true);
|
|
874
927
|
}
|
|
875
928
|
|
|
929
|
+
let normalStreamFollowPending = false;
|
|
930
|
+
const normalStreamSchedulerDiagnostic = streamIsolationDebugLedger ? recordStreamIsolationDiagnostic : undefined;
|
|
931
|
+
const assistantStreamRenderScheduler = createLatestWinsRenderScheduler({
|
|
932
|
+
render: (options) => {
|
|
933
|
+
renderStreamingAssistantText(options);
|
|
934
|
+
completeNormalStreamScheduledRender();
|
|
935
|
+
},
|
|
936
|
+
onDiagnostic: normalStreamSchedulerDiagnostic,
|
|
937
|
+
});
|
|
938
|
+
const thinkingStreamRenderScheduler = createLatestWinsRenderScheduler({
|
|
939
|
+
render: (options = {}) => {
|
|
940
|
+
if (streamThinkingRawText) setStreamingThinkingText(streamThinkingRawText, options);
|
|
941
|
+
if (options.complete) streamThinkingBubble?.classList.add("complete");
|
|
942
|
+
completeNormalStreamScheduledRender();
|
|
943
|
+
},
|
|
944
|
+
onDiagnostic: normalStreamSchedulerDiagnostic,
|
|
945
|
+
});
|
|
946
|
+
|
|
947
|
+
function normalStreamRenderPending() {
|
|
948
|
+
return assistantStreamRenderScheduler.pending() || thinkingStreamRenderScheduler.pending();
|
|
949
|
+
}
|
|
950
|
+
|
|
951
|
+
function completeNormalStreamScheduledRender() {
|
|
952
|
+
if (!normalStreamFollowPending || normalStreamRenderPending()) return;
|
|
953
|
+
normalStreamFollowPending = false;
|
|
954
|
+
scheduleChatFollowScroll();
|
|
955
|
+
}
|
|
956
|
+
|
|
957
|
+
function requestNormalStreamFollowAfterRender() {
|
|
958
|
+
if (normalStreamRenderPending()) {
|
|
959
|
+
normalStreamFollowPending = true;
|
|
960
|
+
return;
|
|
961
|
+
}
|
|
962
|
+
scheduleChatFollowScroll();
|
|
963
|
+
}
|
|
964
|
+
|
|
965
|
+
function flushNormalStreamRenders(reason = "semantic") {
|
|
966
|
+
assistantStreamRenderScheduler.flushNow(reason);
|
|
967
|
+
thinkingStreamRenderScheduler.flushNow(reason);
|
|
968
|
+
completeNormalStreamScheduledRender();
|
|
969
|
+
}
|
|
970
|
+
|
|
971
|
+
function cancelNormalStreamRenders() {
|
|
972
|
+
assistantStreamRenderScheduler.cancel();
|
|
973
|
+
thinkingStreamRenderScheduler.cancel();
|
|
974
|
+
normalStreamFollowPending = false;
|
|
975
|
+
}
|
|
976
|
+
|
|
876
977
|
const streamOutputController = createStreamOutputController({
|
|
877
978
|
isOwnerCurrent: (owner) => owner === transcriptStreamOwner(),
|
|
878
979
|
applyTextUpdate: (event) => handleMessageUpdate(event),
|
|
@@ -892,7 +993,7 @@ const streamOutputController = createStreamOutputController({
|
|
|
892
993
|
applyStreamError: (event) => handleMessageUpdate(event),
|
|
893
994
|
applyFollowScroll: () => {
|
|
894
995
|
if (compactOutputActive()) flushCompactLiveOutput();
|
|
895
|
-
|
|
996
|
+
else requestNormalStreamFollowAfterRender();
|
|
896
997
|
},
|
|
897
998
|
onUnknownStreamEvent: preserveUnknownTranscriptEvidence,
|
|
898
999
|
onDiagnostic: streamIsolationDebugLedger ? recordStreamIsolationDiagnostic : undefined,
|
|
@@ -901,6 +1002,7 @@ let assistantErrorSurfacedThisRun = false;
|
|
|
901
1002
|
let runIndicatorBubble = null;
|
|
902
1003
|
let runIndicatorText = null;
|
|
903
1004
|
let runIndicatorMeta = null;
|
|
1005
|
+
let runIndicatorElapsed = null;
|
|
904
1006
|
let runIndicatorTimer = null;
|
|
905
1007
|
let runIndicatorRenderFrame = null;
|
|
906
1008
|
let runIndicatorRenderScroll = false;
|
|
@@ -953,6 +1055,7 @@ const supervisorEventCursors = new Map();
|
|
|
953
1055
|
const supervisorRetiredEpochs = new Map();
|
|
954
1056
|
const supervisorGapWarnings = new Set();
|
|
955
1057
|
const supervisorContinuityRefreshes = new Map();
|
|
1058
|
+
const closingTerminalTabIds = new Set();
|
|
956
1059
|
const supervisorEnvelopeWarnings = new Set();
|
|
957
1060
|
let activeDialog = null;
|
|
958
1061
|
let activeDialogCancel = null;
|
|
@@ -1451,7 +1554,9 @@ const UPDATE_STATUS_INITIAL_DELAY_MS = 1800;
|
|
|
1451
1554
|
const RUN_INDICATOR_TICK_MS = 1000;
|
|
1452
1555
|
const RUN_INDICATOR_START_GRACE_MS = 2500;
|
|
1453
1556
|
const RUN_INDICATOR_STATE_RECHECK_MS = 5000;
|
|
1454
|
-
const ABORT_LONG_PRESS_MS =
|
|
1557
|
+
const ABORT_LONG_PRESS_MS = 1200;
|
|
1558
|
+
const ABORT_TAP_HINT_MS = 1800;
|
|
1559
|
+
let abortTapHintTimer = null;
|
|
1455
1560
|
const ABORT_LONG_PRESS_TICK_MS = 100;
|
|
1456
1561
|
const ABORT_LONG_PRESS_RELEASE_GRACE_MS = 350;
|
|
1457
1562
|
const EMPTY_PROMPT_ESCAPE_AFTER_ABORT_GRACE_MS = 1000;
|
|
@@ -1624,6 +1729,55 @@ function persistMobileContinuityState() {
|
|
|
1624
1729
|
function scheduleMobileContinuityPersist() {
|
|
1625
1730
|
clearTimeout(mobileContinuityPersistTimer);
|
|
1626
1731
|
mobileContinuityPersistTimer = setTimeout(persistMobileContinuityState, MOBILE_CONTINUITY_PERSIST_DEBOUNCE_MS);
|
|
1732
|
+
scheduleDesktopDraftPersist();
|
|
1733
|
+
}
|
|
1734
|
+
|
|
1735
|
+
// Desktop draft continuity: composer text per tab survives reloads and browser restarts (the
|
|
1736
|
+
// mobile v2 shell has its own richer continuity store; this covers everything else).
|
|
1737
|
+
const DESKTOP_DRAFT_STORAGE_KEY = "pi-webui-composer-drafts-v1";
|
|
1738
|
+
const DESKTOP_DRAFT_PERSIST_DEBOUNCE_MS = 500;
|
|
1739
|
+
const DESKTOP_DRAFT_MAX_TABS = 24;
|
|
1740
|
+
let desktopDraftPersistTimer = null;
|
|
1741
|
+
|
|
1742
|
+
function persistDesktopDrafts() {
|
|
1743
|
+
clearTimeout(desktopDraftPersistTimer);
|
|
1744
|
+
desktopDraftPersistTimer = null;
|
|
1745
|
+
if (isMobileShellV2Active()) return;
|
|
1746
|
+
if (activeTabId && elements.promptInput) tabDrafts.set(activeTabId, elements.promptInput.value || "");
|
|
1747
|
+
const liveIds = new Set(tabs.map((tab) => tab.id));
|
|
1748
|
+
const drafts = {};
|
|
1749
|
+
let count = 0;
|
|
1750
|
+
for (const [tabId, draft] of tabDrafts) {
|
|
1751
|
+
if (!liveIds.has(tabId) || !draft || count >= DESKTOP_DRAFT_MAX_TABS) continue;
|
|
1752
|
+
drafts[tabId] = String(draft).slice(0, 200_000);
|
|
1753
|
+
count += 1;
|
|
1754
|
+
}
|
|
1755
|
+
try {
|
|
1756
|
+
if (count === 0) localStorage.removeItem(DESKTOP_DRAFT_STORAGE_KEY);
|
|
1757
|
+
else localStorage.setItem(DESKTOP_DRAFT_STORAGE_KEY, JSON.stringify({ v: 1, drafts, savedAt: Date.now() }));
|
|
1758
|
+
} catch {
|
|
1759
|
+
// Storage may be unavailable (private mode / quota); drafts then live for this page only.
|
|
1760
|
+
}
|
|
1761
|
+
}
|
|
1762
|
+
|
|
1763
|
+
function scheduleDesktopDraftPersist() {
|
|
1764
|
+
clearTimeout(desktopDraftPersistTimer);
|
|
1765
|
+
desktopDraftPersistTimer = setTimeout(persistDesktopDrafts, DESKTOP_DRAFT_PERSIST_DEBOUNCE_MS);
|
|
1766
|
+
}
|
|
1767
|
+
|
|
1768
|
+
function restoreDesktopDrafts() {
|
|
1769
|
+
if (isMobileShellV2Active()) return;
|
|
1770
|
+
let stored = null;
|
|
1771
|
+
try {
|
|
1772
|
+
stored = JSON.parse(localStorage.getItem(DESKTOP_DRAFT_STORAGE_KEY) || "null");
|
|
1773
|
+
} catch {
|
|
1774
|
+
stored = null;
|
|
1775
|
+
}
|
|
1776
|
+
if (!stored || stored.v !== 1 || !stored.drafts || typeof stored.drafts !== "object") return;
|
|
1777
|
+
const liveIds = new Set(tabs.map((tab) => tab.id));
|
|
1778
|
+
for (const [tabId, draft] of Object.entries(stored.drafts)) {
|
|
1779
|
+
if (liveIds.has(tabId) && !tabDrafts.get(tabId) && typeof draft === "string" && draft) tabDrafts.set(tabId, draft);
|
|
1780
|
+
}
|
|
1627
1781
|
}
|
|
1628
1782
|
|
|
1629
1783
|
function restoreMobileContinuityState() {
|
|
@@ -3384,6 +3538,12 @@ function createGitWorkflowState() {
|
|
|
3384
3538
|
...resetGitWorkflowManualCommitDefaultPatch(),
|
|
3385
3539
|
messageRequestedAt: 0,
|
|
3386
3540
|
messageGenerationId: "",
|
|
3541
|
+
generationId: "",
|
|
3542
|
+
generationKind: "",
|
|
3543
|
+
generationAccepted: false,
|
|
3544
|
+
fallbackStarted: false,
|
|
3545
|
+
fallbackLifecycleKeys: new Set(),
|
|
3546
|
+
pendingFallbackLifecycleEvents: [],
|
|
3387
3547
|
branchName: "",
|
|
3388
3548
|
branchNameRequestedAt: 0,
|
|
3389
3549
|
actionsDone: createGitWorkflowActionsDone(),
|
|
@@ -4177,7 +4337,6 @@ function moveSidePanelSectionRelative(fromId, targetRecord, insertBefore, target
|
|
|
4177
4337
|
|
|
4178
4338
|
function completeControlDeckSectionSideMove(record, side) {
|
|
4179
4339
|
if (!record) return;
|
|
4180
|
-
if (!record.section.classList.contains("collapsed")) setOnlySidePanelSectionExpanded(record);
|
|
4181
4340
|
const sideRecords = sidePanelSectionRecords()
|
|
4182
4341
|
.filter(({ id, section }) => !section.hidden && controlDeckSectionSide(id) === side)
|
|
4183
4342
|
.sort((a, b) => controlDeckLayout.sectionLayout.order.indexOf(a.id) - controlDeckLayout.sectionLayout.order.indexOf(b.id));
|
|
@@ -4369,6 +4528,8 @@ function setSidePanelSectionCollapsed(record, collapsed, { persist = true } = {}
|
|
|
4369
4528
|
record.content.hidden = collapsed;
|
|
4370
4529
|
record.button.setAttribute("aria-expanded", collapsed ? "false" : "true");
|
|
4371
4530
|
updateSidePanelSectionEditAffordance(record);
|
|
4531
|
+
if (!collapsed && record.id === "events") clearUnreadEvents();
|
|
4532
|
+
if (!collapsed && record.id === "subagents") queueMicrotask(() => revealSubagentLaunchSlotConfigIfDeferred());
|
|
4372
4533
|
if (!collapsed && record.id === "git" && !record.section.hidden) {
|
|
4373
4534
|
queueMicrotask(() => {
|
|
4374
4535
|
renderGitPanel();
|
|
@@ -4391,18 +4552,13 @@ function setOnlySidePanelSectionExpanded(targetRecord, { persist = true } = {})
|
|
|
4391
4552
|
if (persist) persistSidePanelSectionState();
|
|
4392
4553
|
}
|
|
4393
4554
|
|
|
4555
|
+
// Sections open and close independently (any number may be expanded at once); the persisted
|
|
4556
|
+
// collapsed set is honored as-is. With no stored state every section starts collapsed.
|
|
4394
4557
|
function restoreSidePanelSectionState() {
|
|
4395
4558
|
const records = sidePanelSectionRecords();
|
|
4396
4559
|
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
4560
|
for (const record of records) {
|
|
4405
|
-
setSidePanelSectionCollapsed(record,
|
|
4561
|
+
setSidePanelSectionCollapsed(record, collapsedIds ? collapsedIds.has(record.id) : true, { persist: false });
|
|
4406
4562
|
}
|
|
4407
4563
|
}
|
|
4408
4564
|
|
|
@@ -4425,6 +4581,7 @@ function showSidePanelContextMenu(event) {
|
|
|
4425
4581
|
closeFileContextMenu({ returnFocus: false });
|
|
4426
4582
|
closeGitPanelContextMenu({ returnFocus: false });
|
|
4427
4583
|
closeSidePanelContextMenu({ returnFocus: false });
|
|
4584
|
+
closeEventTreeContextMenu({ returnFocus: false });
|
|
4428
4585
|
|
|
4429
4586
|
const menu = elements.sidePanelContextMenu;
|
|
4430
4587
|
const eventTrigger = event.currentTarget;
|
|
@@ -4465,11 +4622,7 @@ function bindSidePanelSectionToggles() {
|
|
|
4465
4622
|
event.preventDefault();
|
|
4466
4623
|
return;
|
|
4467
4624
|
}
|
|
4468
|
-
|
|
4469
|
-
setOnlySidePanelSectionExpanded(record);
|
|
4470
|
-
} else {
|
|
4471
|
-
setSidePanelSectionCollapsed(record, true);
|
|
4472
|
-
}
|
|
4625
|
+
setSidePanelSectionCollapsed(record, !record.section.classList.contains("collapsed"));
|
|
4473
4626
|
});
|
|
4474
4627
|
record.button.addEventListener("keydown", (event) => {
|
|
4475
4628
|
if (!isSidePanelSectionReorderingEnabled() || !event.altKey || !["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight"].includes(event.key)) return;
|
|
@@ -4616,13 +4769,48 @@ function persistComposerActionSlotLayout() {
|
|
|
4616
4769
|
markDurableUiLayoutDirty("composerActions");
|
|
4617
4770
|
}
|
|
4618
4771
|
|
|
4619
|
-
function
|
|
4620
|
-
const
|
|
4621
|
-
const
|
|
4622
|
-
|
|
4623
|
-
const
|
|
4624
|
-
|
|
4625
|
-
|
|
4772
|
+
function projectComposerActionSlots(entries, sourceColumns, targetColumns) {
|
|
4773
|
+
const projected = new Map();
|
|
4774
|
+
const chunks = [];
|
|
4775
|
+
let chunk = [];
|
|
4776
|
+
const flushChunk = () => {
|
|
4777
|
+
if (chunk.length) chunks.push(chunk);
|
|
4778
|
+
chunk = [];
|
|
4779
|
+
};
|
|
4780
|
+
|
|
4781
|
+
for (const entry of entries) {
|
|
4782
|
+
const sourceRow = Math.floor(entry.storedSlot / sourceColumns);
|
|
4783
|
+
const sourceColumn = entry.storedSlot % sourceColumns;
|
|
4784
|
+
const sourceEnd = sourceColumn + entry.record.span;
|
|
4785
|
+
const first = chunk[0];
|
|
4786
|
+
const previous = chunk.at(-1);
|
|
4787
|
+
const continuesChunk = !!first
|
|
4788
|
+
&& first.sourceRow === sourceRow
|
|
4789
|
+
&& sourceColumn <= previous.sourceEnd + 1
|
|
4790
|
+
&& sourceEnd - first.sourceColumn <= targetColumns;
|
|
4791
|
+
if (chunk.length && !continuesChunk) flushChunk();
|
|
4792
|
+
chunk.push({ ...entry, sourceRow, sourceColumn, sourceEnd });
|
|
4793
|
+
}
|
|
4794
|
+
flushChunk();
|
|
4795
|
+
|
|
4796
|
+
let lastTargetRow = -1;
|
|
4797
|
+
let lastTargetEnd = 0;
|
|
4798
|
+
for (const entriesInChunk of chunks) {
|
|
4799
|
+
const sourceRow = entriesInChunk[0].sourceRow;
|
|
4800
|
+
const sourceStart = entriesInChunk[0].sourceColumn;
|
|
4801
|
+
const sourceEnd = Math.max(...entriesInChunk.map((entry) => entry.sourceEnd));
|
|
4802
|
+
const chunkWidth = sourceEnd - sourceStart;
|
|
4803
|
+
const targetStart = Math.max(0, Math.min(sourceStart, targetColumns - chunkWidth));
|
|
4804
|
+
let targetRow = Math.max(sourceRow, lastTargetRow);
|
|
4805
|
+
if (targetRow === lastTargetRow && targetStart < lastTargetEnd) targetRow += 1;
|
|
4806
|
+
for (const entry of entriesInChunk) {
|
|
4807
|
+
const targetColumn = targetStart + (entry.sourceColumn - sourceStart);
|
|
4808
|
+
projected.set(entry.id, targetRow * targetColumns + targetColumn);
|
|
4809
|
+
}
|
|
4810
|
+
lastTargetRow = targetRow;
|
|
4811
|
+
lastTargetEnd = targetStart + chunkWidth;
|
|
4812
|
+
}
|
|
4813
|
+
return projected;
|
|
4626
4814
|
}
|
|
4627
4815
|
|
|
4628
4816
|
function nearestAvailableComposerActionSlot(record, preferredSlot, layout, columns) {
|
|
@@ -4653,13 +4841,15 @@ function restoreComposerActionSlotLayout() {
|
|
|
4653
4841
|
return;
|
|
4654
4842
|
}
|
|
4655
4843
|
const records = new Map(composerActionRecords().map((record) => [record.id, record]));
|
|
4656
|
-
|
|
4657
|
-
|
|
4658
|
-
|
|
4659
|
-
|
|
4660
|
-
|
|
4661
|
-
|
|
4662
|
-
|
|
4844
|
+
const storedEntries = [...stored.positions]
|
|
4845
|
+
.sort((a, b) => a[1] - b[1])
|
|
4846
|
+
.map(([id, storedSlot]) => ({ id, storedSlot, record: records.get(id) }))
|
|
4847
|
+
.filter(({ record }) => record && !record.root.hidden && record.root.getClientRects().length);
|
|
4848
|
+
const projectedSlots = stored.columns === columns
|
|
4849
|
+
? new Map(storedEntries.map(({ id, storedSlot }) => [id, storedSlot]))
|
|
4850
|
+
: projectComposerActionSlots(storedEntries, stored.columns, columns);
|
|
4851
|
+
for (const { id, record } of storedEntries) {
|
|
4852
|
+
const slot = nearestAvailableComposerActionSlot(record, projectedSlots.get(id), composerActionSlotLayout, columns);
|
|
4663
4853
|
if (slot !== null) composerActionSlotLayout.set(id, slot);
|
|
4664
4854
|
}
|
|
4665
4855
|
applyComposerActionSlotLayout();
|
|
@@ -5497,7 +5687,7 @@ async function hydrateLoadedWorkspaceActiveTab(requestedTabId) {
|
|
|
5497
5687
|
|
|
5498
5688
|
async function saveWebuiWorkspace({ triggerButton = elements.workspaceSaveButton } = {}) {
|
|
5499
5689
|
if (!tabs.length) return;
|
|
5500
|
-
const promptedName =
|
|
5690
|
+
const promptedName = await appPromptText({ title: "Save workspace", summary: "Captures all open tabs, sessions, groups, and the active tab.", defaultValue: workspaceDefaultName(), confirmLabel: "Save workspace" });
|
|
5501
5691
|
if (promptedName === null) return;
|
|
5502
5692
|
const body = {
|
|
5503
5693
|
name: promptedName.trim() || workspaceDefaultName(),
|
|
@@ -6993,7 +7183,11 @@ function setSkillEditorStatus(message = "", level = "muted") {
|
|
|
6993
7183
|
status.hidden = !message;
|
|
6994
7184
|
}
|
|
6995
7185
|
|
|
6996
|
-
function closeSkillEditor() {
|
|
7186
|
+
async function closeSkillEditor({ force = false } = {}) {
|
|
7187
|
+
if (!force && activeSkillEditor?.dirty && elements.skillEditorDialog?.open) {
|
|
7188
|
+
if (!(await confirmDiscardEdits({ what: "unsaved skill edits", target: activeSkillEditor.path || activeSkillEditor.name || "SKILL.md" }))) return;
|
|
7189
|
+
activeSkillEditor.dirty = false;
|
|
7190
|
+
}
|
|
6997
7191
|
if (elements.skillEditorDialog?.open) elements.skillEditorDialog.close();
|
|
6998
7192
|
else activeSkillEditor = null;
|
|
6999
7193
|
}
|
|
@@ -7258,7 +7452,7 @@ function resizePromptInput() {
|
|
|
7258
7452
|
const maxHeight = Number.parseFloat(getComputedStyle(input).maxHeight);
|
|
7259
7453
|
const nextHeight = Number.isFinite(maxHeight) ? Math.min(input.scrollHeight, maxHeight) : input.scrollHeight;
|
|
7260
7454
|
input.style.height = `${Math.ceil(nextHeight)}px`;
|
|
7261
|
-
input.style.overflowY =
|
|
7455
|
+
input.style.overflowY = "auto";
|
|
7262
7456
|
}
|
|
7263
7457
|
|
|
7264
7458
|
function updateComposerModeButtons() {
|
|
@@ -7297,10 +7491,29 @@ function updateComposerModeButtons() {
|
|
|
7297
7491
|
if (elements.abortButton.getAttribute("aria-label") !== abortTitle) elements.abortButton.setAttribute("aria-label", abortTitle);
|
|
7298
7492
|
}
|
|
7299
7493
|
renderBusyPromptBehaviorTag();
|
|
7494
|
+
renderSendButtonMode(runActive);
|
|
7300
7495
|
document.body.classList.toggle("pi-run-active", runActive || abortAvailable);
|
|
7301
7496
|
scheduleComposerActionSlotLayoutRestore();
|
|
7302
7497
|
}
|
|
7303
7498
|
|
|
7499
|
+
// While Pi is running, Send does not start a new turn: it queues a follow-up or steers the active
|
|
7500
|
+
// run (per the busy-behavior tag). Say so on the button instead of silently acting differently.
|
|
7501
|
+
function renderSendButtonMode(runActive = isRunActive()) {
|
|
7502
|
+
const button = elements.sendButton;
|
|
7503
|
+
if (!button) return;
|
|
7504
|
+
const behavior = normalizeBusyPromptBehavior(busyPromptBehavior);
|
|
7505
|
+
const label = !runActive ? "Send" : behavior === "steer" ? "Steer" : "Queue";
|
|
7506
|
+
const title = !runActive
|
|
7507
|
+
? "Send prompt — Shift+F10 opens visibility options"
|
|
7508
|
+
: behavior === "steer"
|
|
7509
|
+
? "Pi is running: Enter steers the active run with this text. Change the behavior via the tag above the prompt."
|
|
7510
|
+
: "Pi is running: Enter queues this text as a follow-up. Change the behavior via the tag above the prompt.";
|
|
7511
|
+
if (button.textContent !== label) button.textContent = label;
|
|
7512
|
+
if (button.title !== title) button.title = title;
|
|
7513
|
+
button.setAttribute("aria-label", runActive ? `${label} (Send while Pi is running)` : "Send");
|
|
7514
|
+
button.classList.toggle("send-busy-mode", runActive);
|
|
7515
|
+
}
|
|
7516
|
+
|
|
7304
7517
|
function scheduleComposerModeButtonsUpdate() {
|
|
7305
7518
|
if (composerModeButtonsFrame !== null) return;
|
|
7306
7519
|
const flush = () => {
|
|
@@ -7554,6 +7767,72 @@ function appConfirm({ title = "Confirm action", summary = "Continue?", affected
|
|
|
7554
7767
|
});
|
|
7555
7768
|
}
|
|
7556
7769
|
|
|
7770
|
+
// Ask before an action would throw away unsaved edits. Resolves true when it is fine to proceed.
|
|
7771
|
+
function confirmDiscardEdits({ what = "unsaved edits", target = "" } = {}) {
|
|
7772
|
+
return appConfirm({
|
|
7773
|
+
title: `Discard ${what}?`,
|
|
7774
|
+
summary: target ? `${target} has changes that have not been saved.` : "There are changes that have not been saved.",
|
|
7775
|
+
affected: target || "The current editor contents",
|
|
7776
|
+
undoable: false,
|
|
7777
|
+
confirmLabel: "Discard changes",
|
|
7778
|
+
});
|
|
7779
|
+
}
|
|
7780
|
+
|
|
7781
|
+
// Application text prompt (replaces blocking window.prompt): resolves with the entered string,
|
|
7782
|
+
// or null when cancelled. `validate` may return an error message to keep the dialog open.
|
|
7783
|
+
let activeTextPromptResolve = null;
|
|
7784
|
+
|
|
7785
|
+
function appPromptText({ title = "Enter a value", summary = "", defaultValue = "", placeholder = "", confirmLabel = "OK", validate = null, selectRange = null } = {}) {
|
|
7786
|
+
const dialog = elements.textPromptDialog;
|
|
7787
|
+
if (!dialog?.showModal) {
|
|
7788
|
+
const value = window.prompt([title, summary].filter(Boolean).join("\n\n"), defaultValue);
|
|
7789
|
+
return Promise.resolve(value === null ? null : String(value));
|
|
7790
|
+
}
|
|
7791
|
+
if (activeTextPromptResolve) finishTextPrompt(null);
|
|
7792
|
+
elements.textPromptTitle.textContent = title;
|
|
7793
|
+
elements.textPromptSummary.textContent = summary;
|
|
7794
|
+
elements.textPromptSummary.hidden = !summary;
|
|
7795
|
+
elements.textPromptInput.value = defaultValue;
|
|
7796
|
+
elements.textPromptInput.placeholder = placeholder;
|
|
7797
|
+
elements.textPromptError.hidden = true;
|
|
7798
|
+
elements.textPromptError.textContent = "";
|
|
7799
|
+
elements.textPromptConfirmButton.textContent = confirmLabel;
|
|
7800
|
+
dialog.dataset.validate = validate ? "1" : "";
|
|
7801
|
+
textPromptValidator = typeof validate === "function" ? validate : null;
|
|
7802
|
+
return new Promise((resolve) => {
|
|
7803
|
+
activeTextPromptResolve = resolve;
|
|
7804
|
+
dialog.showModal();
|
|
7805
|
+
queueMicrotask(() => {
|
|
7806
|
+
const input = elements.textPromptInput;
|
|
7807
|
+
input.focus();
|
|
7808
|
+
if (Array.isArray(selectRange)) input.setSelectionRange(selectRange[0], selectRange[1]);
|
|
7809
|
+
else input.select();
|
|
7810
|
+
});
|
|
7811
|
+
});
|
|
7812
|
+
}
|
|
7813
|
+
|
|
7814
|
+
let textPromptValidator = null;
|
|
7815
|
+
|
|
7816
|
+
function finishTextPrompt(value) {
|
|
7817
|
+
const resolve = activeTextPromptResolve;
|
|
7818
|
+
activeTextPromptResolve = null;
|
|
7819
|
+
textPromptValidator = null;
|
|
7820
|
+
if (elements.textPromptDialog?.open) elements.textPromptDialog.close();
|
|
7821
|
+
resolve?.(value);
|
|
7822
|
+
}
|
|
7823
|
+
|
|
7824
|
+
function submitTextPrompt() {
|
|
7825
|
+
const value = String(elements.textPromptInput?.value ?? "");
|
|
7826
|
+
const problem = textPromptValidator ? textPromptValidator(value) : "";
|
|
7827
|
+
if (problem) {
|
|
7828
|
+
elements.textPromptError.textContent = String(problem);
|
|
7829
|
+
elements.textPromptError.hidden = false;
|
|
7830
|
+
elements.textPromptInput?.focus();
|
|
7831
|
+
return;
|
|
7832
|
+
}
|
|
7833
|
+
finishTextPrompt(value);
|
|
7834
|
+
}
|
|
7835
|
+
|
|
7557
7836
|
function appConfirmText(message, options = {}) {
|
|
7558
7837
|
const text = String(message || "Continue?").trim();
|
|
7559
7838
|
const [firstLine, ...rest] = text.split("\n");
|
|
@@ -8383,10 +8662,28 @@ function scopedApiPath(path, tabId = activeTabId) {
|
|
|
8383
8662
|
return `${url.pathname}${url.search}${url.hash}`;
|
|
8384
8663
|
}
|
|
8385
8664
|
|
|
8665
|
+
// Identical GET requests that overlap in time (boot fans out several refresh paths that ask for
|
|
8666
|
+
// the same catalogs) share one in-flight fetch. Callers still get their own resolved value.
|
|
8667
|
+
const inFlightGetRequests = new Map();
|
|
8668
|
+
|
|
8386
8669
|
async function api(path, { method = "GET", body, tabId = activeTabId, scoped = true, signal } = {}) {
|
|
8670
|
+
const url = scoped ? scopedApiPath(path, tabId) : path;
|
|
8671
|
+
if (method === "GET" && !signal) {
|
|
8672
|
+
const pending = inFlightGetRequests.get(url);
|
|
8673
|
+
if (pending) return pending;
|
|
8674
|
+
const request = apiUncached(url, { method, body, signal }).finally(() => {
|
|
8675
|
+
if (inFlightGetRequests.get(url) === request) inFlightGetRequests.delete(url);
|
|
8676
|
+
});
|
|
8677
|
+
inFlightGetRequests.set(url, request);
|
|
8678
|
+
return request;
|
|
8679
|
+
}
|
|
8680
|
+
return apiUncached(url, { method, body, signal });
|
|
8681
|
+
}
|
|
8682
|
+
|
|
8683
|
+
async function apiUncached(url, { method = "GET", body, signal } = {}) {
|
|
8387
8684
|
let response;
|
|
8388
8685
|
try {
|
|
8389
|
-
response = await fetch(
|
|
8686
|
+
response = await fetch(url, {
|
|
8390
8687
|
method,
|
|
8391
8688
|
headers: body === undefined ? undefined : { "content-type": "application/json" },
|
|
8392
8689
|
body: body === undefined ? undefined : JSON.stringify(body),
|
|
@@ -9130,7 +9427,22 @@ function renderAttachmentTray() {
|
|
|
9130
9427
|
const pill = make("span", "attachment-pill");
|
|
9131
9428
|
pill.title = attachment.requiresReselect ? `${attachment.name}\nReselect required; only metadata was restored.` : `${attachment.name}\n${attachment.mimeType}\n${formatBytes(attachment.size)}`;
|
|
9132
9429
|
pill.classList.toggle("requires-reselect", attachment.requiresReselect === true);
|
|
9133
|
-
|
|
9430
|
+
let icon = make("span", "attachment-pill-icon", attachmentIcon(attachment.kind));
|
|
9431
|
+
if (attachment.kind === "image" && attachment.previewUrl) {
|
|
9432
|
+
// Show the actual picture so a pasted screenshot can be checked at a glance.
|
|
9433
|
+
const thumb = make("img", "attachment-pill-thumb");
|
|
9434
|
+
thumb.src = attachment.previewUrl;
|
|
9435
|
+
thumb.alt = "";
|
|
9436
|
+
thumb.decoding = "async";
|
|
9437
|
+
thumb.loading = "lazy";
|
|
9438
|
+
const thumbButton = make("button", "attachment-pill-thumb-button");
|
|
9439
|
+
thumbButton.type = "button";
|
|
9440
|
+
thumbButton.title = `Preview ${attachment.name}`;
|
|
9441
|
+
thumbButton.setAttribute("aria-label", `Preview ${attachment.name}`);
|
|
9442
|
+
thumbButton.append(thumb);
|
|
9443
|
+
thumbButton.addEventListener("click", () => openImageLightbox(attachment.previewUrl, attachment.name));
|
|
9444
|
+
icon = thumbButton;
|
|
9445
|
+
}
|
|
9134
9446
|
const name = make("span", "attachment-pill-name", attachment.name);
|
|
9135
9447
|
const meta = make("span", "attachment-pill-meta", attachment.requiresReselect ? `${attachment.kind} · ${formatBytes(attachment.size)} · Reselect required` : `${attachment.kind} · ${formatBytes(attachment.size)}`);
|
|
9136
9448
|
const edit = !attachment.requiresReselect && isEditableTextAttachment(attachment) ? make("button", "attachment-edit-button", "Edit") : null;
|
|
@@ -9163,7 +9475,7 @@ function removeAttachment(id, tabId = activeTabId) {
|
|
|
9163
9475
|
if (index === -1) return;
|
|
9164
9476
|
const [removed] = attachments.splice(index, 1);
|
|
9165
9477
|
if (removed?.previewUrl) URL.revokeObjectURL(removed.previewUrl);
|
|
9166
|
-
if (activeTextAttachmentEditor?.tabId === tabId && activeTextAttachmentEditor?.attachmentId === id) closeTextAttachmentEditor();
|
|
9478
|
+
if (activeTextAttachmentEditor?.tabId === tabId && activeTextAttachmentEditor?.attachmentId === id) closeTextAttachmentEditor({ force: true });
|
|
9167
9479
|
if (attachments.length === 0) tabAttachments.delete(tabId);
|
|
9168
9480
|
if (tabId === activeTabId) renderAttachmentTray();
|
|
9169
9481
|
persistMobileContinuityState();
|
|
@@ -9174,7 +9486,7 @@ function clearAttachments(tabId = activeTabId) {
|
|
|
9174
9486
|
for (const attachment of attachments) {
|
|
9175
9487
|
if (attachment.previewUrl) URL.revokeObjectURL(attachment.previewUrl);
|
|
9176
9488
|
}
|
|
9177
|
-
if (activeTextAttachmentEditor?.tabId === tabId) closeTextAttachmentEditor();
|
|
9489
|
+
if (activeTextAttachmentEditor?.tabId === tabId) closeTextAttachmentEditor({ force: true });
|
|
9178
9490
|
if (tabId) tabAttachments.delete(tabId);
|
|
9179
9491
|
if (tabId === activeTabId) renderAttachmentTray();
|
|
9180
9492
|
persistMobileContinuityState();
|
|
@@ -9237,20 +9549,15 @@ function attachLongTextAsFile(text, source = "input text") {
|
|
|
9237
9549
|
return result.added > 0;
|
|
9238
9550
|
}
|
|
9239
9551
|
|
|
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
9552
|
function attachmentById(tabId, id) {
|
|
9250
9553
|
return attachmentsForTab(tabId).find((attachment) => attachment.id === id) || null;
|
|
9251
9554
|
}
|
|
9252
9555
|
|
|
9253
|
-
function closeTextAttachmentEditor() {
|
|
9556
|
+
async function closeTextAttachmentEditor({ force = false } = {}) {
|
|
9557
|
+
if (!force && activeTextAttachmentEditor?.dirty && elements.attachmentTextDialog?.open) {
|
|
9558
|
+
if (!(await confirmDiscardEdits({ what: "unsaved attachment edits", target: "The attachment text" }))) return;
|
|
9559
|
+
activeTextAttachmentEditor.dirty = false;
|
|
9560
|
+
}
|
|
9254
9561
|
if (elements.attachmentTextDialog?.open) elements.attachmentTextDialog.close();
|
|
9255
9562
|
else activeTextAttachmentEditor = null;
|
|
9256
9563
|
}
|
|
@@ -9348,7 +9655,7 @@ function saveTextAttachmentEdit() {
|
|
|
9348
9655
|
attachment.previewUrl = undefined;
|
|
9349
9656
|
if (tabId === activeTabId) renderAttachmentTray();
|
|
9350
9657
|
addEvent(`updated text attachment ${attachment.name} (${formatBytes(attachment.size)})`, "info");
|
|
9351
|
-
closeTextAttachmentEditor();
|
|
9658
|
+
closeTextAttachmentEditor({ force: true });
|
|
9352
9659
|
}
|
|
9353
9660
|
|
|
9354
9661
|
function clipboardFiles(dataTransfer) {
|
|
@@ -12499,6 +12806,7 @@ function showFileContextMenu(event, entry) {
|
|
|
12499
12806
|
event.stopPropagation();
|
|
12500
12807
|
closeGitPanelContextMenu({ returnFocus: false });
|
|
12501
12808
|
closeSidePanelContextMenu({ returnFocus: false });
|
|
12809
|
+
closeEventTreeContextMenu({ returnFocus: false });
|
|
12502
12810
|
const path = normalizeFileTreePath(entry?.path || "");
|
|
12503
12811
|
fileContextMenuState = { entry: { ...entry, path }, trigger: event.currentTarget || document.activeElement };
|
|
12504
12812
|
const menu = elements.fileContextMenu;
|
|
@@ -12919,6 +13227,37 @@ async function moveFileTreeEntryToDestination(entry = {}, destinationPath = "",
|
|
|
12919
13227
|
}
|
|
12920
13228
|
}
|
|
12921
13229
|
|
|
13230
|
+
// "New file… / New folder…" for the Files panel. `entry` is the folder (or a file, whose parent
|
|
13231
|
+
// folder is used) the action was invoked on; the workspace root when invoked from the toolbar.
|
|
13232
|
+
async function createFileTreeEntry(entry = null, kind = "file") {
|
|
13233
|
+
const entryPath = normalizeFileTreePath(entry?.path || "");
|
|
13234
|
+
const parentPath = !entryPath ? "" : entry?.type === "directory" ? entryPath : entryPath.split("/").slice(0, -1).join("/");
|
|
13235
|
+
const label = kind === "directory" ? "folder" : "file";
|
|
13236
|
+
const name = await appPromptText({
|
|
13237
|
+
title: `New ${label}`,
|
|
13238
|
+
summary: `Created inside ${parentPath || "the workspace root"}. Use "/" to create it deeper (existing folders only).`,
|
|
13239
|
+
placeholder: kind === "directory" ? "folder-name" : "notes.md",
|
|
13240
|
+
confirmLabel: "Create",
|
|
13241
|
+
validate: (value) => {
|
|
13242
|
+
const text = String(value || "").trim();
|
|
13243
|
+
if (!text) return "A name is required.";
|
|
13244
|
+
if (text === "." || text === ".." || text.includes("\0")) return "That name is not allowed.";
|
|
13245
|
+
if (text.startsWith("/") || text.startsWith("..")) return "Use a path relative to this folder.";
|
|
13246
|
+
return "";
|
|
13247
|
+
},
|
|
13248
|
+
});
|
|
13249
|
+
if (name === null) return;
|
|
13250
|
+
const relative = normalizeFileTreePath([parentPath, String(name).trim()].filter(Boolean).join("/"));
|
|
13251
|
+
const tabContext = activeTabContext();
|
|
13252
|
+
const response = await api("/api/files/create", { method: "POST", body: { path: relative, type: kind }, tabId: tabContext.tabId });
|
|
13253
|
+
if (!isCurrentTabContext(tabContext)) return;
|
|
13254
|
+
const created = response.data || {};
|
|
13255
|
+
addEvent(`Created ${label} ${created.path || relative}.`, "success");
|
|
13256
|
+
if (parentPath) fileTreeState.expanded.add(parentPath);
|
|
13257
|
+
await refreshFileTreeLive(tabContext).catch(() => {});
|
|
13258
|
+
if (kind === "file") await openFileInViewer(created.path || relative);
|
|
13259
|
+
}
|
|
13260
|
+
|
|
12922
13261
|
async function moveFileTreeEntry(entry = fileContextMenuState?.entry) {
|
|
12923
13262
|
if (!entry) return;
|
|
12924
13263
|
const sourcePath = normalizeFileTreePath(entry.path || "");
|
|
@@ -12927,12 +13266,18 @@ async function moveFileTreeEntry(entry = fileContextMenuState?.entry) {
|
|
|
12927
13266
|
return;
|
|
12928
13267
|
}
|
|
12929
13268
|
const typeLabel = fileOperationTypeLabel(entry);
|
|
12930
|
-
const
|
|
12931
|
-
|
|
12932
|
-
|
|
12933
|
-
|
|
12934
|
-
`
|
|
12935
|
-
|
|
13269
|
+
const baseName = sourcePath.split("/").pop() || sourcePath;
|
|
13270
|
+
const nameStart = sourcePath.length - baseName.length;
|
|
13271
|
+
const dotIndex = baseName.lastIndexOf(".");
|
|
13272
|
+
const destinationInput = await appPromptText({
|
|
13273
|
+
title: `Move or rename ${typeLabel}`,
|
|
13274
|
+
summary: `${sourcePath} — enter a new name or a destination path inside the workspace. An existing folder receives the ${typeLabel} as a child.`,
|
|
13275
|
+
defaultValue: sourcePath,
|
|
13276
|
+
confirmLabel: "Move",
|
|
13277
|
+
// Pre-select the file name (without extension) so a plain rename is one keystroke away.
|
|
13278
|
+
selectRange: [nameStart, entry.type === "directory" || dotIndex <= 0 ? sourcePath.length : nameStart + dotIndex],
|
|
13279
|
+
validate: (value) => (String(value || "").trim() ? "" : "Destination path is required."),
|
|
13280
|
+
});
|
|
12936
13281
|
if (destinationInput === null) return;
|
|
12937
13282
|
const destinationPath = String(destinationInput || "").trim();
|
|
12938
13283
|
if (!destinationPath) {
|
|
@@ -13235,6 +13580,7 @@ function applyControlVisibility(hiddenIdsOverride) {
|
|
|
13235
13580
|
}
|
|
13236
13581
|
// Hiding composer actions leaves grid holes; repack/restore the saved layout.
|
|
13237
13582
|
if (composerChanged) scheduleComposerActionSlotLayoutRestore();
|
|
13583
|
+
refreshControlVisibilitySetupDialog();
|
|
13238
13584
|
}
|
|
13239
13585
|
|
|
13240
13586
|
function persistControlVisibilityHiddenIds(hiddenIds) {
|
|
@@ -13259,6 +13605,71 @@ function resetControlVisibilityDefaults() {
|
|
|
13259
13605
|
}
|
|
13260
13606
|
|
|
13261
13607
|
let visibilityContextMenuState = null;
|
|
13608
|
+
let controlVisibilitySetupFocusReturn = null;
|
|
13609
|
+
|
|
13610
|
+
function setControlVisibilitySetupStatus(message = "") {
|
|
13611
|
+
if (elements.controlVisibilitySetupStatus) elements.controlVisibilitySetupStatus.textContent = message;
|
|
13612
|
+
}
|
|
13613
|
+
|
|
13614
|
+
function renderControlVisibilitySetupDialog() {
|
|
13615
|
+
const body = elements.controlVisibilitySetupBody;
|
|
13616
|
+
if (!body) return;
|
|
13617
|
+
const groups = CONTROL_VISIBILITY_GROUP_LABELS.map(([groupId, groupLabel], groupIndex) => {
|
|
13618
|
+
const fieldset = make("fieldset", "control-visibility-setup-group");
|
|
13619
|
+
fieldset.append(make("legend", "control-visibility-setup-group-label", groupLabel));
|
|
13620
|
+
const grid = make("div", "control-visibility-setup-grid");
|
|
13621
|
+
for (const [entryIndex, entry] of CONTROL_VISIBILITY_CATALOG.filter((item) => item.group === groupId).entries()) {
|
|
13622
|
+
const label = make("label", "control-visibility-setup-toggle");
|
|
13623
|
+
const checkbox = document.createElement("input");
|
|
13624
|
+
checkbox.type = "checkbox";
|
|
13625
|
+
checkbox.id = `controlVisibilitySetupToggle-${groupIndex}-${entryIndex}`;
|
|
13626
|
+
checkbox.dataset.visibilitySetupId = entry.id;
|
|
13627
|
+
checkbox.setAttribute("aria-label", `Show ${entry.label}`);
|
|
13628
|
+
label.htmlFor = checkbox.id;
|
|
13629
|
+
label.append(checkbox, make("span", "control-visibility-setup-toggle-label", entry.label));
|
|
13630
|
+
grid.append(label);
|
|
13631
|
+
}
|
|
13632
|
+
fieldset.append(grid);
|
|
13633
|
+
return fieldset;
|
|
13634
|
+
});
|
|
13635
|
+
body.replaceChildren(...groups);
|
|
13636
|
+
}
|
|
13637
|
+
|
|
13638
|
+
function refreshControlVisibilitySetupDialog() {
|
|
13639
|
+
const dialog = elements.controlVisibilitySetupDialog;
|
|
13640
|
+
const body = elements.controlVisibilitySetupBody;
|
|
13641
|
+
if (!dialog?.open || !body) return;
|
|
13642
|
+
const hiddenSet = new Set(userControlHiddenIds());
|
|
13643
|
+
for (const checkbox of body.querySelectorAll("[data-visibility-setup-id]")) {
|
|
13644
|
+
checkbox.checked = !hiddenSet.has(checkbox.dataset.visibilitySetupId);
|
|
13645
|
+
}
|
|
13646
|
+
const visibleCount = CONTROL_VISIBILITY_CATALOG.filter((entry) => !hiddenSet.has(entry.id)).length;
|
|
13647
|
+
setControlVisibilitySetupStatus(`${visibleCount} of ${CONTROL_VISIBILITY_CATALOG.length} optional controls shown by preference.`);
|
|
13648
|
+
}
|
|
13649
|
+
|
|
13650
|
+
function openControlVisibilitySetupDialog(trigger = null) {
|
|
13651
|
+
const dialog = elements.controlVisibilitySetupDialog;
|
|
13652
|
+
if (!dialog) return;
|
|
13653
|
+
controlVisibilitySetupFocusReturn = trigger instanceof HTMLElement ? trigger : elements.promptInput;
|
|
13654
|
+
if (!elements.controlVisibilitySetupBody?.childElementCount) renderControlVisibilitySetupDialog();
|
|
13655
|
+
if (!dialog.open) dialog.showModal();
|
|
13656
|
+
refreshControlVisibilitySetupDialog();
|
|
13657
|
+
queueMicrotask(() => elements.controlVisibilitySetupBody?.querySelector("input")?.focus({ preventScroll: true }));
|
|
13658
|
+
}
|
|
13659
|
+
|
|
13660
|
+
function restoreControlVisibilitySetupFocus() {
|
|
13661
|
+
const trigger = controlVisibilitySetupFocusReturn;
|
|
13662
|
+
controlVisibilitySetupFocusReturn = null;
|
|
13663
|
+
const triggerSurvives = trigger
|
|
13664
|
+
&& trigger.isConnected
|
|
13665
|
+
&& !trigger.closest?.("[hidden], .webui-user-hidden")
|
|
13666
|
+
&& typeof trigger.focus === "function";
|
|
13667
|
+
requestAnimationFrame(() => {
|
|
13668
|
+
if (triggerSurvives) trigger.focus({ preventScroll: true });
|
|
13669
|
+
else elements.promptInput?.focus({ preventScroll: true });
|
|
13670
|
+
});
|
|
13671
|
+
}
|
|
13672
|
+
|
|
13262
13673
|
|
|
13263
13674
|
function closeVisibilityContextMenu({ returnFocus = true } = {}) {
|
|
13264
13675
|
const trigger = visibilityContextMenuState?.trigger;
|
|
@@ -13305,6 +13716,7 @@ function prepareControlVisibilityMenu(trigger, entryId = null) {
|
|
|
13305
13716
|
closeGitPanelContextMenu({ returnFocus: false });
|
|
13306
13717
|
closeSidePanelContextMenu({ returnFocus: false });
|
|
13307
13718
|
closeGitFooterContextMenu({ returnFocus: false });
|
|
13719
|
+
closeEventTreeContextMenu({ returnFocus: false });
|
|
13308
13720
|
closeVisibilityContextMenu({ returnFocus: false });
|
|
13309
13721
|
// Region hosts are plain non-focusable containers; storing one as the
|
|
13310
13722
|
// trigger would let Escape focus fall through to <body>. Fall back to the
|
|
@@ -13324,12 +13736,13 @@ function prepareControlVisibilityMenu(trigger, entryId = null) {
|
|
|
13324
13736
|
|
|
13325
13737
|
// Right-clicking a visible registered control offers Hide <label> plus the
|
|
13326
13738
|
// recovery actions; empty marked regions open the grouped full catalog.
|
|
13327
|
-
function showControlVisibilityDirectMenu(entry,
|
|
13328
|
-
const menu = prepareControlVisibilityMenu(
|
|
13739
|
+
function showControlVisibilityDirectMenu(entry, focusTrigger, { clientX, clientY }) {
|
|
13740
|
+
const menu = prepareControlVisibilityMenu(focusTrigger, entry.id);
|
|
13329
13741
|
if (!menu) return;
|
|
13330
13742
|
const items = [
|
|
13331
13743
|
controlVisibilityMenuLabel("Hide or restore controls"),
|
|
13332
13744
|
controlVisibilityMenuAction("hide", `Hide ${entry.label}`),
|
|
13745
|
+
controlVisibilityMenuAction("open-setup", "Open setup"),
|
|
13333
13746
|
controlVisibilityMenuAction("show-all", "Show all"),
|
|
13334
13747
|
controlVisibilityMenuAction("reset-defaults", "Reset defaults"),
|
|
13335
13748
|
];
|
|
@@ -13354,6 +13767,7 @@ function showControlVisibilityRegionMenu(trigger, { clientX, clientY }) {
|
|
|
13354
13767
|
children.push(button);
|
|
13355
13768
|
}
|
|
13356
13769
|
}
|
|
13770
|
+
children.push(controlVisibilityMenuAction("open-setup", "Open setup"));
|
|
13357
13771
|
children.push(controlVisibilityMenuAction("show-all", "Show all"));
|
|
13358
13772
|
children.push(controlVisibilityMenuAction("reset-defaults", "Reset defaults"));
|
|
13359
13773
|
menu.replaceChildren(...children);
|
|
@@ -13372,7 +13786,8 @@ function handleControlVisibilityContextMenu(event) {
|
|
|
13372
13786
|
if (entry) {
|
|
13373
13787
|
event.preventDefault();
|
|
13374
13788
|
event.stopPropagation();
|
|
13375
|
-
|
|
13789
|
+
const focusTrigger = target.closest?.("button, a, input, select, textarea, [tabindex]");
|
|
13790
|
+
showControlVisibilityDirectMenu(entry, focusTrigger, { clientX: event.clientX, clientY: event.clientY });
|
|
13376
13791
|
return;
|
|
13377
13792
|
}
|
|
13378
13793
|
if (target.closest?.("button, input, textarea, select, [contenteditable='true'], a")) return;
|
|
@@ -13401,8 +13816,10 @@ function handleControlVisibilityKeydown(event) {
|
|
|
13401
13816
|
const position = { clientX: rect.left + Math.min(rect.width, 24), clientY: rect.bottom };
|
|
13402
13817
|
event.preventDefault();
|
|
13403
13818
|
event.stopPropagation();
|
|
13404
|
-
if (entry)
|
|
13405
|
-
|
|
13819
|
+
if (entry) {
|
|
13820
|
+
const focusTrigger = target.closest?.("button, a, input, select, textarea, [tabindex]");
|
|
13821
|
+
showControlVisibilityDirectMenu(entry, focusTrigger, position);
|
|
13822
|
+
} else showControlVisibilityRegionMenu(anchor, position);
|
|
13406
13823
|
}
|
|
13407
13824
|
|
|
13408
13825
|
function initializeControlVisibility() {
|
|
@@ -14947,6 +15364,9 @@ async function applyGitFileChangesSnapshot(request, tabContext, viewerPath, requ
|
|
|
14947
15364
|
async function openFileInViewer(path = "", { gitCategory = "", gitPath = "" } = {}) {
|
|
14948
15365
|
const normalized = normalizeFileTreePath(path);
|
|
14949
15366
|
if (!normalized) return;
|
|
15367
|
+
if (activeFileViewer?.dirty && activeFileViewer.path !== normalized) {
|
|
15368
|
+
if (!(await confirmDiscardEdits({ what: "unsaved file edits", target: activeFileViewer.path }))) return;
|
|
15369
|
+
}
|
|
14950
15370
|
const openRequestSerial = ++fileViewerOpenRequestSerial;
|
|
14951
15371
|
const tabContext = activeTabContext();
|
|
14952
15372
|
fileTreeState.selectedPath = normalized;
|
|
@@ -15443,6 +15863,7 @@ function updateDocumentTitle() {
|
|
|
15443
15863
|
function saveActiveDraft() {
|
|
15444
15864
|
if (activeTabId) tabDrafts.set(activeTabId, elements.promptInput.value || "");
|
|
15445
15865
|
persistMobileContinuityState();
|
|
15866
|
+
persistDesktopDrafts();
|
|
15446
15867
|
}
|
|
15447
15868
|
|
|
15448
15869
|
function restoreActiveDraft() {
|
|
@@ -15603,6 +16024,8 @@ function resetActiveTabUi() {
|
|
|
15603
16024
|
clearRefreshTimers();
|
|
15604
16025
|
eventSource?.close();
|
|
15605
16026
|
eventSource = null;
|
|
16027
|
+
setControlsPendingModel("");
|
|
16028
|
+
setControlsPendingThinking("");
|
|
15606
16029
|
currentState = cachedStateForTabSwitch(activeTabId);
|
|
15607
16030
|
latestStats = activeTabId ? tabStatsCache.get(activeTabId) || null : null;
|
|
15608
16031
|
latestStatsOverlayPayload = null;
|
|
@@ -15641,6 +16064,8 @@ function resetActiveTabUi() {
|
|
|
15641
16064
|
bindGitWorkflowToActiveTab();
|
|
15642
16065
|
resetChatOutput();
|
|
15643
16066
|
elements.stateDetails.replaceChildren();
|
|
16067
|
+
closeEventTreeContextMenu({ returnFocus: false });
|
|
16068
|
+
toolEventStartedAt.clear();
|
|
15644
16069
|
elements.eventLog.replaceChildren();
|
|
15645
16070
|
const queuedSnapshot = activeTabId ? latestQueuedMessagesByTab.get(activeTabId) : null;
|
|
15646
16071
|
if (queuedSnapshot) renderQueue({ tabId: activeTabId, ...queuedSnapshot });
|
|
@@ -16014,6 +16439,7 @@ function showGitPanelContextMenu(event, context) {
|
|
|
16014
16439
|
closeFileContextMenu({ returnFocus: false });
|
|
16015
16440
|
closeGitPanelContextMenu({ returnFocus: false });
|
|
16016
16441
|
closeSidePanelContextMenu({ returnFocus: false });
|
|
16442
|
+
closeEventTreeContextMenu({ returnFocus: false });
|
|
16017
16443
|
const menu = elements.gitPanelContextMenu;
|
|
16018
16444
|
const items = gitPanelContextMenuItems(context);
|
|
16019
16445
|
if (!items.length) return;
|
|
@@ -16042,6 +16468,30 @@ function showGitPanelContextMenu(event, context) {
|
|
|
16042
16468
|
menu.querySelector('[role="menuitem"]:not([disabled])')?.focus({ preventScroll: true });
|
|
16043
16469
|
}
|
|
16044
16470
|
|
|
16471
|
+
// Touch- and keyboard-discoverable entry to the same actions as the right-click menu.
|
|
16472
|
+
function gitPanelOverflowButton(context, label) {
|
|
16473
|
+
const button = make("button", "git-side-panel-overflow-button file-tree-overflow-button", "⋯");
|
|
16474
|
+
button.type = "button";
|
|
16475
|
+
button.setAttribute("aria-label", `Git actions for ${label}`);
|
|
16476
|
+
button.setAttribute("aria-haspopup", "menu");
|
|
16477
|
+
button.title = "Git actions";
|
|
16478
|
+
button.addEventListener("click", (event) => {
|
|
16479
|
+
event.stopPropagation();
|
|
16480
|
+
const rect = button.getBoundingClientRect();
|
|
16481
|
+
showGitPanelContextMenu({
|
|
16482
|
+
preventDefault: () => event.preventDefault(),
|
|
16483
|
+
stopPropagation: () => event.stopPropagation(),
|
|
16484
|
+
clientX: rect.right,
|
|
16485
|
+
clientY: rect.bottom,
|
|
16486
|
+
currentTarget: button,
|
|
16487
|
+
}, context);
|
|
16488
|
+
});
|
|
16489
|
+
button.addEventListener("keydown", (event) => {
|
|
16490
|
+
if (event.key === "Enter" || event.key === " ") event.stopPropagation();
|
|
16491
|
+
});
|
|
16492
|
+
return button;
|
|
16493
|
+
}
|
|
16494
|
+
|
|
16045
16495
|
function bindGitPanelContextMenu(trigger, context) {
|
|
16046
16496
|
trigger.setAttribute("aria-haspopup", "menu");
|
|
16047
16497
|
trigger.addEventListener("contextmenu", (event) => showGitPanelContextMenu(event, context));
|
|
@@ -16149,7 +16599,7 @@ function renderGitPanelFile(entry, card, category) {
|
|
|
16149
16599
|
const row = make("div", `git-side-panel-file ${category}`);
|
|
16150
16600
|
row.dataset.gitPanelContinuityKey = `file:${card.root}:${category}:${entry.path}`;
|
|
16151
16601
|
const fullPath = entry.oldPath ? `${entry.oldPath} → ${entry.path}` : entry.path;
|
|
16152
|
-
row.title = `${fullPath} · Open in WebUI ·
|
|
16602
|
+
row.title = `${fullPath} · Open in WebUI · ⋯ or right-click for Git actions`;
|
|
16153
16603
|
row.tabIndex = 0;
|
|
16154
16604
|
row.setAttribute("role", "button");
|
|
16155
16605
|
row.setAttribute("aria-label", `Open ${entry.name || entry.path} in WebUI, ${gitPanelStatsText(entry, category) || "no line statistics"}`);
|
|
@@ -16166,8 +16616,9 @@ function renderGitPanelFile(entry, card, category) {
|
|
|
16166
16616
|
const statsText = gitPanelStatsText(entry, category);
|
|
16167
16617
|
const stats = make("span", "git-side-panel-file-stats", statsText);
|
|
16168
16618
|
stats.hidden = !statsText;
|
|
16169
|
-
|
|
16170
|
-
row
|
|
16619
|
+
const context = { card, category, kind: "file", path: entry.path };
|
|
16620
|
+
bindGitPanelContextMenu(row, context);
|
|
16621
|
+
row.append(status, name, stats, gitPanelOverflowButton(context, entry.name || entry.path));
|
|
16171
16622
|
return row;
|
|
16172
16623
|
}
|
|
16173
16624
|
|
|
@@ -16336,7 +16787,7 @@ function renderGitPanelRepositoryCard(card) {
|
|
|
16336
16787
|
button.type = "button";
|
|
16337
16788
|
button.dataset.gitPanelContinuityKey = `repository:${card.root}`;
|
|
16338
16789
|
button.setAttribute("aria-expanded", expanded ? "true" : "false");
|
|
16339
|
-
button.title = `${expanded ? "Collapse" : "Expand"} ${card.root} ·
|
|
16790
|
+
button.title = `${expanded ? "Collapse" : "Expand"} ${card.root} · ⋯ or right-click for repository actions`;
|
|
16340
16791
|
const count = gitPanelChangeCount(snapshot?.data);
|
|
16341
16792
|
button.append(
|
|
16342
16793
|
make("span", "git-side-panel-repository-chevron", "›"),
|
|
@@ -16346,8 +16797,11 @@ function renderGitPanelRepositoryCard(card) {
|
|
|
16346
16797
|
const copy = button.querySelector(".git-side-panel-repository-copy");
|
|
16347
16798
|
copy.append(make("strong", undefined, gitPanelRootLabel(card.root)), make("span", undefined, card.root));
|
|
16348
16799
|
button.addEventListener("click", () => toggleGitPanelRepository(card));
|
|
16349
|
-
|
|
16350
|
-
|
|
16800
|
+
const repositoryContext = { card, kind: "repository", path: card.root };
|
|
16801
|
+
bindGitPanelContextMenu(button, repositoryContext);
|
|
16802
|
+
const header = make("div", "git-side-panel-repository-header");
|
|
16803
|
+
header.append(button, gitPanelOverflowButton(repositoryContext, gitPanelRootLabel(card.root)));
|
|
16804
|
+
section.append(header);
|
|
16351
16805
|
if (expanded) section.append(renderGitPanelRepositoryContent(card, snapshot));
|
|
16352
16806
|
return section;
|
|
16353
16807
|
}
|
|
@@ -16410,7 +16864,7 @@ function renderGitPanel() {
|
|
|
16410
16864
|
? "No terminal tabs are open."
|
|
16411
16865
|
: discovering
|
|
16412
16866
|
? "Discovering repositories…"
|
|
16413
|
-
: `${repositoryCount} Git ${repositoryCount === 1 ? "repository" : "repositories"} ·
|
|
16867
|
+
: `${repositoryCount} Git ${repositoryCount === 1 ? "repository" : "repositories"} · ⋯ or right-click for actions`;
|
|
16414
16868
|
}
|
|
16415
16869
|
ensureGitPanelRepositoriesDiscovered();
|
|
16416
16870
|
ensureGitPanelVisibleRepositoriesFresh(cards);
|
|
@@ -17077,10 +17531,11 @@ async function switchTab(tabId) {
|
|
|
17077
17531
|
focusPromptInput({ defer: true });
|
|
17078
17532
|
connectEvents(tabContext);
|
|
17079
17533
|
await refreshAll(tabContext);
|
|
17534
|
+
noteRecentFullRefresh();
|
|
17080
17535
|
if (isCurrentTabContext(tabContext)) markTabOutputSeen();
|
|
17081
17536
|
await refreshThemeCatalog(tabContext).catch((error) => addEvent(`Custom theme catalog refresh failed: ${error.message || String(error)}`, "warn"));
|
|
17082
17537
|
if (!subagentLaunchSlotDraftIsDirty()) {
|
|
17083
|
-
|
|
17538
|
+
loadSubagentLaunchSlotConfigWhenVisible({ tabId }).catch(() => {});
|
|
17084
17539
|
} else {
|
|
17085
17540
|
renderSubagentLaunchSlots();
|
|
17086
17541
|
}
|
|
@@ -17285,14 +17740,26 @@ async function confirmCloseTerminalTabs(targetTabs, label) {
|
|
|
17285
17740
|
});
|
|
17286
17741
|
}
|
|
17287
17742
|
|
|
17743
|
+
async function reopenClosedTerminalTab(tabId) {
|
|
17744
|
+
const response = await api("/api/tabs/reopen", { method: "POST", body: { id: tabId }, scoped: false });
|
|
17745
|
+
await refreshTabs();
|
|
17746
|
+
const reopened = response.data?.tab?.id;
|
|
17747
|
+
if (reopened) await switchTab(reopened);
|
|
17748
|
+
}
|
|
17749
|
+
|
|
17288
17750
|
async function closeTerminalTabs(tabIds, { label = "selected terminal tabs", allowEmpty = false } = {}) {
|
|
17289
17751
|
const targetIds = [...new Set(tabIds.filter(Boolean))];
|
|
17290
17752
|
const targetTabs = targetIds.map((id) => tabs.find((item) => item.id === id)).filter(Boolean);
|
|
17291
17753
|
if (!targetTabs.length) return;
|
|
17292
|
-
|
|
17754
|
+
// Closing one idle tab is routine and reversible (its session stays resumable), so it closes at
|
|
17755
|
+
// once with an Undo instead of a confirmation. Anything with running work still asks first.
|
|
17756
|
+
const quickClose = targetTabs.length === 1 && !tabHasActiveAgent(targetTabs[0]) && !allowEmpty;
|
|
17757
|
+
if (!quickClose && !(await confirmCloseTerminalTabs(targetTabs, label))) return;
|
|
17293
17758
|
|
|
17294
17759
|
const closedActiveTab = targetTabs.some((tab) => tab.id === activeTabId);
|
|
17760
|
+
const closedActiveCwd = closedActiveTab ? tabs.find((tab) => tab.id === activeTabId)?.cwd || "" : "";
|
|
17295
17761
|
const fallbackTabId = tabs.find((item) => !targetIds.includes(item.id))?.id || null;
|
|
17762
|
+
for (const id of targetIds) closingTerminalTabIds.add(id);
|
|
17296
17763
|
try {
|
|
17297
17764
|
if (closedActiveTab) eventSource?.close();
|
|
17298
17765
|
const response = await api("/api/tabs/close", { method: "POST", body: { ids: targetIds, allowEmpty }, scoped: false });
|
|
@@ -17315,12 +17782,25 @@ async function closeTerminalTabs(tabIds, { label = "selected terminal tabs", all
|
|
|
17315
17782
|
syncTerminalCustomGroupsWithTabs(tabs);
|
|
17316
17783
|
clearOpenTerminalTabGroup(null, { force: true });
|
|
17317
17784
|
if (!tabs.length) setWorkspaceDashboardCollapsed(false, { persist: false });
|
|
17785
|
+
if (quickClose && closedIds.length === 1) {
|
|
17786
|
+
const closedTitle = targetTabs[0].title || "tab";
|
|
17787
|
+
offerUndo({
|
|
17788
|
+
message: `Closed ${closedTitle}.`,
|
|
17789
|
+
undo: () => reopenClosedTerminalTab(closedIds[0]),
|
|
17790
|
+
successMessage: `${closedTitle} reopened.`,
|
|
17791
|
+
});
|
|
17792
|
+
}
|
|
17318
17793
|
|
|
17319
17794
|
const activeTabNeedsFallback = closedIds.includes(activeTabId) || !tabs.some((item) => item.id === activeTabId);
|
|
17320
17795
|
if (activeTabNeedsFallback) {
|
|
17321
|
-
const
|
|
17322
|
-
?
|
|
17323
|
-
:
|
|
17796
|
+
const sameCwdFallbackTabId = closedActiveCwd
|
|
17797
|
+
? tabs.find((item) => !closedIds.includes(item.id) && item.cwd === closedActiveCwd)?.id || null
|
|
17798
|
+
: null;
|
|
17799
|
+
const tabContext = setActiveTabId((sameCwdFallbackTabId && tabs.some((item) => item.id === sameCwdFallbackTabId)
|
|
17800
|
+
? sameCwdFallbackTabId
|
|
17801
|
+
: response.data?.activeTabId && tabs.some((item) => item.id === response.data.activeTabId)
|
|
17802
|
+
? response.data.activeTabId
|
|
17803
|
+
: (fallbackTabId && tabs.some((item) => item.id === fallbackTabId) ? fallbackTabId : tabs[0]?.id)) || null, { remember: true });
|
|
17324
17804
|
resetActiveTabUi();
|
|
17325
17805
|
renderTabs();
|
|
17326
17806
|
restoreActiveDraft();
|
|
@@ -17336,6 +17816,8 @@ async function closeTerminalTabs(tabIds, { label = "selected terminal tabs", all
|
|
|
17336
17816
|
addEvent(`closed ${closedIds.length || targetTabs.length} terminal ${closedIds.length === 1 ? "tab" : "tabs"}`, "warn");
|
|
17337
17817
|
} catch (error) {
|
|
17338
17818
|
addEvent(error.message, "error");
|
|
17819
|
+
} finally {
|
|
17820
|
+
for (const id of targetIds) closingTerminalTabIds.delete(id);
|
|
17339
17821
|
}
|
|
17340
17822
|
}
|
|
17341
17823
|
|
|
@@ -17361,6 +17843,7 @@ async function initializeTabs() {
|
|
|
17361
17843
|
restoreTerminalCustomGroups();
|
|
17362
17844
|
syncTerminalCustomGroupsWithTabs(tabs, { persist: false });
|
|
17363
17845
|
restoreMobileContinuityState();
|
|
17846
|
+
restoreDesktopDrafts();
|
|
17364
17847
|
resetActiveTabUi();
|
|
17365
17848
|
renderTabs();
|
|
17366
17849
|
restoreActiveDraft();
|
|
@@ -17379,9 +17862,10 @@ async function initializeTabs() {
|
|
|
17379
17862
|
connectEvents(tabContext);
|
|
17380
17863
|
if (activeTabId) {
|
|
17381
17864
|
await refreshAll(tabContext);
|
|
17865
|
+
noteRecentFullRefresh();
|
|
17382
17866
|
if (isCurrentTabContext(tabContext)) markTabOutputSeen();
|
|
17383
17867
|
if (!subagentLaunchSlotDraftIsDirty() || subagentLaunchSlotConfigTabId !== activeTabId) {
|
|
17384
|
-
|
|
17868
|
+
loadSubagentLaunchSlotConfigWhenVisible().catch(() => {});
|
|
17385
17869
|
}
|
|
17386
17870
|
refreshSamplingParametersForTabContext(tabContext);
|
|
17387
17871
|
await refreshThemeCatalog(tabContext).catch((error) => addEvent(`Custom theme catalog refresh failed: ${error.message || String(error)}`, "warn"));
|
|
@@ -17439,18 +17923,444 @@ function jumpToChatEvent(line) {
|
|
|
17439
17923
|
}
|
|
17440
17924
|
}
|
|
17441
17925
|
|
|
17442
|
-
|
|
17926
|
+
const TOOL_EVENT_TARGET_FIELDS = new Map([
|
|
17927
|
+
["read", "path"],
|
|
17928
|
+
["write", "path"],
|
|
17929
|
+
["edit", "path"],
|
|
17930
|
+
["grep", "path"],
|
|
17931
|
+
["find", "path"],
|
|
17932
|
+
["ls", "path"],
|
|
17933
|
+
]);
|
|
17934
|
+
|
|
17935
|
+
function boundedToolEventTarget(event) {
|
|
17936
|
+
const toolName = String(event?.toolName || "").trim().toLowerCase();
|
|
17937
|
+
const field = TOOL_EVENT_TARGET_FIELDS.get(toolName);
|
|
17938
|
+
if (!field) return "";
|
|
17939
|
+
const args = event?.args ?? event?.arguments ?? event?.invocation?.args;
|
|
17940
|
+
const value = args && typeof args === "object" && !Array.isArray(args) ? args[field] : "";
|
|
17941
|
+
if (typeof value !== "string") return "";
|
|
17942
|
+
const singleLine = value.replace(/[\u0000-\u001f\u007f]+/g, " ").trim();
|
|
17943
|
+
return singleLine.length > 96 ? `${singleLine.slice(0, 93)}…` : singleLine;
|
|
17944
|
+
}
|
|
17945
|
+
|
|
17946
|
+
function shortenedToolCallId(value) {
|
|
17947
|
+
const id = String(value || "").trim();
|
|
17948
|
+
if (!id) return "";
|
|
17949
|
+
return id.length <= 14 ? id : `${id.slice(0, 7)}…${id.slice(-5)}`;
|
|
17950
|
+
}
|
|
17951
|
+
|
|
17952
|
+
function toolEventTimerKey(event) {
|
|
17953
|
+
const toolCallId = String(event?.toolCallId || "").trim();
|
|
17954
|
+
return toolCallId ? `${event?.tabId || activeTabId || "tab"}:${toolCallId}` : "";
|
|
17955
|
+
}
|
|
17956
|
+
|
|
17957
|
+
function toolEventDurationMs(event, phase, occurredAt) {
|
|
17958
|
+
if (phase !== "finish") return null;
|
|
17959
|
+
const reportedDurationMs = Number(event?.durationMs);
|
|
17960
|
+
if (Number.isFinite(reportedDurationMs) && reportedDurationMs >= 0) return reportedDurationMs;
|
|
17961
|
+
const startedAt = toolEventStartedAt.get(toolEventTimerKey(event))?.startedAt;
|
|
17962
|
+
return Number.isFinite(startedAt) ? Math.max(0, occurredAt - startedAt) : null;
|
|
17963
|
+
}
|
|
17964
|
+
|
|
17965
|
+
function formatToolEventDuration(durationMs) {
|
|
17966
|
+
if (!Number.isFinite(durationMs)) return "";
|
|
17967
|
+
if (durationMs < 1000) return `${Math.round(durationMs)} ms`;
|
|
17968
|
+
if (durationMs < 10_000) return `${(durationMs / 1000).toFixed(1)} s`;
|
|
17969
|
+
return `${Math.round(durationMs / 1000)} s`;
|
|
17970
|
+
}
|
|
17971
|
+
|
|
17972
|
+
function toolLifecycleEventDetails(event, phase, occurredAt) {
|
|
17973
|
+
const status = phase === "start" ? "started" : event?.isError ? "failed" : "finished";
|
|
17974
|
+
const startRecord = phase === "finish" ? toolEventStartedAt.get(toolEventTimerKey(event)) : null;
|
|
17975
|
+
const target = boundedToolEventTarget(event) || startRecord?.target || "";
|
|
17976
|
+
const duration = formatToolEventDuration(toolEventDurationMs(event, phase, occurredAt));
|
|
17977
|
+
const callId = shortenedToolCallId(event?.toolCallId);
|
|
17978
|
+
return [
|
|
17979
|
+
target ? { label: "target", value: target } : null,
|
|
17980
|
+
{ label: "status", value: status, tone: event?.isError ? "error" : phase === "finish" ? "success" : "info" },
|
|
17981
|
+
duration ? { label: "duration", value: duration } : null,
|
|
17982
|
+
callId ? { label: "call", value: callId } : null,
|
|
17983
|
+
].filter(Boolean);
|
|
17984
|
+
}
|
|
17985
|
+
|
|
17986
|
+
function toolLifecycleEventArguments(event, phase) {
|
|
17443
17987
|
const occurredAt = Date.now();
|
|
17988
|
+
const timerKey = toolEventTimerKey(event);
|
|
17989
|
+
if (phase === "start" && timerKey) {
|
|
17990
|
+
toolEventStartedAt.set(timerKey, { startedAt: occurredAt, target: boundedToolEventTarget(event) });
|
|
17991
|
+
while (toolEventStartedAt.size > 240) toolEventStartedAt.delete(toolEventStartedAt.keys().next().value);
|
|
17992
|
+
}
|
|
17993
|
+
const toolName = runIndicatorToolName(event?.toolName || "tool");
|
|
17994
|
+
const status = phase === "start" ? "started" : event?.isError ? "failed" : "finished";
|
|
17995
|
+
const args = [`tool ${toolName} ${status}`, event?.isError ? "error" : "info", {
|
|
17996
|
+
toolCallId: event?.toolCallId,
|
|
17997
|
+
toolEventPhase: phase,
|
|
17998
|
+
details: toolLifecycleEventDetails(event, phase, occurredAt),
|
|
17999
|
+
occurredAt,
|
|
18000
|
+
}];
|
|
18001
|
+
if (phase === "finish" && timerKey) toolEventStartedAt.delete(timerKey);
|
|
18002
|
+
return args;
|
|
18003
|
+
}
|
|
18004
|
+
|
|
18005
|
+
function normalizeEventDisplayMode(value) {
|
|
18006
|
+
return value === "compact" ? "compact" : "detailed";
|
|
18007
|
+
}
|
|
18008
|
+
|
|
18009
|
+
function readStoredEventDisplayMode() {
|
|
18010
|
+
try {
|
|
18011
|
+
return normalizeEventDisplayMode(localStorage.getItem(EVENT_DISPLAY_MODE_STORAGE_KEY));
|
|
18012
|
+
} catch {
|
|
18013
|
+
return "detailed";
|
|
18014
|
+
}
|
|
18015
|
+
}
|
|
18016
|
+
|
|
18017
|
+
function normalizeEventFilter(value) {
|
|
18018
|
+
return EVENT_FILTER_VALUES.has(value) ? value : "all";
|
|
18019
|
+
}
|
|
18020
|
+
|
|
18021
|
+
function readStoredEventFilter() {
|
|
18022
|
+
try {
|
|
18023
|
+
return normalizeEventFilter(localStorage.getItem(EVENT_FILTER_STORAGE_KEY));
|
|
18024
|
+
} catch {
|
|
18025
|
+
return "all";
|
|
18026
|
+
}
|
|
18027
|
+
}
|
|
18028
|
+
|
|
18029
|
+
function eventRowMatchesFilter(line, filter = eventFilter) {
|
|
18030
|
+
if (!line?.classList?.contains("event") || filter === "all") return true;
|
|
18031
|
+
if (filter === "errors") return line.dataset.eventLevel === "error";
|
|
18032
|
+
if (filter === "warnings") return line.dataset.eventLevel === "warn";
|
|
18033
|
+
if (filter === "tools") return ["start", "finish"].includes(line.dataset.eventToolPhase);
|
|
18034
|
+
if (filter === "tree") return line.dataset.eventTreeAvailable === "true";
|
|
18035
|
+
return true;
|
|
18036
|
+
}
|
|
18037
|
+
|
|
18038
|
+
function applyEventFilter() {
|
|
18039
|
+
const rows = [...(elements.eventLog?.children || [])].filter((line) => line.classList?.contains("event"));
|
|
18040
|
+
let shown = 0;
|
|
18041
|
+
for (const line of rows) {
|
|
18042
|
+
const matches = eventRowMatchesFilter(line);
|
|
18043
|
+
line.hidden = !matches;
|
|
18044
|
+
if (matches) shown += 1;
|
|
18045
|
+
}
|
|
18046
|
+
const total = rows.length;
|
|
18047
|
+
if (elements.eventFilterStatus) {
|
|
18048
|
+
elements.eventFilterStatus.textContent = total === 0
|
|
18049
|
+
? "No events yet"
|
|
18050
|
+
: eventFilter === "all"
|
|
18051
|
+
? `${total} event${total === 1 ? "" : "s"}`
|
|
18052
|
+
: `${shown} of ${total}`;
|
|
18053
|
+
}
|
|
18054
|
+
if (elements.eventFilterEmpty) {
|
|
18055
|
+
elements.eventFilterEmpty.hidden = total === 0 || shown > 0;
|
|
18056
|
+
const label = elements.eventFilterSelect?.selectedOptions?.[0]?.textContent?.trim() || "this filter";
|
|
18057
|
+
elements.eventFilterEmpty.textContent = `No events match ${label.toLowerCase()}.`;
|
|
18058
|
+
}
|
|
18059
|
+
}
|
|
18060
|
+
|
|
18061
|
+
function syncEventFilterUi() {
|
|
18062
|
+
if (elements.eventFilterSelect) elements.eventFilterSelect.value = eventFilter;
|
|
18063
|
+
applyEventFilter();
|
|
18064
|
+
}
|
|
18065
|
+
|
|
18066
|
+
function setEventFilter(value, { persist = true } = {}) {
|
|
18067
|
+
eventFilter = normalizeEventFilter(value);
|
|
18068
|
+
syncEventFilterUi();
|
|
18069
|
+
if (!persist) return;
|
|
18070
|
+
try {
|
|
18071
|
+
localStorage.setItem(EVENT_FILTER_STORAGE_KEY, eventFilter);
|
|
18072
|
+
} catch {
|
|
18073
|
+
// The filter remains active for this page when storage is unavailable.
|
|
18074
|
+
}
|
|
18075
|
+
}
|
|
18076
|
+
|
|
18077
|
+
function syncEventDisplayModeUi() {
|
|
18078
|
+
if (elements.eventLog) elements.eventLog.dataset.displayMode = eventDisplayMode;
|
|
18079
|
+
elements.eventDisplayDetailedAction?.setAttribute("aria-checked", String(eventDisplayMode === "detailed"));
|
|
18080
|
+
elements.eventDisplayCompactAction?.setAttribute("aria-checked", String(eventDisplayMode === "compact"));
|
|
18081
|
+
}
|
|
18082
|
+
|
|
18083
|
+
function setEventDisplayMode(value, { persist = true } = {}) {
|
|
18084
|
+
eventDisplayMode = normalizeEventDisplayMode(value);
|
|
18085
|
+
syncEventDisplayModeUi();
|
|
18086
|
+
if (!persist) return;
|
|
18087
|
+
try {
|
|
18088
|
+
localStorage.setItem(EVENT_DISPLAY_MODE_STORAGE_KEY, eventDisplayMode);
|
|
18089
|
+
} catch {
|
|
18090
|
+
// Display mode remains active for this page when storage is unavailable.
|
|
18091
|
+
}
|
|
18092
|
+
}
|
|
18093
|
+
|
|
18094
|
+
function addEvent(message, level = "info", { toolCallId = "", toolEventPhase = "", details = [], notify = true, occurredAt = Date.now() } = {}) {
|
|
17444
18095
|
const line = make("button", `event ${level}`.trim());
|
|
17445
18096
|
line.type = "button";
|
|
18097
|
+
line.dataset.eventLevel = String(level || "info").trim().toLowerCase() || "info";
|
|
17446
18098
|
line.dataset.chatEventTimestamp = String(occurredAt);
|
|
17447
|
-
|
|
17448
|
-
|
|
17449
|
-
|
|
17450
|
-
line.
|
|
18099
|
+
const stableToolCallId = String(toolCallId || "").trim();
|
|
18100
|
+
const toolLifecycle = ["start", "finish"].includes(toolEventPhase);
|
|
18101
|
+
const treeEligible = stableToolCallId && toolLifecycle;
|
|
18102
|
+
line.dataset.eventTreeAvailable = String(!!treeEligible);
|
|
18103
|
+
if (stableToolCallId) line.dataset.chatToolCallId = stableToolCallId;
|
|
18104
|
+
if (toolLifecycle) line.dataset.eventToolPhase = toolEventPhase;
|
|
18105
|
+
line.setAttribute("aria-keyshortcuts", "ContextMenu Shift+F10");
|
|
18106
|
+
const time = make("span", "event-time", `[${new Date(occurredAt).toLocaleTimeString()}]`);
|
|
18107
|
+
const summary = make("span", "event-summary", String(message || ""));
|
|
18108
|
+
const main = make("span", "event-main");
|
|
18109
|
+
main.append(time, summary);
|
|
18110
|
+
line.append(main);
|
|
18111
|
+
if (Array.isArray(details) && details.length) {
|
|
18112
|
+
const meta = make("span", "event-details");
|
|
18113
|
+
for (const detail of details) {
|
|
18114
|
+
if (!detail?.label || !detail?.value) continue;
|
|
18115
|
+
const item = make("span", `event-detail${detail.tone ? ` ${detail.tone}` : ""}`);
|
|
18116
|
+
item.append(make("span", "event-detail-label", `${detail.label}:`), document.createTextNode(` ${detail.value}`));
|
|
18117
|
+
meta.append(item);
|
|
18118
|
+
}
|
|
18119
|
+
if (meta.childElementCount) line.append(meta);
|
|
18120
|
+
}
|
|
18121
|
+
const accessibleText = line.textContent.trim();
|
|
18122
|
+
line.title = `Jump to this event in the chat; open the context menu for display options${treeEligible ? " and Tree navigation" : ""}`;
|
|
18123
|
+
line.setAttribute("aria-label", `${accessibleText}. Jump to this event in the chat. Context menu: display options${treeEligible ? " and Tree navigation" : ""}.`);
|
|
17451
18124
|
line.addEventListener("click", () => jumpToChatEvent(line));
|
|
17452
18125
|
elements.eventLog.prepend(line);
|
|
17453
18126
|
while (elements.eventLog.children.length > 120) elements.eventLog.lastElementChild?.remove();
|
|
18127
|
+
applyEventFilter();
|
|
18128
|
+
if (notify && (level === "error" || level === "warn")) {
|
|
18129
|
+
showNoticeToast(message, level);
|
|
18130
|
+
noteUnreadEvent();
|
|
18131
|
+
}
|
|
18132
|
+
}
|
|
18133
|
+
|
|
18134
|
+
function closeEventTreeContextMenu({ returnFocus = true } = {}) {
|
|
18135
|
+
const trigger = eventTreeContextMenuState?.trigger;
|
|
18136
|
+
eventTreeContextMenuState = null;
|
|
18137
|
+
if (elements.eventTreeContextMenu) elements.eventTreeContextMenu.hidden = true;
|
|
18138
|
+
if (elements.eventTreeContextMenuAction) elements.eventTreeContextMenuAction.disabled = false;
|
|
18139
|
+
if (returnFocus && trigger?.isConnected) queueMicrotask(() => trigger.focus({ preventScroll: true }));
|
|
18140
|
+
}
|
|
18141
|
+
|
|
18142
|
+
function setEventTreeContextMenuStatus(message = "", level = "info") {
|
|
18143
|
+
const status = elements.eventTreeContextMenuStatus;
|
|
18144
|
+
if (!status) return;
|
|
18145
|
+
status.textContent = message;
|
|
18146
|
+
status.hidden = !message;
|
|
18147
|
+
status.className = `event-tree-context-menu-status ${level}`;
|
|
18148
|
+
}
|
|
18149
|
+
|
|
18150
|
+
function closeOtherContextMenusForEventTree() {
|
|
18151
|
+
closeFileContextMenu({ returnFocus: false });
|
|
18152
|
+
closeGitPanelContextMenu({ returnFocus: false });
|
|
18153
|
+
closeSidePanelContextMenu({ returnFocus: false });
|
|
18154
|
+
closeVisibilityContextMenu({ returnFocus: false });
|
|
18155
|
+
closeGitFooterContextMenu({ returnFocus: false });
|
|
18156
|
+
closeEventTreeContextMenu({ returnFocus: false });
|
|
18157
|
+
}
|
|
18158
|
+
|
|
18159
|
+
function showEventTreeContextMenu(event, line = null) {
|
|
18160
|
+
const menu = elements.eventTreeContextMenu;
|
|
18161
|
+
if (!menu || (line && !elements.eventLog?.contains(line))) return;
|
|
18162
|
+
const toolCallId = String(line?.dataset.chatToolCallId || "").trim();
|
|
18163
|
+
const phase = line?.dataset.eventToolPhase || "";
|
|
18164
|
+
const treeEligible = !!toolCallId && ["start", "finish"].includes(phase);
|
|
18165
|
+
event.preventDefault();
|
|
18166
|
+
event.stopPropagation();
|
|
18167
|
+
closeOtherContextMenusForEventTree();
|
|
18168
|
+
eventTreeContextMenuState = {
|
|
18169
|
+
trigger: line,
|
|
18170
|
+
toolCallId,
|
|
18171
|
+
phase,
|
|
18172
|
+
tabContext: treeEligible ? activeTabContext() : null,
|
|
18173
|
+
busy: false,
|
|
18174
|
+
openedAt: performance.now(),
|
|
18175
|
+
};
|
|
18176
|
+
setEventTreeContextMenuStatus("");
|
|
18177
|
+
syncEventDisplayModeUi();
|
|
18178
|
+
if (elements.eventTreeContextMenuAction) elements.eventTreeContextMenuAction.hidden = !treeEligible;
|
|
18179
|
+
menu.hidden = false;
|
|
18180
|
+
const rect = menu.getBoundingClientRect();
|
|
18181
|
+
const left = Math.min(Number(event.clientX) || 0, Math.max(8, window.innerWidth - rect.width - 8));
|
|
18182
|
+
const top = Math.min(Number(event.clientY) || 0, Math.max(8, window.innerHeight - rect.height - 8));
|
|
18183
|
+
menu.style.left = `${Math.max(8, left)}px`;
|
|
18184
|
+
menu.style.top = `${Math.max(8, top)}px`;
|
|
18185
|
+
const displayAction = eventDisplayMode === "compact" ? elements.eventDisplayCompactAction : elements.eventDisplayDetailedAction;
|
|
18186
|
+
displayAction?.focus({ preventScroll: true });
|
|
18187
|
+
}
|
|
18188
|
+
|
|
18189
|
+
function eventTreeTargetEntryId(data, state) {
|
|
18190
|
+
const targets = Array.isArray(data?.eventTargets) ? data.eventTargets : [];
|
|
18191
|
+
const target = targets.find((item) => String(item?.toolCallId || "") === state.toolCallId);
|
|
18192
|
+
const entryId = state.phase === "start" ? target?.startEntryId : target?.finishEntryId || target?.startEntryId;
|
|
18193
|
+
if (typeof entryId !== "string" || !entryId.trim()) return "";
|
|
18194
|
+
const nodes = Array.isArray(data?.nodes) ? data.nodes : [];
|
|
18195
|
+
return nodes.some((node) => node?.id === entryId) ? entryId : "";
|
|
18196
|
+
}
|
|
18197
|
+
|
|
18198
|
+
async function navigateEventTreeBoundary() {
|
|
18199
|
+
const state = eventTreeContextMenuState;
|
|
18200
|
+
const action = elements.eventTreeContextMenuAction;
|
|
18201
|
+
if (!state || state.busy || !action || !isCurrentTabContext(state.tabContext)) return;
|
|
18202
|
+
state.busy = true;
|
|
18203
|
+
action.disabled = true;
|
|
18204
|
+
setEventTreeContextMenuStatus("Resolving this tool boundary…");
|
|
18205
|
+
try {
|
|
18206
|
+
const tree = await api("/api/session-tree", { tabId: state.tabContext.tabId });
|
|
18207
|
+
if (eventTreeContextMenuState !== state || !isCurrentTabContext(state.tabContext)) return;
|
|
18208
|
+
const entryId = eventTreeTargetEntryId(tree.data, state);
|
|
18209
|
+
if (!entryId) {
|
|
18210
|
+
setEventTreeContextMenuStatus("This tool boundary is not available in the current persisted session tree.", "warn");
|
|
18211
|
+
addEvent("Tree navigation target is unavailable or stale; the session was not changed.", "warn");
|
|
18212
|
+
return;
|
|
18213
|
+
}
|
|
18214
|
+
setEventTreeContextMenuStatus("");
|
|
18215
|
+
const confirmed = await appConfirm({
|
|
18216
|
+
title: "Navigate to this tool boundary?",
|
|
18217
|
+
summary: "This changes the current session branch. Later entries stay in the tree, and no automatic branch summary is generated.",
|
|
18218
|
+
affected: "Use /tree to navigate back or choose another branch.",
|
|
18219
|
+
undoable: true,
|
|
18220
|
+
confirmLabel: "Navigate",
|
|
18221
|
+
danger: false,
|
|
18222
|
+
});
|
|
18223
|
+
if (eventTreeContextMenuState !== state || !isCurrentTabContext(state.tabContext)) return;
|
|
18224
|
+
if (!confirmed) {
|
|
18225
|
+
setEventTreeContextMenuStatus("Navigation cancelled; the session was not changed.");
|
|
18226
|
+
return;
|
|
18227
|
+
}
|
|
18228
|
+
setEventTreeContextMenuStatus("Navigating…");
|
|
18229
|
+
const result = await api("/api/tree-navigate", {
|
|
18230
|
+
method: "POST",
|
|
18231
|
+
body: { entryId, summarize: false },
|
|
18232
|
+
tabId: state.tabContext.tabId,
|
|
18233
|
+
});
|
|
18234
|
+
if (!isCurrentTabContext(state.tabContext)) return;
|
|
18235
|
+
applyResponseTab(result);
|
|
18236
|
+
addTransientMessage({ role: "native", title: "/tree", content: result.data?.message || "Navigated to the selected tool boundary.", level: "info" });
|
|
18237
|
+
if (eventTreeContextMenuState === state) closeEventTreeContextMenu();
|
|
18238
|
+
await refreshAll(state.tabContext);
|
|
18239
|
+
} catch (error) {
|
|
18240
|
+
if (eventTreeContextMenuState === state && isCurrentTabContext(state.tabContext)) {
|
|
18241
|
+
const message = error?.message || String(error);
|
|
18242
|
+
setEventTreeContextMenuStatus(`Navigation failed: ${message}`, "error");
|
|
18243
|
+
addEvent(`Tree navigation failed: ${message}`, "error");
|
|
18244
|
+
}
|
|
18245
|
+
} finally {
|
|
18246
|
+
if (eventTreeContextMenuState === state) {
|
|
18247
|
+
state.busy = false;
|
|
18248
|
+
action.disabled = false;
|
|
18249
|
+
action.focus({ preventScroll: true });
|
|
18250
|
+
}
|
|
18251
|
+
}
|
|
18252
|
+
}
|
|
18253
|
+
|
|
18254
|
+
// --- Non-blocking warn/error notices -------------------------------------------------------
|
|
18255
|
+
// The Events log lives in a collapsed Control Deck section, so on its own it makes failures look
|
|
18256
|
+
// like "nothing happened". Warnings and errors additionally surface as a short-lived toast (max 3,
|
|
18257
|
+
// deduplicated) with a shortcut to the Events log, and the Events header shows an unread count.
|
|
18258
|
+
function noticeToastTimeout(level) {
|
|
18259
|
+
return NOTICE_TOAST_TIMEOUT_MS[level] || (level === "error" ? NOTICE_TOAST_TIMEOUT_MS.error : NOTICE_TOAST_TIMEOUT_MS.warn);
|
|
18260
|
+
}
|
|
18261
|
+
|
|
18262
|
+
function removeNoticeToast(entry) {
|
|
18263
|
+
const index = noticeToasts.indexOf(entry);
|
|
18264
|
+
if (index >= 0) noticeToasts.splice(index, 1);
|
|
18265
|
+
clearTimeout(entry.timer);
|
|
18266
|
+
entry.node.remove();
|
|
18267
|
+
}
|
|
18268
|
+
|
|
18269
|
+
function armNoticeToastTimer(entry) {
|
|
18270
|
+
clearTimeout(entry.timer);
|
|
18271
|
+
entry.timer = setTimeout(() => removeNoticeToast(entry), noticeToastTimeout(entry.level));
|
|
18272
|
+
}
|
|
18273
|
+
|
|
18274
|
+
function showNoticeToast(message, level = "warn") {
|
|
18275
|
+
const stack = elements.noticeToastStack;
|
|
18276
|
+
const text = String(message || "").trim();
|
|
18277
|
+
if (!stack || !text) return null;
|
|
18278
|
+
const existing = noticeToasts.find((entry) => entry.level === level && entry.text === text);
|
|
18279
|
+
if (existing) {
|
|
18280
|
+
existing.count += 1;
|
|
18281
|
+
existing.countNode.textContent = `×${existing.count}`;
|
|
18282
|
+
existing.countNode.hidden = false;
|
|
18283
|
+
armNoticeToastTimer(existing);
|
|
18284
|
+
return existing;
|
|
18285
|
+
}
|
|
18286
|
+
const node = make("div", `notice-toast ${level}`);
|
|
18287
|
+
node.setAttribute("role", level === "error" ? "alert" : "status");
|
|
18288
|
+
const messageNode = make("span", "notice-toast-message", text);
|
|
18289
|
+
const countNode = make("span", "notice-toast-count", "");
|
|
18290
|
+
countNode.hidden = true;
|
|
18291
|
+
messageNode.append(countNode);
|
|
18292
|
+
const eventsButton = make("button", "notice-toast-events", "Events");
|
|
18293
|
+
eventsButton.type = "button";
|
|
18294
|
+
eventsButton.title = "Open the Events log in the Control Deck";
|
|
18295
|
+
const dismissButton = make("button", "notice-toast-dismiss", "×");
|
|
18296
|
+
dismissButton.type = "button";
|
|
18297
|
+
dismissButton.setAttribute("aria-label", "Dismiss notification");
|
|
18298
|
+
node.append(messageNode, eventsButton, dismissButton);
|
|
18299
|
+
const entry = { node, level, text, count: 1, countNode, timer: null };
|
|
18300
|
+
eventsButton.addEventListener("click", () => {
|
|
18301
|
+
removeNoticeToast(entry);
|
|
18302
|
+
revealEventsSection();
|
|
18303
|
+
});
|
|
18304
|
+
dismissButton.addEventListener("click", () => removeNoticeToast(entry));
|
|
18305
|
+
node.addEventListener("pointerenter", () => clearTimeout(entry.timer));
|
|
18306
|
+
node.addEventListener("pointerleave", () => armNoticeToastTimer(entry));
|
|
18307
|
+
noticeToasts.push(entry);
|
|
18308
|
+
stack.append(node);
|
|
18309
|
+
while (noticeToasts.length > NOTICE_TOAST_LIMIT) removeNoticeToast(noticeToasts[0]);
|
|
18310
|
+
armNoticeToastTimer(entry);
|
|
18311
|
+
return entry;
|
|
18312
|
+
}
|
|
18313
|
+
|
|
18314
|
+
function eventsSectionRecord() {
|
|
18315
|
+
return sidePanelSectionRecords().find((record) => record.id === "events") || null;
|
|
18316
|
+
}
|
|
18317
|
+
|
|
18318
|
+
function eventsSectionIsVisibleAndExpanded() {
|
|
18319
|
+
const record = eventsSectionRecord();
|
|
18320
|
+
if (!record || record.section.hidden || record.section.classList.contains("collapsed")) return false;
|
|
18321
|
+
return !document.body.classList.contains("side-panel-collapsed") || document.body.classList.contains("control-deck-left");
|
|
18322
|
+
}
|
|
18323
|
+
|
|
18324
|
+
function renderEventsUnreadBadge() {
|
|
18325
|
+
const badge = elements.eventsUnreadBadge;
|
|
18326
|
+
if (!badge) return;
|
|
18327
|
+
badge.textContent = eventsUnreadCount > 99 ? "99+" : String(eventsUnreadCount);
|
|
18328
|
+
badge.hidden = eventsUnreadCount === 0;
|
|
18329
|
+
badge.setAttribute("aria-label", `${eventsUnreadCount} unread warning${eventsUnreadCount === 1 ? "" : "s"} or errors`);
|
|
18330
|
+
}
|
|
18331
|
+
|
|
18332
|
+
function noteUnreadEvent() {
|
|
18333
|
+
if (eventsSectionIsVisibleAndExpanded()) return;
|
|
18334
|
+
eventsUnreadCount += 1;
|
|
18335
|
+
renderEventsUnreadBadge();
|
|
18336
|
+
}
|
|
18337
|
+
|
|
18338
|
+
function clearUnreadEvents() {
|
|
18339
|
+
if (!eventsUnreadCount) return;
|
|
18340
|
+
eventsUnreadCount = 0;
|
|
18341
|
+
renderEventsUnreadBadge();
|
|
18342
|
+
}
|
|
18343
|
+
|
|
18344
|
+
function revealSidePanelSectionById(id) {
|
|
18345
|
+
const record = sidePanelSectionRecords().find((entry) => entry.id === id);
|
|
18346
|
+
if (!record) return;
|
|
18347
|
+
if (record.section.hidden) setSidePanelSectionVisible(record, true);
|
|
18348
|
+
if (document.body.classList.contains("side-panel-collapsed") && !document.body.classList.contains("control-deck-left")) setSidePanelCollapsed(false, { focusPanel: true });
|
|
18349
|
+
if (record.section.classList.contains("collapsed")) setSidePanelSectionCollapsed(record, false);
|
|
18350
|
+
queueMicrotask(() => {
|
|
18351
|
+
record.section.scrollIntoView?.({ block: "nearest" });
|
|
18352
|
+
record.button?.focus?.({ preventScroll: true });
|
|
18353
|
+
});
|
|
18354
|
+
}
|
|
18355
|
+
|
|
18356
|
+
function revealEventsSection() {
|
|
18357
|
+
const record = eventsSectionRecord();
|
|
18358
|
+
if (!record) return;
|
|
18359
|
+
if (record.section.hidden) setSidePanelSectionVisible(record, true);
|
|
18360
|
+
if (document.body.classList.contains("side-panel-collapsed") && !document.body.classList.contains("control-deck-left")) setSidePanelCollapsed(false);
|
|
18361
|
+
if (record.section.classList.contains("collapsed")) setSidePanelSectionCollapsed(record, false);
|
|
18362
|
+
clearUnreadEvents();
|
|
18363
|
+
queueMicrotask(() => record.section.scrollIntoView?.({ block: "nearest" }));
|
|
17454
18364
|
}
|
|
17455
18365
|
|
|
17456
18366
|
function browserNotificationSupported() {
|
|
@@ -17745,6 +18655,24 @@ function formatDate(value) {
|
|
|
17745
18655
|
return Number.isNaN(date.getTime()) ? "" : date.toLocaleString();
|
|
17746
18656
|
}
|
|
17747
18657
|
|
|
18658
|
+
// "3 min ago", "yesterday 14:05", "Aug 3, 09:12" — for lists where raw ISO stamps were shown.
|
|
18659
|
+
function formatRelativeDate(value, now = Date.now()) {
|
|
18660
|
+
if (!value) return "";
|
|
18661
|
+
const date = typeof value === "number" ? new Date(value) : new Date(String(value));
|
|
18662
|
+
const time = date.getTime();
|
|
18663
|
+
if (Number.isNaN(time)) return String(value);
|
|
18664
|
+
const diff = Math.max(0, now - time);
|
|
18665
|
+
const minute = 60_000;
|
|
18666
|
+
const hour = 60 * minute;
|
|
18667
|
+
const day = 24 * hour;
|
|
18668
|
+
if (diff < minute) return "just now";
|
|
18669
|
+
if (diff < hour) return `${Math.round(diff / minute)} min ago`;
|
|
18670
|
+
if (diff < day && new Date(now).getDate() === date.getDate()) return `today ${date.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })}`;
|
|
18671
|
+
if (diff < 2 * day) return `yesterday ${date.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })}`;
|
|
18672
|
+
if (diff < 7 * day) return `${Math.round(diff / day)} days ago`;
|
|
18673
|
+
return date.toLocaleDateString([], { month: "short", day: "numeric", ...(new Date(now).getFullYear() === date.getFullYear() ? {} : { year: "numeric" }) });
|
|
18674
|
+
}
|
|
18675
|
+
|
|
17748
18676
|
function stripAnsi(text) {
|
|
17749
18677
|
return String(text ?? "").replace(/(?:\x1B|\u241B)(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g, "");
|
|
17750
18678
|
}
|
|
@@ -17895,7 +18823,9 @@ function formatStatusEntry(key, value) {
|
|
|
17895
18823
|
|
|
17896
18824
|
function shortModelLabel(model) {
|
|
17897
18825
|
if (!model) return "unknown";
|
|
17898
|
-
|
|
18826
|
+
// Model id first: when a narrow footer chip truncates from the end, the useful part survives
|
|
18827
|
+
// ("qwen3.6-35b-a3b · lmstu…" instead of "(lmstu…").
|
|
18828
|
+
return `${model.id} · ${model.provider}`;
|
|
17899
18829
|
}
|
|
17900
18830
|
|
|
17901
18831
|
function footerThinkingLevelLabel(level) {
|
|
@@ -17948,6 +18878,37 @@ function footerThinkingLevels() {
|
|
|
17948
18878
|
return levels.length ? levels : ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
|
|
17949
18879
|
}
|
|
17950
18880
|
|
|
18881
|
+
// Which thinking levels the active model actually honors (mirrors the server-side rule used for
|
|
18882
|
+
// launch slots): non-reasoning models only "off"; xhigh/max only when the model maps them.
|
|
18883
|
+
function activeModelSupportedThinkingLevels(model = currentState?.model) {
|
|
18884
|
+
const catalogModel = model && Array.isArray(availableModels)
|
|
18885
|
+
? availableModels.find((candidate) => candidate?.provider === model.provider && candidate?.id === model.id) || model
|
|
18886
|
+
: model;
|
|
18887
|
+
if (!catalogModel || typeof catalogModel.reasoning !== "boolean") return null; // unknown → don't restrict
|
|
18888
|
+
if (!catalogModel.reasoning) return ["off"];
|
|
18889
|
+
const mapping = catalogModel.thinkingLevelMap && typeof catalogModel.thinkingLevelMap === "object" ? catalogModel.thinkingLevelMap : {};
|
|
18890
|
+
return footerThinkingLevels().filter((level) => {
|
|
18891
|
+
if (mapping[level] === null) return false;
|
|
18892
|
+
if (["xhigh", "max"].includes(level)) return typeof mapping[level] === "string" || !Object.keys(mapping).length;
|
|
18893
|
+
return true;
|
|
18894
|
+
});
|
|
18895
|
+
}
|
|
18896
|
+
|
|
18897
|
+
function thinkingLevelSupportedByActiveModel(level) {
|
|
18898
|
+
const supported = activeModelSupportedThinkingLevels();
|
|
18899
|
+
return !supported || supported.includes(level);
|
|
18900
|
+
}
|
|
18901
|
+
|
|
18902
|
+
function syncThinkingSelectSupport() {
|
|
18903
|
+
const supported = activeModelSupportedThinkingLevels();
|
|
18904
|
+
for (const option of elements.thinkingSelect?.options || []) {
|
|
18905
|
+
const ok = !supported || supported.includes(option.value);
|
|
18906
|
+
option.disabled = !ok && option.value !== elements.thinkingSelect.value;
|
|
18907
|
+
const base = option.dataset.baseLabel || (option.dataset.baseLabel = option.textContent);
|
|
18908
|
+
option.textContent = ok ? base : `${base} (not supported by this model)`;
|
|
18909
|
+
}
|
|
18910
|
+
}
|
|
18911
|
+
|
|
17951
18912
|
function formatFooterTokenCount(value) {
|
|
17952
18913
|
const n = Math.max(0, Number(value) || 0);
|
|
17953
18914
|
if (n < 1000) return `${Math.round(n)}`;
|
|
@@ -18824,6 +19785,7 @@ function showGitFooterContextMenu(event, chip, trigger) {
|
|
|
18824
19785
|
closeGitPanelContextMenu({ returnFocus: false });
|
|
18825
19786
|
closeSidePanelContextMenu({ returnFocus: false });
|
|
18826
19787
|
closeGitFooterContextMenu({ returnFocus: false });
|
|
19788
|
+
closeEventTreeContextMenu({ returnFocus: false });
|
|
18827
19789
|
hideFooterTooltip();
|
|
18828
19790
|
|
|
18829
19791
|
const label = cleanStatusText(chip?.label) || gitFooterVisibilityLabel(key);
|
|
@@ -18955,6 +19917,39 @@ function normalizeFooterPayloadChip(value, index) {
|
|
|
18955
19917
|
return chip;
|
|
18956
19918
|
}
|
|
18957
19919
|
|
|
19920
|
+
function normalizeFooterProviderUsageWindow(value) {
|
|
19921
|
+
if (!value || typeof value !== "object") return null;
|
|
19922
|
+
const label = cleanFooterPayloadText(value.label, "Usage window", 32);
|
|
19923
|
+
const usedPercent = Number(value.usedPercent);
|
|
19924
|
+
if (!Number.isFinite(usedPercent) || usedPercent < 0 || usedPercent > 100) return null;
|
|
19925
|
+
const window = { label, usedPercent };
|
|
19926
|
+
const windowMinutes = typeof value.windowMinutes === "number" ? value.windowMinutes : Number.NaN;
|
|
19927
|
+
if (Number.isFinite(windowMinutes) && windowMinutes > 0) window.windowMinutes = windowMinutes;
|
|
19928
|
+
const resetAt = typeof value.resetAt === "number" ? value.resetAt : Number.NaN;
|
|
19929
|
+
if (Number.isFinite(resetAt) && resetAt >= 0) window.resetAt = resetAt;
|
|
19930
|
+
const resetAfterSeconds = typeof value.resetAfterSeconds === "number" ? value.resetAfterSeconds : Number.NaN;
|
|
19931
|
+
if (Number.isFinite(resetAfterSeconds) && resetAfterSeconds >= 0) window.resetAfterSeconds = resetAfterSeconds;
|
|
19932
|
+
return window;
|
|
19933
|
+
}
|
|
19934
|
+
|
|
19935
|
+
function normalizeFooterProviderUsage(value) {
|
|
19936
|
+
if (!value || typeof value !== "object") return null;
|
|
19937
|
+
if (value.provider !== "anthropic" && value.provider !== "openai-codex") return null;
|
|
19938
|
+
const capturedAt = typeof value.capturedAt === "number" ? value.capturedAt : Number.NaN;
|
|
19939
|
+
if (!Number.isFinite(capturedAt) || capturedAt <= 0) return null;
|
|
19940
|
+
const primary = normalizeFooterProviderUsageWindow(value.primary);
|
|
19941
|
+
const secondary = normalizeFooterProviderUsageWindow(value.secondary);
|
|
19942
|
+
if (!primary && !secondary) return null;
|
|
19943
|
+
const plan = cleanFooterPayloadText(value.plan, "", 80);
|
|
19944
|
+
return {
|
|
19945
|
+
provider: value.provider,
|
|
19946
|
+
capturedAt,
|
|
19947
|
+
...(primary ? { primary } : {}),
|
|
19948
|
+
...(secondary ? { secondary } : {}),
|
|
19949
|
+
...(plan ? { plan } : {}),
|
|
19950
|
+
};
|
|
19951
|
+
}
|
|
19952
|
+
|
|
18958
19953
|
function currentGitFooterCacheCwd(tabId = activeTabId) {
|
|
18959
19954
|
const tab = tabs.find((item) => item.id === tabId) || activeTab();
|
|
18960
19955
|
return latestWorkspace?.cwd || tab?.cwd || "";
|
|
@@ -18968,8 +19963,9 @@ function parseGitFooterWebuiPayloadRaw(raw) {
|
|
|
18968
19963
|
const main = Array.isArray(parsed.main) ? parsed.main.map(normalizeFooterPayloadChip).filter(Boolean).slice(0, 8) : [];
|
|
18969
19964
|
const meta = Array.isArray(parsed.meta) ? parsed.meta.map(normalizeFooterPayloadChip).filter(Boolean).slice(0, 10) : [];
|
|
18970
19965
|
const visibility = normalizeGitFooterWebuiVisibility(parsed.visibility);
|
|
18971
|
-
|
|
18972
|
-
|
|
19966
|
+
const providerUsage = normalizeFooterProviderUsage(parsed.providerUsage);
|
|
19967
|
+
if (!main.length && !meta.length && !parsed.visibility && !providerUsage) return null;
|
|
19968
|
+
return { main, meta, visibility, ...(providerUsage ? { providerUsage } : {}) };
|
|
18973
19969
|
} catch {
|
|
18974
19970
|
return null;
|
|
18975
19971
|
}
|
|
@@ -19970,9 +20966,15 @@ function gitFileActionButtons(actions) {
|
|
|
19970
20966
|
const button = make("button", `git-file-action ${action.className || ""}`.trim(), action.label);
|
|
19971
20967
|
button.type = "button";
|
|
19972
20968
|
button.title = action.title || action.label;
|
|
20969
|
+
if (action.path) button.dataset.gitFileActionPath = action.path;
|
|
20970
|
+
if (action.path && gitChangesState.busyPath === action.path) {
|
|
20971
|
+
button.disabled = true;
|
|
20972
|
+
button.setAttribute("aria-busy", "true");
|
|
20973
|
+
}
|
|
19973
20974
|
button.addEventListener("click", (event) => {
|
|
19974
20975
|
event.preventDefault();
|
|
19975
20976
|
event.stopPropagation();
|
|
20977
|
+
if (button.disabled) return;
|
|
19976
20978
|
action.onClick();
|
|
19977
20979
|
});
|
|
19978
20980
|
wrap.append(button);
|
|
@@ -20056,14 +21058,14 @@ function gitChangesFileActionsFor(sectionKey, path) {
|
|
|
20056
21058
|
if (!path || gitChangesState.loading || gitChangesState.pulling || gitChangesState.fetching) return [];
|
|
20057
21059
|
if (sectionKey === "unstaged") {
|
|
20058
21060
|
return [
|
|
20059
|
-
{ label: "Stage", title: `git add -- ${path}`, onClick: () => runGitFileAction("stage", path) },
|
|
21061
|
+
{ label: "Stage", path, title: `git add -- ${path}`, onClick: () => runGitFileAction("stage", path) },
|
|
20060
21062
|
...gitChangesCommonFileActions(path),
|
|
20061
|
-
{ label: "Discard", className: "danger", title: `git restore -- ${path} (destructive)`, onClick: () => runGitFileAction("discard", path) },
|
|
21063
|
+
{ label: "Discard", path, className: "danger", title: `git restore -- ${path} (destructive)`, onClick: () => runGitFileAction("discard", path) },
|
|
20062
21064
|
];
|
|
20063
21065
|
}
|
|
20064
21066
|
if (sectionKey === "staged") {
|
|
20065
21067
|
return [
|
|
20066
|
-
{ label: "Unstage", title: `git restore --staged -- ${path}`, onClick: () => runGitFileAction("unstage", path) },
|
|
21068
|
+
{ label: "Unstage", path, title: `git restore --staged -- ${path}`, onClick: () => runGitFileAction("unstage", path) },
|
|
20067
21069
|
...gitChangesCommonFileActions(path),
|
|
20068
21070
|
];
|
|
20069
21071
|
}
|
|
@@ -20071,9 +21073,18 @@ function gitChangesFileActionsFor(sectionKey, path) {
|
|
|
20071
21073
|
return [];
|
|
20072
21074
|
}
|
|
20073
21075
|
|
|
21076
|
+
// Per-file fold state for the Git Changes dialog survives the full re-render that follows every
|
|
21077
|
+
// stage/unstage/discard, so files the user collapsed stay collapsed.
|
|
21078
|
+
const gitChangesCollapsedFiles = new Set();
|
|
21079
|
+
|
|
20074
21080
|
function renderGitDiffFile(file, actions = []) {
|
|
20075
21081
|
const details = make("details", `git-diff-file ${file.className || ""}`.trim());
|
|
20076
|
-
|
|
21082
|
+
const fileKey = file.path || "diff";
|
|
21083
|
+
details.open = !gitChangesCollapsedFiles.has(fileKey);
|
|
21084
|
+
details.addEventListener("toggle", () => {
|
|
21085
|
+
if (details.open) gitChangesCollapsedFiles.delete(fileKey);
|
|
21086
|
+
else gitChangesCollapsedFiles.add(fileKey);
|
|
21087
|
+
});
|
|
20077
21088
|
details.dataset.gitDiffFile = file.path || "diff";
|
|
20078
21089
|
const summary = make("summary", "git-diff-file-summary");
|
|
20079
21090
|
summary.append(
|
|
@@ -20194,9 +21205,9 @@ function renderGitUntrackedFile(entry) {
|
|
|
20194
21205
|
if (!gitChangesState.loading && !gitChangesState.pulling && !gitChangesState.fetching) {
|
|
20195
21206
|
const summary = node.querySelector("summary");
|
|
20196
21207
|
const actions = gitFileActionButtons([
|
|
20197
|
-
{ label: "Stage", title: `git add -- ${entry.path}`, onClick: () => runGitFileAction("stage", entry.path) },
|
|
21208
|
+
{ label: "Stage", path: entry.path, title: `git add -- ${entry.path}`, onClick: () => runGitFileAction("stage", entry.path) },
|
|
20198
21209
|
...gitChangesCommonFileActions(entry.path),
|
|
20199
|
-
{ label: "Delete", className: "danger", title: "Delete this untracked file from disk (destructive)", onClick: () => runGitFileAction("delete-untracked", entry.path) },
|
|
21210
|
+
{ label: "Delete", path: entry.path, className: "danger", title: "Delete this untracked file from disk (destructive)", onClick: () => runGitFileAction("delete-untracked", entry.path) },
|
|
20200
21211
|
]);
|
|
20201
21212
|
if (summary && actions) summary.append(actions);
|
|
20202
21213
|
}
|
|
@@ -20505,7 +21516,7 @@ function renderGitChangesDialog() {
|
|
|
20505
21516
|
return;
|
|
20506
21517
|
}
|
|
20507
21518
|
if (!data) {
|
|
20508
|
-
body.append(make("div", "git-changes-empty", "Open from the
|
|
21519
|
+
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
21520
|
return;
|
|
20510
21521
|
}
|
|
20511
21522
|
|
|
@@ -20547,7 +21558,8 @@ function renderGitChangesDialog() {
|
|
|
20547
21558
|
async function loadGitChangesDialog(tabContext = activeTabContext()) {
|
|
20548
21559
|
const requestSerial = ++gitChangesRequestSerial;
|
|
20549
21560
|
gitChangesUntrackedContentRequests.clear();
|
|
20550
|
-
|
|
21561
|
+
if (gitChangesState.tabId !== (tabContext.tabId || activeTabId)) gitChangesCollapsedFiles.clear();
|
|
21562
|
+
gitChangesState = { ...gitChangesState, loading: true, busyPath: "", error: "", errorCode: "", errorHint: "", message: "", pullResult: null, tabId: tabContext.tabId || activeTabId, mode: "changes", commit: null };
|
|
20551
21563
|
renderGitChangesDialog();
|
|
20552
21564
|
try {
|
|
20553
21565
|
const [response, operationResponse] = await Promise.all([
|
|
@@ -20789,16 +21801,30 @@ async function runGitFileAction(action, path) {
|
|
|
20789
21801
|
}[action];
|
|
20790
21802
|
if (!config) return;
|
|
20791
21803
|
if (config.confirm && !(await appConfirmText(config.confirm, { affected: path, confirmLabel: action }))) return;
|
|
21804
|
+
if (gitChangesState.busyPath) return; // one file action at a time; ignore double clicks
|
|
21805
|
+
// Remember which control had focus so it can be restored after the dialog re-renders.
|
|
21806
|
+
const focusedActionLabel = document.activeElement?.classList?.contains("git-file-action") ? document.activeElement.textContent : "";
|
|
21807
|
+
const restoreFocus = () => {
|
|
21808
|
+
if (!focusedActionLabel) return;
|
|
21809
|
+
const candidates = [...(elements.gitChangesBody?.querySelectorAll(`.git-file-action[data-git-file-action-path="${CSS.escape(path)}"]`) || [])];
|
|
21810
|
+
const target = candidates.find((node) => node.textContent === focusedActionLabel) || candidates[0]
|
|
21811
|
+
|| elements.gitChangesBody?.querySelector(".git-file-action") || elements.gitChangesDialog?.querySelector("button");
|
|
21812
|
+
target?.focus?.({ preventScroll: true });
|
|
21813
|
+
};
|
|
21814
|
+
gitChangesState = { ...gitChangesState, busyPath: path };
|
|
21815
|
+
renderGitChangesDialog();
|
|
20792
21816
|
try {
|
|
20793
21817
|
const response = await api(config.url, { method: "POST", body: config.body, tabId });
|
|
20794
21818
|
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: "" };
|
|
21819
|
+
gitChangesState = { ...gitChangesState, busyPath: "", data: response.data?.changes || gitChangesState.data, message: config.label, error: "", errorCode: "", errorHint: "" };
|
|
20796
21820
|
addEvent(config.label, "success");
|
|
20797
21821
|
renderGitChangesDialog();
|
|
21822
|
+
restoreFocus();
|
|
20798
21823
|
requestGitFooterWebuiPayload(activeTabContext(tabId), { force: true });
|
|
20799
21824
|
} catch (error) {
|
|
20800
|
-
gitChangesState = { ...gitChangesState, error: error.message || String(error) };
|
|
21825
|
+
gitChangesState = { ...gitChangesState, busyPath: "", error: error.message || String(error) };
|
|
20801
21826
|
renderGitChangesDialog();
|
|
21827
|
+
restoreFocus();
|
|
20802
21828
|
addEvent(error.message || String(error), "error");
|
|
20803
21829
|
}
|
|
20804
21830
|
}
|
|
@@ -21195,8 +22221,8 @@ function renderGitUndoTools(body, data, busy) {
|
|
|
21195
22221
|
row.append(gitToolsButton(
|
|
21196
22222
|
"Amend last commit message",
|
|
21197
22223
|
{ 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 =
|
|
22224
|
+
async () => {
|
|
22225
|
+
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
22226
|
if (!message || !message.trim()) return;
|
|
21201
22227
|
runGitToolAction("undo", {
|
|
21202
22228
|
url: "/api/git-undo/amend-message",
|
|
@@ -21341,10 +22367,10 @@ function renderGitTagTools(body, data, busy) {
|
|
|
21341
22367
|
body.append(item);
|
|
21342
22368
|
}
|
|
21343
22369
|
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 =
|
|
22370
|
+
row.append(gitToolsButton("Create annotated tag…", { disabled: busy, title: "git tag -a <name> -m <message> (never pushed automatically)" }, async () => {
|
|
22371
|
+
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
22372
|
if (!name || !name.trim()) return;
|
|
21347
|
-
const message =
|
|
22373
|
+
const message = await appPromptText({ title: `Tag message for ${name.trim()}`, defaultValue: name.trim(), confirmLabel: "Create tag" });
|
|
21348
22374
|
if (message === null) return;
|
|
21349
22375
|
runGitToolAction("tags", {
|
|
21350
22376
|
url: "/api/git-tags/create",
|
|
@@ -22028,6 +23054,7 @@ function applyOptimisticGitFooterBranch(branch, tabContext = activeTabContext())
|
|
|
22028
23054
|
type: GIT_FOOTER_WEBUI_PAYLOAD_TYPE,
|
|
22029
23055
|
version: GIT_FOOTER_WEBUI_PAYLOAD_VERSION,
|
|
22030
23056
|
generatedAt: Date.now(),
|
|
23057
|
+
...(payload.providerUsage ? { providerUsage: payload.providerUsage } : {}),
|
|
22031
23058
|
main: payload.main,
|
|
22032
23059
|
meta: payload.meta.map((chip) => chip.key === "git" ? { ...chip, value: nextBranch, title: `git branch: ${nextBranch}` } : chip),
|
|
22033
23060
|
visibility: payload.visibility,
|
|
@@ -23005,7 +24032,8 @@ async function applyFooterThinking(level) {
|
|
|
23005
24032
|
} else if (response.data?.level) {
|
|
23006
24033
|
const requested = response.data.requestedLevel;
|
|
23007
24034
|
const effective = response.data.level;
|
|
23008
|
-
|
|
24035
|
+
if (requested && requested !== effective) addEvent(`Thinking effort set to ${effective}: the active model does not support ${requested}.`, "warn");
|
|
24036
|
+
else addEvent(`Thinking effort set to ${effective}.`, "info");
|
|
23009
24037
|
}
|
|
23010
24038
|
await refreshState(tabContext);
|
|
23011
24039
|
} catch (error) {
|
|
@@ -23027,12 +24055,14 @@ function renderFooterThinkingPicker() {
|
|
|
23027
24055
|
const current = currentState?.pendingThinkingLevel || currentState?.thinkingLevel || "off";
|
|
23028
24056
|
for (const level of footerThinkingLevels()) {
|
|
23029
24057
|
const selected = current === level;
|
|
23030
|
-
const
|
|
24058
|
+
const supported = thinkingLevelSupportedByActiveModel(level);
|
|
24059
|
+
const button = make("button", `footer-model-option${selected ? " active" : ""}${supported ? "" : " unsupported"}`);
|
|
23031
24060
|
button.type = "button";
|
|
23032
24061
|
button.setAttribute("role", "option");
|
|
23033
24062
|
button.setAttribute("aria-selected", selected ? "true" : "false");
|
|
23034
|
-
button.title = `Set thinking effort to ${level}`;
|
|
23035
|
-
button.
|
|
24063
|
+
button.title = supported ? `Set thinking effort to ${level}` : `${level} is not supported by the active model`;
|
|
24064
|
+
button.disabled = !supported && !selected;
|
|
24065
|
+
button.append(make("span", "footer-model-option-main", supported ? footerThinkingLevelLabel(level) : `${footerThinkingLevelLabel(level)} · not supported`));
|
|
23036
24066
|
button.addEventListener("click", () => applyFooterThinking(level));
|
|
23037
24067
|
picker.append(button);
|
|
23038
24068
|
}
|
|
@@ -23221,25 +24251,25 @@ function currentFastPick() {
|
|
|
23221
24251
|
function updateAddFastPickButton() {
|
|
23222
24252
|
if (!pathFastPicksReady) {
|
|
23223
24253
|
elements.pathPickerAddFastPickButton.disabled = true;
|
|
23224
|
-
elements.pathPickerAddFastPickButton.textContent = "Loading
|
|
24254
|
+
elements.pathPickerAddFastPickButton.textContent = "Loading pinned folders…";
|
|
23225
24255
|
return;
|
|
23226
24256
|
}
|
|
23227
24257
|
const pick = currentFastPick();
|
|
23228
24258
|
const exists = !!pick && loadFastPicks().some((item) => item.cwd === pick.cwd);
|
|
23229
24259
|
elements.pathPickerAddFastPickButton.disabled = !pick || exists;
|
|
23230
|
-
elements.pathPickerAddFastPickButton.textContent = exists ? "
|
|
24260
|
+
elements.pathPickerAddFastPickButton.textContent = exists ? "Pinned" : "Pin this folder";
|
|
23231
24261
|
}
|
|
23232
24262
|
|
|
23233
24263
|
function renderFastPicks() {
|
|
23234
24264
|
const picks = loadFastPicks();
|
|
23235
24265
|
elements.pathPickerFastPicks.replaceChildren();
|
|
23236
24266
|
if (!pathFastPicksReady) {
|
|
23237
|
-
elements.pathPickerFastPicks.append(make("div", "path-picker-fast-picks-empty muted", "Loading
|
|
24267
|
+
elements.pathPickerFastPicks.append(make("div", "path-picker-fast-picks-empty muted", "Loading pinned folders…"));
|
|
23238
24268
|
updateAddFastPickButton();
|
|
23239
24269
|
return;
|
|
23240
24270
|
}
|
|
23241
24271
|
if (picks.length === 0) {
|
|
23242
|
-
elements.pathPickerFastPicks.append(make("div", "path-picker-fast-picks-empty muted", "No
|
|
24272
|
+
elements.pathPickerFastPicks.append(make("div", "path-picker-fast-picks-empty muted", "No pinned folders yet. Pin the folders you switch to often."));
|
|
23243
24273
|
updateAddFastPickButton();
|
|
23244
24274
|
return;
|
|
23245
24275
|
}
|
|
@@ -23247,7 +24277,7 @@ function renderFastPicks() {
|
|
|
23247
24277
|
for (const pick of picks) {
|
|
23248
24278
|
const item = make("span", "path-picker-fast-pick");
|
|
23249
24279
|
const jump = pathPickerButton(fastPickLabel(pick), pick.cwd, () => loadPathPickerDirectory(pick.cwd), "path-picker-fast-pick-button");
|
|
23250
|
-
const remove = pathPickerButton("×", `
|
|
24280
|
+
const remove = pathPickerButton("×", `Unpin ${pick.cwd}`, async () => {
|
|
23251
24281
|
await saveFastPicks(loadFastPicks().filter((item) => item.cwd !== pick.cwd));
|
|
23252
24282
|
}, "path-picker-fast-pick-remove");
|
|
23253
24283
|
item.append(jump, remove);
|
|
@@ -23405,6 +24435,7 @@ async function changeActiveTabCwd() {
|
|
|
23405
24435
|
}
|
|
23406
24436
|
|
|
23407
24437
|
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;
|
|
24438
|
+
if (activeFileViewer?.dirty && !(await confirmDiscardEdits({ what: "unsaved file edits", target: activeFileViewer.path }))) return;
|
|
23408
24439
|
|
|
23409
24440
|
saveActiveDraft();
|
|
23410
24441
|
if (isCurrentTabContext(tabContext)) {
|
|
@@ -23980,6 +25011,54 @@ function initializeCodexUsage() {
|
|
|
23980
25011
|
codexUsageRenderTimer = setInterval(renderCodexUsage, CODEX_USAGE_RENDER_TICK_MS);
|
|
23981
25012
|
}
|
|
23982
25013
|
|
|
25014
|
+
function claudeUsageWindowFromProvider(window, capturedAt) {
|
|
25015
|
+
if (!window) return null;
|
|
25016
|
+
const resetAt = Number(window.resetAt);
|
|
25017
|
+
const resetAfterSeconds = Number(window.resetAfterSeconds);
|
|
25018
|
+
const resetsAt = Number.isFinite(resetAt) && resetAt >= 0
|
|
25019
|
+
? new Date(resetAt).toISOString()
|
|
25020
|
+
: Number.isFinite(resetAfterSeconds) && resetAfterSeconds >= 0
|
|
25021
|
+
? new Date(capturedAt + resetAfterSeconds * 1000).toISOString()
|
|
25022
|
+
: undefined;
|
|
25023
|
+
return {
|
|
25024
|
+
label: window.label || "Usage window",
|
|
25025
|
+
usedPercent: window.usedPercent,
|
|
25026
|
+
...(Number.isFinite(window.windowMinutes) ? { windowMinutes: window.windowMinutes } : {}),
|
|
25027
|
+
...(resetsAt ? { resetsAt } : {}),
|
|
25028
|
+
};
|
|
25029
|
+
}
|
|
25030
|
+
|
|
25031
|
+
function claudeUsageFromGitFooterPayload(payload = parseGitFooterWebuiPayload()) {
|
|
25032
|
+
const providerUsage = payload?.providerUsage;
|
|
25033
|
+
if (providerUsage?.provider !== "anthropic") return null;
|
|
25034
|
+
const capturedAt = Number(providerUsage.capturedAt);
|
|
25035
|
+
if (!Number.isFinite(capturedAt) || capturedAt <= 0) return null;
|
|
25036
|
+
const windows = [providerUsage.primary, providerUsage.secondary]
|
|
25037
|
+
.map((window) => claudeUsageWindowFromProvider(window, capturedAt))
|
|
25038
|
+
.filter(Boolean);
|
|
25039
|
+
if (windows.length === 0) return null;
|
|
25040
|
+
return {
|
|
25041
|
+
available: true,
|
|
25042
|
+
providerId: "claude-code",
|
|
25043
|
+
source: "git-footer-status-provider-headers",
|
|
25044
|
+
fetchedAt: new Date(capturedAt).toISOString(),
|
|
25045
|
+
summary: "Live Anthropic subscription usage from provider response headers.",
|
|
25046
|
+
windows,
|
|
25047
|
+
activityTitle: "",
|
|
25048
|
+
activity: [],
|
|
25049
|
+
notes: [],
|
|
25050
|
+
};
|
|
25051
|
+
}
|
|
25052
|
+
|
|
25053
|
+
function syncClaudeUsageFromGitFooterPayload(payload = parseGitFooterWebuiPayload()) {
|
|
25054
|
+
const usage = claudeUsageFromGitFooterPayload(payload);
|
|
25055
|
+
if (!usage) return false;
|
|
25056
|
+
latestClaudeUsage = usage;
|
|
25057
|
+
claudeUsageError = null;
|
|
25058
|
+
renderClaudeUsage();
|
|
25059
|
+
return true;
|
|
25060
|
+
}
|
|
25061
|
+
|
|
23983
25062
|
function claudeUsageResetDate(window) {
|
|
23984
25063
|
const resetAt = window?.resetsAt ? new Date(window.resetsAt) : null;
|
|
23985
25064
|
if (resetAt && Number.isFinite(resetAt.getTime())) return resetAt;
|
|
@@ -24124,15 +25203,18 @@ function renderClaudeUsage() {
|
|
|
24124
25203
|
}
|
|
24125
25204
|
}
|
|
24126
25205
|
|
|
24127
|
-
async function refreshClaudeUsage() {
|
|
25206
|
+
async function refreshClaudeUsage({ forceCli = false } = {}) {
|
|
25207
|
+
if (!forceCli && syncClaudeUsageFromGitFooterPayload()) return;
|
|
24128
25208
|
if (claudeUsageLoading) return;
|
|
24129
25209
|
claudeUsageLoading = true;
|
|
24130
25210
|
renderClaudeUsage();
|
|
24131
25211
|
try {
|
|
24132
25212
|
const response = await api("/api/claude-usage", { scoped: false });
|
|
25213
|
+
if (!forceCli && syncClaudeUsageFromGitFooterPayload()) return;
|
|
24133
25214
|
latestClaudeUsage = response.data || null;
|
|
24134
25215
|
claudeUsageError = null;
|
|
24135
25216
|
} catch (error) {
|
|
25217
|
+
if (!forceCli && syncClaudeUsageFromGitFooterPayload()) return;
|
|
24136
25218
|
claudeUsageError = error;
|
|
24137
25219
|
} finally {
|
|
24138
25220
|
claudeUsageLoading = false;
|
|
@@ -26139,9 +27221,38 @@ async function reloadActiveTabForSubagentLaunchSlots() {
|
|
|
26139
27221
|
}
|
|
26140
27222
|
}
|
|
26141
27223
|
|
|
27224
|
+
// The launch-slot editor lives in a collapsed <details> inside the (usually collapsed) Subagents
|
|
27225
|
+
// section, yet its config payload is one of the largest boot requests (~290 KB uncompressed).
|
|
27226
|
+
// Load it lazily: only when the editor is actually visible, otherwise on first reveal.
|
|
27227
|
+
let subagentLaunchSlotConfigDeferred = false;
|
|
27228
|
+
|
|
27229
|
+
function subagentLaunchSlotsVisible() {
|
|
27230
|
+
const details = elements.subagentLaunchSlots;
|
|
27231
|
+
if (!details || !details.open) return false;
|
|
27232
|
+
const section = details.closest?.("[data-side-panel-section]");
|
|
27233
|
+
return !section || (!section.hidden && !section.classList.contains("collapsed"));
|
|
27234
|
+
}
|
|
27235
|
+
|
|
27236
|
+
function loadSubagentLaunchSlotConfigWhenVisible(options = {}) {
|
|
27237
|
+
if (subagentLaunchSlotsVisible()) {
|
|
27238
|
+
subagentLaunchSlotConfigDeferred = false;
|
|
27239
|
+
return loadSubagentLaunchSlotConfig(options);
|
|
27240
|
+
}
|
|
27241
|
+
subagentLaunchSlotConfigDeferred = true;
|
|
27242
|
+
renderSubagentLaunchSlots();
|
|
27243
|
+
return Promise.resolve();
|
|
27244
|
+
}
|
|
27245
|
+
|
|
27246
|
+
function revealSubagentLaunchSlotConfigIfDeferred() {
|
|
27247
|
+
if (!subagentLaunchSlotConfigDeferred || !subagentLaunchSlotsVisible()) return;
|
|
27248
|
+
subagentLaunchSlotConfigDeferred = false;
|
|
27249
|
+
loadSubagentLaunchSlotConfig().catch(() => {});
|
|
27250
|
+
}
|
|
27251
|
+
|
|
26142
27252
|
function initializeSubagentLaunchSlots() {
|
|
26143
27253
|
renderSubagentLaunchSlots();
|
|
26144
|
-
if (activeTabId)
|
|
27254
|
+
if (activeTabId) loadSubagentLaunchSlotConfigWhenVisible().catch(() => {});
|
|
27255
|
+
elements.subagentLaunchSlots?.addEventListener("toggle", () => revealSubagentLaunchSlotConfigIfDeferred());
|
|
26145
27256
|
}
|
|
26146
27257
|
|
|
26147
27258
|
function samplingParametersPath(tabId) {
|
|
@@ -26738,7 +27849,9 @@ function renderStatus() {
|
|
|
26738
27849
|
);
|
|
26739
27850
|
elements.stateDetails.append(overview, infoGrid);
|
|
26740
27851
|
|
|
26741
|
-
if (shownThinkingLevel
|
|
27852
|
+
if (controlsPendingThinkingValue && shownThinkingLevel === controlsPendingThinkingValue) setControlsPendingThinking("");
|
|
27853
|
+
if (shownThinkingLevel && !controlsPendingThinkingValue) elements.thinkingSelect.value = shownThinkingLevel;
|
|
27854
|
+
syncThinkingSelectSupport();
|
|
26742
27855
|
elements.compactButton.disabled = !!state?.isCompacting;
|
|
26743
27856
|
elements.compactButton.textContent = state?.isCompacting ? "Compacting…" : "Compact";
|
|
26744
27857
|
syncModelSelectToState();
|
|
@@ -28942,6 +30055,47 @@ function renderAppRunnerInputForm(run) {
|
|
|
28942
30055
|
return form;
|
|
28943
30056
|
}
|
|
28944
30057
|
|
|
30058
|
+
// Fast path for streaming app-runner output: same run, same lifecycle state, output only grew.
|
|
30059
|
+
function patchAppRunnerWidgetInPlace(tabId, previousRun, nextRun) {
|
|
30060
|
+
if (tabId !== activeTabId) return true; // not the visible tab; nothing to repaint here
|
|
30061
|
+
if (!previousRun || !nextRun || previousRun.id !== nextRun.id) return false;
|
|
30062
|
+
if (appRunnerIsRunning(previousRun) !== appRunnerIsRunning(nextRun)) return false;
|
|
30063
|
+
if ((previousRun.status || "") !== (nextRun.status || "") || Boolean(previousRun.truncated) !== Boolean(nextRun.truncated)) return false;
|
|
30064
|
+
const widget = elements.widgetArea?.querySelector(".app-runner-widget");
|
|
30065
|
+
const terminal = widget?.querySelector(".release-npm-terminal");
|
|
30066
|
+
if (!widget || !terminal) return false;
|
|
30067
|
+
const previousLines = appRunnerOutputLines(previousRun);
|
|
30068
|
+
const nextLines = appRunnerOutputLines(nextRun);
|
|
30069
|
+
if (nextLines.length < previousLines.length) return false;
|
|
30070
|
+
// The server keeps a bounded window; when it starts dropping the head, prefixes diverge.
|
|
30071
|
+
const sample = Math.min(previousLines.length, 3);
|
|
30072
|
+
for (let index = 0; index < sample; index += 1) {
|
|
30073
|
+
if (previousLines[previousLines.length - 1 - index] !== nextLines[previousLines.length - 1 - index]) return false;
|
|
30074
|
+
}
|
|
30075
|
+
const renderedCount = previousLines.length ? terminal.childElementCount : 0;
|
|
30076
|
+
if (renderedCount !== previousLines.length) return false;
|
|
30077
|
+
// A partial pending line is re-rendered as it grows: replace the last row when it changed.
|
|
30078
|
+
const pendingIndex = previousRun.pendingLine ? previousLines.length - 1 : -1;
|
|
30079
|
+
if (pendingIndex >= 0 && nextLines[pendingIndex] !== previousLines[pendingIndex]) {
|
|
30080
|
+
terminal.children[pendingIndex]?.remove();
|
|
30081
|
+
const rest = nextLines.slice(pendingIndex);
|
|
30082
|
+
if (!previousLines.length) terminal.replaceChildren();
|
|
30083
|
+
for (const line of rest) appendReleaseNpmTerminalLine(terminal, line);
|
|
30084
|
+
} else {
|
|
30085
|
+
if (!previousLines.length) terminal.replaceChildren();
|
|
30086
|
+
for (const line of nextLines.slice(previousLines.length)) appendReleaseNpmTerminalLine(terminal, line);
|
|
30087
|
+
}
|
|
30088
|
+
const count = widget.querySelector(".release-npm-stream-count");
|
|
30089
|
+
const lineCount = Math.max(nextRun.lineCount || 0, nextLines.length);
|
|
30090
|
+
if (count) count.textContent = `${lineCount} line${lineCount === 1 ? "" : "s"}`;
|
|
30091
|
+
const elapsedPill = widget.querySelector(".release-npm-pill.elapsed");
|
|
30092
|
+
const elapsed = appRunnerElapsedLabel(nextRun);
|
|
30093
|
+
if (elapsedPill && elapsed && elapsedPill.textContent !== elapsed) elapsedPill.textContent = elapsed;
|
|
30094
|
+
// Keep the terminal pinned to the bottom when it was already there.
|
|
30095
|
+
if (terminal.scrollHeight - terminal.scrollTop - terminal.clientHeight < 40) terminal.scrollTop = terminal.scrollHeight;
|
|
30096
|
+
return true;
|
|
30097
|
+
}
|
|
30098
|
+
|
|
28945
30099
|
function renderAppRunnerWidget() {
|
|
28946
30100
|
const data = activeAppRunnerData();
|
|
28947
30101
|
const run = data.activeRun;
|
|
@@ -30901,6 +32055,109 @@ function appendGitWorkflowOutput(text, { tabId = activeTabId } = {}) {
|
|
|
30901
32055
|
setGitWorkflow({ output: next.slice(-60000) }, { tabId });
|
|
30902
32056
|
}
|
|
30903
32057
|
|
|
32058
|
+
function gitWorkflowGenerationProfileText(profile) {
|
|
32059
|
+
const provider = String(profile?.provider || "").trim();
|
|
32060
|
+
const modelId = String(profile?.modelId || "").trim();
|
|
32061
|
+
const thinkingLevel = String(profile?.thinkingLevel || "").trim();
|
|
32062
|
+
if (!provider || !modelId) return "no model";
|
|
32063
|
+
return `${provider}/${modelId}${thinkingLevel ? ` at ${thinkingLevel} effort` : ""}`;
|
|
32064
|
+
}
|
|
32065
|
+
|
|
32066
|
+
function gitWorkflowFallbackConfigured(preferences) {
|
|
32067
|
+
return !!preferences?.generation?.fallback?.provider && !!preferences?.generation?.fallback?.modelId;
|
|
32068
|
+
}
|
|
32069
|
+
|
|
32070
|
+
function gitWorkflowConfiguredGenerationText(preferences) {
|
|
32071
|
+
const primary = gitWorkflowGenerationProfileText(preferences?.generation);
|
|
32072
|
+
if (!gitWorkflowFallbackConfigured(preferences)) return `Primary Git-writing model: ${primary}. No fallback is configured.`;
|
|
32073
|
+
return `Primary Git-writing model: ${primary}. Fallback after a final primary generation failure: ${gitWorkflowGenerationProfileText(preferences.generation.fallback)} (one attempt).`;
|
|
32074
|
+
}
|
|
32075
|
+
|
|
32076
|
+
function gitWorkflowGenerationAcceptedText(generation, subject) {
|
|
32077
|
+
const effective = gitWorkflowGenerationProfileText(generation?.generation);
|
|
32078
|
+
if (generation?.fallbackUsed === true) {
|
|
32079
|
+
const primary = gitWorkflowGenerationProfileText(generation.primaryGeneration);
|
|
32080
|
+
return `The primary Git-writing model ${primary} failed. ${subject} continued with the fallback ${effective}.`;
|
|
32081
|
+
}
|
|
32082
|
+
return `${subject} started with the primary Git-writing model ${effective}.`;
|
|
32083
|
+
}
|
|
32084
|
+
|
|
32085
|
+
function gitWorkflowFallbackEventMatchesPendingRequest(workflow, event) {
|
|
32086
|
+
if (!workflow?.active || workflow.generationKind !== event?.kind) return false;
|
|
32087
|
+
const expectedSteps = { commit: "generating", branch: "branchNaming", pr: "prGenerating" };
|
|
32088
|
+
return workflow.step === expectedSteps[event.kind] && !!String(event.generationId || "").trim();
|
|
32089
|
+
}
|
|
32090
|
+
|
|
32091
|
+
function gitWorkflowFallbackEventMatches(workflow, event) {
|
|
32092
|
+
if (!workflow?.generationAccepted || !gitWorkflowFallbackEventMatchesPendingRequest(workflow, event)) return false;
|
|
32093
|
+
return String(event.generationId || "").trim() === String(workflow.generationId || "").trim();
|
|
32094
|
+
}
|
|
32095
|
+
|
|
32096
|
+
function gitWorkflowFallbackLifecycleKey(workflow, event) {
|
|
32097
|
+
return [event.type, workflow.runId, event.kind, event.generationId || "", event.generation?.provider || "", event.generation?.modelId || ""].join(":");
|
|
32098
|
+
}
|
|
32099
|
+
|
|
32100
|
+
function applyGitWorkflowFallbackLifecycleEvent(workflow, event, tabId) {
|
|
32101
|
+
if (!gitWorkflowFallbackEventMatches(workflow, event)) return false;
|
|
32102
|
+
const keys = workflow.fallbackLifecycleKeys instanceof Set ? workflow.fallbackLifecycleKeys : new Set();
|
|
32103
|
+
const key = gitWorkflowFallbackLifecycleKey(workflow, event);
|
|
32104
|
+
if (keys.has(key)) return true;
|
|
32105
|
+
keys.add(key);
|
|
32106
|
+
const primary = gitWorkflowGenerationProfileText(event.primaryGeneration);
|
|
32107
|
+
const fallback = gitWorkflowGenerationProfileText(event.generation);
|
|
32108
|
+
if (event.type === "webui_git_workflow_generation_fallback_started") {
|
|
32109
|
+
setGitWorkflow({ fallbackStarted: true, fallbackLifecycleKeys: keys }, { tabId });
|
|
32110
|
+
appendGitWorkflowOutput(`The primary Git-writing model ${primary} failed${event.reason ? `: ${event.reason}` : "."} Generation continued with the fallback ${fallback}.`, { tabId });
|
|
32111
|
+
} else {
|
|
32112
|
+
setGitWorkflow({ fallbackLifecycleKeys: keys }, { tabId });
|
|
32113
|
+
appendGitWorkflowOutput(`The fallback Git-writing model ${fallback} also failed${event.error ? `: ${event.error}` : "."} No additional model retry will run.`, { tabId });
|
|
32114
|
+
}
|
|
32115
|
+
return true;
|
|
32116
|
+
}
|
|
32117
|
+
|
|
32118
|
+
function flushPendingGitWorkflowFallbackLifecycleEvents(tabId) {
|
|
32119
|
+
const workflow = gitWorkflowForTab(tabId, { create: false });
|
|
32120
|
+
if (!workflow?.generationAccepted) return;
|
|
32121
|
+
const pending = Array.isArray(workflow.pendingFallbackLifecycleEvents) ? workflow.pendingFallbackLifecycleEvents : [];
|
|
32122
|
+
setGitWorkflow({ pendingFallbackLifecycleEvents: [] }, { tabId });
|
|
32123
|
+
for (const event of pending) applyGitWorkflowFallbackLifecycleEvent(gitWorkflowForTab(tabId, { create: false }), event, tabId);
|
|
32124
|
+
}
|
|
32125
|
+
|
|
32126
|
+
function acceptGitWorkflowGenerationCorrelation(generation, tabId) {
|
|
32127
|
+
const workflow = gitWorkflowForTab(tabId, { create: false });
|
|
32128
|
+
const generationId = String(generation?.generationId || "").trim();
|
|
32129
|
+
if (!workflow || !generationId || generation?.kind !== workflow.generationKind) return false;
|
|
32130
|
+
setGitWorkflow({
|
|
32131
|
+
generationId,
|
|
32132
|
+
messageGenerationId: generation.kind === "commit" ? generationId : workflow.messageGenerationId,
|
|
32133
|
+
generationAccepted: true,
|
|
32134
|
+
}, { tabId });
|
|
32135
|
+
flushPendingGitWorkflowFallbackLifecycleEvents(tabId);
|
|
32136
|
+
if (generation.fallbackUsed === true) setGitWorkflow({ fallbackStarted: true }, { tabId });
|
|
32137
|
+
return true;
|
|
32138
|
+
}
|
|
32139
|
+
|
|
32140
|
+
function acceptGitWorkflowGenerationErrorCorrelation(error, tabId) {
|
|
32141
|
+
return acceptGitWorkflowGenerationCorrelation(error?.data?.gitWorkflowGeneration, tabId);
|
|
32142
|
+
}
|
|
32143
|
+
|
|
32144
|
+
function handleGitWorkflowFallbackLifecycleEvent(event) {
|
|
32145
|
+
if (!["webui_git_workflow_generation_fallback_started", "webui_git_workflow_generation_fallback_failed"].includes(event?.type)) return false;
|
|
32146
|
+
const tabId = event.tabId;
|
|
32147
|
+
const workflow = gitWorkflowForTab(tabId, { create: false });
|
|
32148
|
+
if (!tabId || !gitWorkflowFallbackEventMatchesPendingRequest(workflow, event)) return true;
|
|
32149
|
+
if (!workflow.generationAccepted) {
|
|
32150
|
+
const pending = Array.isArray(workflow.pendingFallbackLifecycleEvents) ? workflow.pendingFallbackLifecycleEvents : [];
|
|
32151
|
+
const key = gitWorkflowFallbackLifecycleKey(workflow, event);
|
|
32152
|
+
if (!pending.some((item) => gitWorkflowFallbackLifecycleKey(workflow, item) === key)) {
|
|
32153
|
+
setGitWorkflow({ pendingFallbackLifecycleEvents: [...pending, event].slice(-4) }, { tabId });
|
|
32154
|
+
}
|
|
32155
|
+
return true;
|
|
32156
|
+
}
|
|
32157
|
+
applyGitWorkflowFallbackLifecycleEvent(workflow, event, tabId);
|
|
32158
|
+
return true;
|
|
32159
|
+
}
|
|
32160
|
+
|
|
30904
32161
|
function formatGitCommandResult(result) {
|
|
30905
32162
|
if (!result) return "";
|
|
30906
32163
|
const lines = [`$ ${result.command || "git"}`];
|
|
@@ -31641,7 +32898,7 @@ function renderGitWorkflow() {
|
|
|
31641
32898
|
}
|
|
31642
32899
|
} else if (gitWorkflow.step === "generate") {
|
|
31643
32900
|
const commitInputButton = renderGitWorkflowManualCommitInput({ appendCommitButton: false });
|
|
31644
|
-
addGitWorkflowAction("
|
|
32901
|
+
addGitWorkflowAction("Generate commit message", () => runGitMessagePrompt(), "primary", false);
|
|
31645
32902
|
addGitWorkflowAction("Preview current message files", () => loadGitWorkflowMessage({ requireFresh: false }), "", false);
|
|
31646
32903
|
elements.gitWorkflowActions.append(commitInputButton);
|
|
31647
32904
|
} else if (gitWorkflow.step === "generating") {
|
|
@@ -31675,7 +32932,7 @@ function renderGitWorkflow() {
|
|
|
31675
32932
|
addGitWorkflowAction("Refresh PR description", () => loadGitWorkflowPr({ requireFresh: true }), "", false);
|
|
31676
32933
|
} else if (gitWorkflow.step === "prReview") {
|
|
31677
32934
|
addGitWorkflowAction("Create PR", () => createGitPrFromReview(), "primary", false);
|
|
31678
|
-
addGitWorkflowAction("Regenerate
|
|
32935
|
+
addGitWorkflowAction("Regenerate PR text", () => runGitPrPrompt(), "", false);
|
|
31679
32936
|
} else if (gitWorkflow.step === "prCreating") {
|
|
31680
32937
|
addGitWorkflowAction("Creating PR…", () => {}, "primary", true);
|
|
31681
32938
|
} else if (gitWorkflow.step === "done") {
|
|
@@ -31978,7 +33235,7 @@ async function startGitWorkflow(tabId = activeTabId, { skipSetup = false } = {})
|
|
|
31978
33235
|
step: "add",
|
|
31979
33236
|
process: "stage",
|
|
31980
33237
|
busy: false,
|
|
31981
|
-
output: `${gitWorkflowStagingReadyMessage(preferences)}\n\
|
|
33238
|
+
output: `${gitWorkflowStagingReadyMessage(preferences)}\n\n${gitWorkflowConfiguredGenerationText(preferences)} The active tab model and effort are restored after generation.`,
|
|
31982
33239
|
error: "",
|
|
31983
33240
|
githubUsername: "",
|
|
31984
33241
|
repoName: "",
|
|
@@ -31992,6 +33249,12 @@ async function startGitWorkflow(tabId = activeTabId, { skipSetup = false } = {})
|
|
|
31992
33249
|
...resetGitWorkflowManualCommitDefaultPatch(),
|
|
31993
33250
|
messageRequestedAt: 0,
|
|
31994
33251
|
messageGenerationId: "",
|
|
33252
|
+
generationId: "",
|
|
33253
|
+
generationKind: "",
|
|
33254
|
+
generationAccepted: false,
|
|
33255
|
+
fallbackStarted: false,
|
|
33256
|
+
fallbackLifecycleKeys: new Set(),
|
|
33257
|
+
pendingFallbackLifecycleEvents: [],
|
|
31995
33258
|
branchName: "",
|
|
31996
33259
|
branchNameRequestedAt: 0,
|
|
31997
33260
|
actionsDone: createGitWorkflowActionsDone(),
|
|
@@ -32136,7 +33399,7 @@ async function promptGitInitReadme(status, { runId, tabId }) {
|
|
|
32136
33399
|
try {
|
|
32137
33400
|
await api("/api/prompt", { method: "POST", body: { message: gitInitReadmePromptMessage({ stack, status, repoName }) }, tabId });
|
|
32138
33401
|
if (!isCurrentGitWorkflowRun(runId, tabId)) return;
|
|
32139
|
-
appendGitWorkflowOutput("README.md request accepted. Waiting for
|
|
33402
|
+
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
33403
|
if (isCurrentTabContext(tabContext)) scheduleRefreshState(120, tabContext);
|
|
32141
33404
|
setTimeout(() => {
|
|
32142
33405
|
const currentWorkflow = gitWorkflowForTab(tabId, { create: false });
|
|
@@ -32178,7 +33441,7 @@ async function promptGitInitGitignore(status, { runId, tabId }) {
|
|
|
32178
33441
|
try {
|
|
32179
33442
|
await api("/api/prompt", { method: "POST", body: { message: gitInitGitignorePromptMessage({ stack, status, repoName }) }, tabId });
|
|
32180
33443
|
if (!isCurrentGitWorkflowRun(runId, tabId)) return;
|
|
32181
|
-
appendGitWorkflowOutput(".gitignore request accepted. Waiting for
|
|
33444
|
+
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
33445
|
if (isCurrentTabContext(tabContext)) scheduleRefreshState(120, tabContext);
|
|
32183
33446
|
setTimeout(() => {
|
|
32184
33447
|
const currentWorkflow = gitWorkflowForTab(tabId, { create: false });
|
|
@@ -32432,16 +33695,21 @@ async function runGitMessagePrompt(tabId = gitWorkflowActionTabId()) {
|
|
|
32432
33695
|
error: "",
|
|
32433
33696
|
messageRequestedAt: requestedAt,
|
|
32434
33697
|
messageGenerationId: "",
|
|
32435
|
-
|
|
33698
|
+
generationId: "",
|
|
33699
|
+
generationKind: "commit",
|
|
33700
|
+
generationAccepted: false,
|
|
33701
|
+
fallbackStarted: false,
|
|
33702
|
+
fallbackLifecycleKeys: new Set(),
|
|
33703
|
+
pendingFallbackLifecycleEvents: [],
|
|
33704
|
+
output: "Asking Pi to write the commit message…\n\nCancel stops the request.",
|
|
32436
33705
|
}, { tabId });
|
|
32437
|
-
if (isCurrentTabContext(tabContext)) setRunIndicatorActivity("
|
|
33706
|
+
if (isCurrentTabContext(tabContext)) setRunIndicatorActivity("Generating commit message…");
|
|
32438
33707
|
try {
|
|
32439
33708
|
const generation = await gitWorkflowRequest("/api/git-workflow/generate", { body: { kind: "commit", ...(expectedStagedContentHash ? { expectedStagedContentHash } : {}) }, runId, tabId });
|
|
32440
33709
|
if (!generation || !isCurrentGitWorkflowRun(runId, tabId)) return;
|
|
32441
33710
|
const generationId = String(generation.generationId || "").trim();
|
|
32442
|
-
if (!
|
|
32443
|
-
|
|
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 });
|
|
33711
|
+
if (!acceptGitWorkflowGenerationCorrelation(generation, tabId)) throw new Error("The WebUI server did not return a commit-message generation ID. Restart Pi Web UI and regenerate.");
|
|
33712
|
+
appendGitWorkflowOutput(`${gitWorkflowGenerationAcceptedText(generation, "Commit message generation")} Waiting for Pi to finish, then the short and long messages will be loaded.`, { tabId });
|
|
32445
33713
|
if (isCurrentTabContext(tabContext)) scheduleRefreshState(120, tabContext);
|
|
32446
33714
|
setTimeout(() => {
|
|
32447
33715
|
const currentWorkflow = gitWorkflowForTab(tabId, { create: false });
|
|
@@ -32453,6 +33721,7 @@ async function runGitMessagePrompt(tabId = gitWorkflowActionTabId()) {
|
|
|
32453
33721
|
}, 2500);
|
|
32454
33722
|
} catch (error) {
|
|
32455
33723
|
if (isCurrentGitWorkflowRun(runId, tabId)) {
|
|
33724
|
+
acceptGitWorkflowGenerationErrorCorrelation(error, tabId);
|
|
32456
33725
|
if (isCurrentTabContext(tabContext)) clearRunIndicatorActivity();
|
|
32457
33726
|
failGitWorkflow(error, "generate", { tabId });
|
|
32458
33727
|
}
|
|
@@ -32597,13 +33866,20 @@ async function runGitBranchNamePrompt(tabId = gitWorkflowActionTabId()) {
|
|
|
32597
33866
|
busy: true,
|
|
32598
33867
|
error: "",
|
|
32599
33868
|
branchNameRequestedAt: requestedAt,
|
|
33869
|
+
generationId: "",
|
|
33870
|
+
generationKind: "branch",
|
|
33871
|
+
generationAccepted: false,
|
|
33872
|
+
fallbackStarted: false,
|
|
33873
|
+
fallbackLifecycleKeys: new Set(),
|
|
33874
|
+
pendingFallbackLifecycleEvents: [],
|
|
32600
33875
|
output: "Sending branch-name request to Pi.\n\nCancel will request Pi abort.",
|
|
32601
33876
|
}, { tabId });
|
|
32602
33877
|
if (isCurrentTabContext(tabContext)) setRunIndicatorActivity("Sending branch-name request to Pi…");
|
|
32603
33878
|
try {
|
|
32604
33879
|
const generation = await gitWorkflowRequest("/api/git-workflow/generate", { body: { kind: "branch", ...(expectedStagedContentHash ? { expectedStagedContentHash } : {}) }, runId, tabId });
|
|
32605
33880
|
if (!generation || !isCurrentGitWorkflowRun(runId, tabId)) return;
|
|
32606
|
-
|
|
33881
|
+
if (!acceptGitWorkflowGenerationCorrelation(generation, tabId)) throw new Error("The WebUI server did not return a branch-name generation ID. Restart Pi Web UI and regenerate.");
|
|
33882
|
+
appendGitWorkflowOutput(`${gitWorkflowGenerationAcceptedText(generation, "Branch-name generation")} Waiting for Pi to finish, then the branch name will be loaded.`, { tabId });
|
|
32607
33883
|
if (isCurrentTabContext(tabContext)) scheduleRefreshState(120, tabContext);
|
|
32608
33884
|
setTimeout(() => {
|
|
32609
33885
|
const currentWorkflow = gitWorkflowForTab(tabId, { create: false });
|
|
@@ -32614,6 +33890,7 @@ async function runGitBranchNamePrompt(tabId = gitWorkflowActionTabId()) {
|
|
|
32614
33890
|
}, 2500);
|
|
32615
33891
|
} catch (error) {
|
|
32616
33892
|
if (isCurrentGitWorkflowRun(runId, tabId)) {
|
|
33893
|
+
acceptGitWorkflowGenerationErrorCorrelation(error, tabId);
|
|
32617
33894
|
if (isCurrentTabContext(tabContext)) clearRunIndicatorActivity();
|
|
32618
33895
|
failGitWorkflow(error, "message", { tabId });
|
|
32619
33896
|
}
|
|
@@ -32623,8 +33900,11 @@ async function runGitBranchNamePrompt(tabId = gitWorkflowActionTabId()) {
|
|
|
32623
33900
|
async function loadGitWorkflowBranchName({ requireFresh = false, retries = 0, runId, tabId = activeTabId } = {}) {
|
|
32624
33901
|
const workflow = gitWorkflowForTab(tabId, { create: false });
|
|
32625
33902
|
const expectedRunId = runId ?? workflow?.runId;
|
|
33903
|
+
const generationId = requireFresh ? String(workflow?.generationId || "").trim() : "";
|
|
33904
|
+
if (requireFresh && !generationId) return;
|
|
32626
33905
|
try {
|
|
32627
|
-
const
|
|
33906
|
+
const query = generationId ? `?generationId=${encodeURIComponent(generationId)}` : "";
|
|
33907
|
+
const branchName = await gitWorkflowRequest(`/api/git-workflow/branch-name${query}`, { method: "GET", runId: expectedRunId, tabId });
|
|
32628
33908
|
if (!branchName) return;
|
|
32629
33909
|
const currentWorkflow = gitWorkflowForTab(tabId, { create: false });
|
|
32630
33910
|
if (!currentWorkflow) return;
|
|
@@ -32675,7 +33955,7 @@ async function createGitPrBranchWithSuggestion(suggestion, tabId = gitWorkflowAc
|
|
|
32675
33955
|
const workflow = gitWorkflowForTab(tabId, { create: false });
|
|
32676
33956
|
if (!workflow) return;
|
|
32677
33957
|
const sourceWorkflow = { ...workflow, actionsDone: createGitWorkflowActionsDone(workflow.actionsDone) };
|
|
32678
|
-
const proposedBranch =
|
|
33958
|
+
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
33959
|
if (expectedRunId !== undefined && !isCurrentGitWorkflowRun(expectedRunId, tabId)) return;
|
|
32680
33960
|
if (proposedBranch === null) {
|
|
32681
33961
|
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 });
|
|
@@ -32940,13 +34220,20 @@ async function runGitPrPrompt(tabId = gitWorkflowActionTabId(), { prefixOutput =
|
|
|
32940
34220
|
busy: true,
|
|
32941
34221
|
error: "",
|
|
32942
34222
|
prRequestedAt: requestedAt,
|
|
34223
|
+
generationId: "",
|
|
34224
|
+
generationKind: "pr",
|
|
34225
|
+
generationAccepted: false,
|
|
34226
|
+
fallbackStarted: false,
|
|
34227
|
+
fallbackLifecycleKeys: new Set(),
|
|
34228
|
+
pendingFallbackLifecycleEvents: [],
|
|
32943
34229
|
output: `${prefixOutput ? `${prefixOutput}\n\n` : ""}Sending /pr to Pi.\n\nCancel will request Pi abort.`,
|
|
32944
34230
|
}, { tabId });
|
|
32945
34231
|
if (isCurrentTabContext(tabContext)) setRunIndicatorActivity("Sending /pr to Pi…");
|
|
32946
34232
|
try {
|
|
32947
34233
|
const generation = await gitWorkflowRequest("/api/git-workflow/generate", { body: { kind: "pr" }, runId, tabId });
|
|
32948
34234
|
if (!generation || !isCurrentGitWorkflowRun(runId, tabId)) return;
|
|
32949
|
-
|
|
34235
|
+
if (!acceptGitWorkflowGenerationCorrelation(generation, tabId)) throw new Error("The WebUI server did not return a PR-text generation ID. Restart Pi Web UI and regenerate.");
|
|
34236
|
+
appendGitWorkflowOutput(`${gitWorkflowGenerationAcceptedText(generation, "PR text generation")} Waiting for Pi to finish, then the PR description will be loaded.`, { tabId });
|
|
32950
34237
|
if (isCurrentTabContext(tabContext)) scheduleRefreshState(120, tabContext);
|
|
32951
34238
|
setTimeout(() => {
|
|
32952
34239
|
const currentWorkflow = gitWorkflowForTab(tabId, { create: false });
|
|
@@ -32957,6 +34244,7 @@ async function runGitPrPrompt(tabId = gitWorkflowActionTabId(), { prefixOutput =
|
|
|
32957
34244
|
}, 2500);
|
|
32958
34245
|
} catch (error) {
|
|
32959
34246
|
if (isCurrentGitWorkflowRun(runId, tabId)) {
|
|
34247
|
+
acceptGitWorkflowGenerationErrorCorrelation(error, tabId);
|
|
32960
34248
|
if (isCurrentTabContext(tabContext)) clearRunIndicatorActivity();
|
|
32961
34249
|
failGitWorkflow(error, "push", { tabId });
|
|
32962
34250
|
}
|
|
@@ -32966,8 +34254,11 @@ async function runGitPrPrompt(tabId = gitWorkflowActionTabId(), { prefixOutput =
|
|
|
32966
34254
|
async function loadGitWorkflowPr({ requireFresh = false, retries = 0, runId, tabId = activeTabId } = {}) {
|
|
32967
34255
|
const workflow = gitWorkflowForTab(tabId, { create: false });
|
|
32968
34256
|
const expectedRunId = runId ?? workflow?.runId;
|
|
34257
|
+
const generationId = requireFresh ? String(workflow?.generationId || "").trim() : "";
|
|
34258
|
+
if (requireFresh && !generationId) return;
|
|
32969
34259
|
try {
|
|
32970
|
-
const
|
|
34260
|
+
const query = generationId ? `?generationId=${encodeURIComponent(generationId)}` : "";
|
|
34261
|
+
const pr = await gitWorkflowRequest(`/api/git-workflow/pr-description${query}`, { method: "GET", runId: expectedRunId, tabId });
|
|
32971
34262
|
if (!pr) return;
|
|
32972
34263
|
const currentWorkflow = gitWorkflowForTab(tabId, { create: false });
|
|
32973
34264
|
if (!currentWorkflow) return;
|
|
@@ -34064,9 +35355,22 @@ function appendInlineMarkdown(parent, text, depth = 0) {
|
|
|
34064
35355
|
continue;
|
|
34065
35356
|
}
|
|
34066
35357
|
}
|
|
35358
|
+
if (value[index] === "h" && (value.startsWith("http://", index) || value.startsWith("https://", index)) && !isMarkdownWordCharacter(value[index - 1])) {
|
|
35359
|
+
const match = value.slice(index).match(MARKDOWN_BARE_URL_REGEX);
|
|
35360
|
+
const href = match ? trimBareUrl(match[0]) : "";
|
|
35361
|
+
const safeHref = href ? safeMarkdownLinkHref(href) : "";
|
|
35362
|
+
if (safeHref) {
|
|
35363
|
+
const link = make("a");
|
|
35364
|
+
configureMarkdownLink(link, safeHref);
|
|
35365
|
+
link.textContent = href;
|
|
35366
|
+
parent.append(link);
|
|
35367
|
+
index += href.length;
|
|
35368
|
+
continue;
|
|
35369
|
+
}
|
|
35370
|
+
}
|
|
34067
35371
|
const strongMarker = value.startsWith("**", index) ? "**" : value.startsWith("__", index) ? "__" : "";
|
|
34068
|
-
if (strongMarker) {
|
|
34069
|
-
const end = value
|
|
35372
|
+
if (strongMarker && markdownCanOpenEmphasis(value, index, strongMarker)) {
|
|
35373
|
+
const end = findMarkdownEmphasisClose(value, index + 2, strongMarker);
|
|
34070
35374
|
if (end > index + 2) {
|
|
34071
35375
|
const strong = make("strong");
|
|
34072
35376
|
appendInlineMarkdown(strong, value.slice(index + 2, end), depth + 1);
|
|
@@ -34086,8 +35390,8 @@ function appendInlineMarkdown(parent, text, depth = 0) {
|
|
|
34086
35390
|
}
|
|
34087
35391
|
}
|
|
34088
35392
|
const emphasisMarker = value[index] === "*" || value[index] === "_" ? value[index] : "";
|
|
34089
|
-
if (emphasisMarker && value[index + 1] !== emphasisMarker) {
|
|
34090
|
-
const end = value
|
|
35393
|
+
if (emphasisMarker && value[index + 1] !== emphasisMarker && markdownCanOpenEmphasis(value, index, emphasisMarker)) {
|
|
35394
|
+
const end = findMarkdownEmphasisClose(value, index + 1, emphasisMarker);
|
|
34091
35395
|
if (end > index + 1) {
|
|
34092
35396
|
const em = make("em");
|
|
34093
35397
|
appendInlineMarkdown(em, value.slice(index + 1, end), depth + 1);
|
|
@@ -34096,13 +35400,59 @@ function appendInlineMarkdown(parent, text, depth = 0) {
|
|
|
34096
35400
|
continue;
|
|
34097
35401
|
}
|
|
34098
35402
|
}
|
|
34099
|
-
const nextSpecials = ["`", "[", "**", "__", "~~", "*", "_"]
|
|
35403
|
+
const nextSpecials = ["`", "[", "**", "__", "~~", "*", "_", "http://", "https://"]
|
|
34100
35404
|
.map((marker) => value.indexOf(marker, index + 1))
|
|
34101
35405
|
.filter((pos) => pos !== -1);
|
|
34102
35406
|
appendPlain(nextSpecials.length ? Math.min(...nextSpecials) : value.length);
|
|
34103
35407
|
}
|
|
34104
35408
|
}
|
|
34105
35409
|
|
|
35410
|
+
// CommonMark-ish flanking rules so identifiers such as snake_case_name, MAX_RETRY_COUNT or
|
|
35411
|
+
// 2*3*4 stop turning into emphasis. `_` never opens/closes inside a word; `*` may not open
|
|
35412
|
+
// before whitespace or close after whitespace.
|
|
35413
|
+
const MARKDOWN_BARE_URL_REGEX = /^https?:\/\/[^\s<>"'`]+/;
|
|
35414
|
+
|
|
35415
|
+
function isMarkdownWordCharacter(character) {
|
|
35416
|
+
return Boolean(character) && /[\p{L}\p{N}_]/u.test(character);
|
|
35417
|
+
}
|
|
35418
|
+
|
|
35419
|
+
function markdownCanOpenEmphasis(value, index, marker) {
|
|
35420
|
+
const after = value[index + marker.length];
|
|
35421
|
+
if (!after || /\s/.test(after)) return false;
|
|
35422
|
+
if (marker[0] === "_" && isMarkdownWordCharacter(value[index - 1])) return false;
|
|
35423
|
+
return true;
|
|
35424
|
+
}
|
|
35425
|
+
|
|
35426
|
+
function markdownCanCloseEmphasis(value, index, marker) {
|
|
35427
|
+
const before = value[index - 1];
|
|
35428
|
+
if (!before || /\s/.test(before)) return false;
|
|
35429
|
+
if (marker[0] === "_" && isMarkdownWordCharacter(value[index + marker.length])) return false;
|
|
35430
|
+
return true;
|
|
35431
|
+
}
|
|
35432
|
+
|
|
35433
|
+
function findMarkdownEmphasisClose(value, from, marker) {
|
|
35434
|
+
let cursor = from;
|
|
35435
|
+
while (cursor < value.length) {
|
|
35436
|
+
const candidate = value.indexOf(marker, cursor);
|
|
35437
|
+
if (candidate === -1) return -1;
|
|
35438
|
+
// Skip runs longer than the marker (e.g. "***" when looking for "*") — they are not a clean close.
|
|
35439
|
+
const runEnd = candidate + marker.length;
|
|
35440
|
+
const overlong = marker.length === 1 && value[runEnd] === marker;
|
|
35441
|
+
if (!overlong && markdownCanCloseEmphasis(value, candidate, marker)) return candidate;
|
|
35442
|
+
cursor = overlong ? runEnd + 1 : candidate + 1;
|
|
35443
|
+
}
|
|
35444
|
+
return -1;
|
|
35445
|
+
}
|
|
35446
|
+
|
|
35447
|
+
function trimBareUrl(url) {
|
|
35448
|
+
let text = String(url || "");
|
|
35449
|
+
// Trailing punctuation usually belongs to the sentence, not the link.
|
|
35450
|
+
while (/[.,;:!?'"]$/.test(text)) text = text.slice(0, -1);
|
|
35451
|
+
// Balance closing parentheses (Wikipedia-style links keep their own parens).
|
|
35452
|
+
while (text.endsWith(")") && (text.match(/\(/g) || []).length < (text.match(/\)/g) || []).length) text = text.slice(0, -1);
|
|
35453
|
+
return text;
|
|
35454
|
+
}
|
|
35455
|
+
|
|
34106
35456
|
function appendMarkdownParagraph(parent, lines) {
|
|
34107
35457
|
const paragraph = make("p");
|
|
34108
35458
|
lines.forEach((line, index) => {
|
|
@@ -34385,13 +35735,84 @@ function appendMarkdownTable(parent, rows) {
|
|
|
34385
35735
|
}
|
|
34386
35736
|
|
|
34387
35737
|
function markdownListMatch(line) {
|
|
34388
|
-
const unordered = line.match(
|
|
34389
|
-
if (unordered) return { ordered: false, text: unordered[1] };
|
|
34390
|
-
const ordered = line.match(
|
|
34391
|
-
if (ordered) return { ordered: true, start: Number(ordered[
|
|
35738
|
+
const unordered = line.match(/^(\s*)[-*+]\s+(.+)$/);
|
|
35739
|
+
if (unordered) return { ordered: false, text: unordered[2], indent: unordered[1].replace(/\t/g, " ").length, markerWidth: 2 };
|
|
35740
|
+
const ordered = line.match(/^(\s*)(\d+)[.)]\s+(.+)$/);
|
|
35741
|
+
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
35742
|
return null;
|
|
34393
35743
|
}
|
|
34394
35744
|
|
|
35745
|
+
// Builds nested lists from a block of list lines using indentation: a marker line indented at
|
|
35746
|
+
// least two columns deeper than the current list starts a child list of the previous item;
|
|
35747
|
+
// indented non-marker lines continue the previous item's text.
|
|
35748
|
+
function parseMarkdownListTree(blockLines) {
|
|
35749
|
+
const lists = [];
|
|
35750
|
+
const stack = [];
|
|
35751
|
+
let lastItem = null;
|
|
35752
|
+
const newList = (match) => ({ ordered: match.ordered, start: match.ordered ? match.start : null, items: [], indent: match.indent });
|
|
35753
|
+
for (const line of blockLines) {
|
|
35754
|
+
const match = markdownListMatch(line);
|
|
35755
|
+
if (!match) {
|
|
35756
|
+
if (lastItem && line.trim()) lastItem.text += `\n${line.trim()}`;
|
|
35757
|
+
continue;
|
|
35758
|
+
}
|
|
35759
|
+
while (stack.length && match.indent < stack[stack.length - 1].indent) stack.pop();
|
|
35760
|
+
let top = stack[stack.length - 1];
|
|
35761
|
+
if (!top) {
|
|
35762
|
+
top = newList(match);
|
|
35763
|
+
lists.push(top);
|
|
35764
|
+
stack.push(top);
|
|
35765
|
+
} else if (match.indent >= top.indent + 2 && lastItem && lastItem.list === top) {
|
|
35766
|
+
top = newList(match);
|
|
35767
|
+
lastItem.children.push(top);
|
|
35768
|
+
stack.push(top);
|
|
35769
|
+
} else if (top.ordered !== match.ordered) {
|
|
35770
|
+
stack.pop();
|
|
35771
|
+
top = newList(match);
|
|
35772
|
+
const parentList = stack[stack.length - 1];
|
|
35773
|
+
const owner = parentList?.items[parentList.items.length - 1];
|
|
35774
|
+
if (owner) owner.children.push(top);
|
|
35775
|
+
else lists.push(top);
|
|
35776
|
+
stack.push(top);
|
|
35777
|
+
}
|
|
35778
|
+
const item = { text: match.text, children: [], list: top };
|
|
35779
|
+
top.items.push(item);
|
|
35780
|
+
lastItem = item;
|
|
35781
|
+
}
|
|
35782
|
+
return lists;
|
|
35783
|
+
}
|
|
35784
|
+
|
|
35785
|
+
function appendMarkdownListTree(parent, tree) {
|
|
35786
|
+
const build = (list) => {
|
|
35787
|
+
const element = make(list.ordered ? "ol" : "ul", "markdown-list");
|
|
35788
|
+
if (list.ordered && Number.isFinite(list.start) && list.start > 1) element.start = list.start;
|
|
35789
|
+
for (const item of list.items) {
|
|
35790
|
+
const li = make("li");
|
|
35791
|
+
const [firstLine, ...moreLines] = String(item.text).split("\n");
|
|
35792
|
+
const task = firstLine.match(/^\[( |x|X|-)\]\s+(.+)$/);
|
|
35793
|
+
if (task) {
|
|
35794
|
+
li.classList.add("markdown-task-item");
|
|
35795
|
+
const checkbox = make("input", "markdown-task-checkbox");
|
|
35796
|
+
checkbox.type = "checkbox";
|
|
35797
|
+
checkbox.disabled = true;
|
|
35798
|
+
checkbox.checked = task[1].toLowerCase() === "x";
|
|
35799
|
+
li.append(checkbox);
|
|
35800
|
+
appendInlineMarkdown(li, task[2]);
|
|
35801
|
+
} else {
|
|
35802
|
+
appendInlineMarkdown(li, firstLine);
|
|
35803
|
+
}
|
|
35804
|
+
for (const extra of moreLines) {
|
|
35805
|
+
li.append(make("br"));
|
|
35806
|
+
appendInlineMarkdown(li, extra);
|
|
35807
|
+
}
|
|
35808
|
+
for (const child of item.children) li.append(build(child));
|
|
35809
|
+
element.append(li);
|
|
35810
|
+
}
|
|
35811
|
+
return element;
|
|
35812
|
+
};
|
|
35813
|
+
for (const list of tree) parent.append(build(list));
|
|
35814
|
+
}
|
|
35815
|
+
|
|
34395
35816
|
function appendMarkdownList(parent, items, ordered = false, start = null) {
|
|
34396
35817
|
const list = make(ordered ? "ol" : "ul", "markdown-list");
|
|
34397
35818
|
if (ordered && Number.isFinite(start) && start > 1) list.start = start;
|
|
@@ -34431,13 +35852,15 @@ function renderMarkdownInto(parent, text) {
|
|
|
34431
35852
|
index += 1;
|
|
34432
35853
|
continue;
|
|
34433
35854
|
}
|
|
34434
|
-
const fence = line.match(/^\s
|
|
35855
|
+
const fence = line.match(/^\s*(`{3,}|~{3,})\s*([\w.+-]*)\s*$/);
|
|
34435
35856
|
if (fence) {
|
|
34436
35857
|
flushParagraph();
|
|
34437
|
-
const
|
|
35858
|
+
const delimiter = fence[1];
|
|
35859
|
+
const language = fence[2] || "";
|
|
35860
|
+
const closingFence = new RegExp(`^\\s*${delimiter[0] === "~" ? "~" : "\`"}{${delimiter.length},}\\s*$`);
|
|
34438
35861
|
const codeLines = [];
|
|
34439
35862
|
index += 1;
|
|
34440
|
-
while (index < lines.length &&
|
|
35863
|
+
while (index < lines.length && !closingFence.test(lines[index])) {
|
|
34441
35864
|
codeLines.push(lines[index]);
|
|
34442
35865
|
index += 1;
|
|
34443
35866
|
}
|
|
@@ -34488,16 +35911,25 @@ function renderMarkdownInto(parent, text) {
|
|
|
34488
35911
|
const listMatch = markdownListMatch(line);
|
|
34489
35912
|
if (listMatch) {
|
|
34490
35913
|
flushParagraph();
|
|
34491
|
-
|
|
34492
|
-
|
|
34493
|
-
const
|
|
35914
|
+
// Collect the whole list block: marker lines plus indented continuation lines. A blank line
|
|
35915
|
+
// followed by an indented line stays in the list (loose list); anything else ends it.
|
|
35916
|
+
const blockLines = [];
|
|
34494
35917
|
while (index < lines.length) {
|
|
34495
|
-
const
|
|
34496
|
-
if (
|
|
34497
|
-
|
|
34498
|
-
|
|
35918
|
+
const current = lines[index];
|
|
35919
|
+
if (markdownListMatch(current) || (blockLines.length && /^\s{2,}\S/.test(current))) {
|
|
35920
|
+
blockLines.push(current);
|
|
35921
|
+
index += 1;
|
|
35922
|
+
continue;
|
|
35923
|
+
}
|
|
35924
|
+
if (!current.trim() && blockLines.length && index + 1 < lines.length && /^\s{2,}\S/.test(lines[index + 1]) && (markdownListMatch(lines[index + 1]) || true)) {
|
|
35925
|
+
blockLines.push("");
|
|
35926
|
+
index += 1;
|
|
35927
|
+
continue;
|
|
35928
|
+
}
|
|
35929
|
+
break;
|
|
34499
35930
|
}
|
|
34500
|
-
|
|
35931
|
+
while (blockLines.length && !blockLines[blockLines.length - 1].trim()) blockLines.pop();
|
|
35932
|
+
appendMarkdownListTree(parent, parseMarkdownListTree(blockLines));
|
|
34501
35933
|
continue;
|
|
34502
35934
|
}
|
|
34503
35935
|
paragraph.push(line);
|
|
@@ -34519,63 +35951,127 @@ function renderMarkdown(block, text) {
|
|
|
34519
35951
|
}
|
|
34520
35952
|
|
|
34521
35953
|
/**
|
|
34522
|
-
*
|
|
34523
|
-
*
|
|
34524
|
-
*
|
|
34525
|
-
*
|
|
34526
|
-
* open tail is re-parsed per streaming tick, keeping per-tick cost flat
|
|
34527
|
-
* instead of O(message length).
|
|
35954
|
+
* Streaming Markdown keeps the boundary automaton in transcript-owned
|
|
35955
|
+
* per-surface state. The scanner consumes only appended suffixes; open fences
|
|
35956
|
+
* and bounded-fallback tails reuse one mounted live subtree until an
|
|
35957
|
+
* authoritative close/completion render.
|
|
34528
35958
|
*/
|
|
34529
|
-
|
|
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;
|
|
35959
|
+
function streamingMarkdownStableBoundary(text, previousState, options) {
|
|
35960
|
+
return advanceStreamingMarkdownTail(previousState, text, options);
|
|
34548
35961
|
}
|
|
34549
35962
|
|
|
34550
35963
|
function clearStreamingMarkdownBlock(block) {
|
|
34551
35964
|
while (block.firstChild) block.firstChild.remove();
|
|
34552
35965
|
}
|
|
34553
35966
|
|
|
34554
|
-
function
|
|
34555
|
-
const
|
|
34556
|
-
|
|
34557
|
-
|
|
34558
|
-
|
|
35967
|
+
function streamingLiveCodeSource(tail, boundaryInfo) {
|
|
35968
|
+
const relativeOffset = Math.max(0, Number(boundaryInfo.fenceContentOffset) - Number(boundaryInfo.boundary));
|
|
35969
|
+
return String(tail || "").slice(relativeOffset).replace(/\n+$/g, "");
|
|
35970
|
+
}
|
|
35971
|
+
|
|
35972
|
+
function syncStreamingLiveCodeLanguage(wrapper, codeNode, language) {
|
|
35973
|
+
const value = String(language || "");
|
|
35974
|
+
let label = wrapper.querySelector(":scope > .markdown-code-language");
|
|
35975
|
+
if (value && !label) {
|
|
35976
|
+
label = make("div", "markdown-code-language");
|
|
35977
|
+
wrapper.prepend(label);
|
|
35978
|
+
}
|
|
35979
|
+
if (label) {
|
|
35980
|
+
label.textContent = value;
|
|
35981
|
+
if (!value) label.remove();
|
|
35982
|
+
}
|
|
35983
|
+
codeNode.className = value ? `language-${value.replace(/[^a-z0-9_-]/gi, "")}` : "";
|
|
34559
35984
|
}
|
|
34560
35985
|
|
|
34561
|
-
function
|
|
35986
|
+
function renderStreamingMarkdownLiveTail(parent, tail, boundaryInfo) {
|
|
35987
|
+
if (boundaryInfo.liveMode === "open-fence") {
|
|
35988
|
+
const wrapper = make("div", "markdown-code-block");
|
|
35989
|
+
const pre = make("pre", "code-block markdown-code");
|
|
35990
|
+
const codeNode = make("code");
|
|
35991
|
+
codeNode.append(document.createTextNode(streamingLiveCodeSource(tail, boundaryInfo)));
|
|
35992
|
+
pre.append(codeNode);
|
|
35993
|
+
wrapper.append(pre);
|
|
35994
|
+
syncStreamingLiveCodeLanguage(wrapper, codeNode, boundaryInfo.fenceLanguage);
|
|
35995
|
+
attachMarkdownCodeCopyButton(wrapper);
|
|
35996
|
+
parent.append(wrapper);
|
|
35997
|
+
return;
|
|
35998
|
+
}
|
|
35999
|
+
const paragraph = make("p", "streaming-markdown-plain-tail");
|
|
36000
|
+
paragraph.append(document.createTextNode(String(tail || "")));
|
|
36001
|
+
parent.append(paragraph);
|
|
36002
|
+
}
|
|
36003
|
+
|
|
36004
|
+
function appendStreamingMarkdownLiveTail(nodes, previousTail, tail, boundaryInfo) {
|
|
36005
|
+
const root = nodes.find((node) => node.nodeType === Node.ELEMENT_NODE);
|
|
36006
|
+
const textNode = boundaryInfo.liveMode === "open-fence"
|
|
36007
|
+
? root?.querySelector(":scope > pre.markdown-code > code")?.firstChild
|
|
36008
|
+
: root?.firstChild;
|
|
36009
|
+
const value = boundaryInfo.liveMode === "open-fence"
|
|
36010
|
+
? streamingLiveCodeSource(tail, boundaryInfo)
|
|
36011
|
+
: String(tail || "");
|
|
36012
|
+
if (!textNode || textNode.nodeType !== Node.TEXT_NODE) return;
|
|
36013
|
+
if (boundaryInfo.liveMode === "open-fence") {
|
|
36014
|
+
const codeNode = textNode.parentElement;
|
|
36015
|
+
syncStreamingLiveCodeLanguage(root, codeNode, boundaryInfo.fenceLanguage);
|
|
36016
|
+
}
|
|
36017
|
+
if (value.startsWith(textNode.data)) textNode.appendData(value.slice(textNode.data.length));
|
|
36018
|
+
else textNode.data = value;
|
|
36019
|
+
}
|
|
36020
|
+
|
|
36021
|
+
function renderStreamingMarkdown(block, text, { complete = false } = {}) {
|
|
34562
36022
|
const profileStart = streamIsolationDebugLedger ? performance.now() : 0;
|
|
34563
36023
|
const selectionSnapshot = captureChatTextSelection(block);
|
|
34564
36024
|
const bubble = block?.closest(".message");
|
|
34565
|
-
transcriptRenderer.reconcileMarkdownSurface({
|
|
36025
|
+
const result = transcriptRenderer.reconcileMarkdownSurface({
|
|
34566
36026
|
key: `stream:${bubble?.dataset?.transcriptMessageKey || bubble?.dataset?.itemKey || "assistant"}`,
|
|
34567
36027
|
surface: block,
|
|
34568
36028
|
messageKey: bubble?.dataset?.transcriptMessageKey || bubble?.dataset?.itemKey || "live:assistant",
|
|
34569
36029
|
kind: "assistant-final",
|
|
34570
36030
|
text,
|
|
36031
|
+
complete,
|
|
34571
36032
|
stableBoundary: streamingMarkdownStableBoundary,
|
|
34572
36033
|
renderInto: renderMarkdownInto,
|
|
36034
|
+
renderLiveTail: renderStreamingMarkdownLiveTail,
|
|
36035
|
+
appendLiveTail: appendStreamingMarkdownLiveTail,
|
|
34573
36036
|
});
|
|
34574
36037
|
restoreChatTextSelection(selectionSnapshot);
|
|
34575
36038
|
if (streamIsolationDebugLedger) {
|
|
34576
|
-
const
|
|
34577
|
-
recordStreamProfileDiagnostic({ type: "markdown-commit", ms: performance.now() - profileStart, textBytes: streamDiagnosticBytes(text), tailBytes, tailKind });
|
|
36039
|
+
const tailBytes = Math.max(0, streamDiagnosticBytes(text) - (Number(result.boundary) || 0) * 2);
|
|
36040
|
+
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" });
|
|
36041
|
+
}
|
|
36042
|
+
}
|
|
36043
|
+
|
|
36044
|
+
// Minimal lightbox: click an inline/transcript image (or attachment thumbnail) to view it large.
|
|
36045
|
+
let imageLightbox = null;
|
|
36046
|
+
function openImageLightbox(src, alt = "") {
|
|
36047
|
+
if (!src) return;
|
|
36048
|
+
if (!imageLightbox) {
|
|
36049
|
+
imageLightbox = document.createElement("dialog");
|
|
36050
|
+
imageLightbox.className = "image-lightbox";
|
|
36051
|
+
imageLightbox.setAttribute("aria-label", "Image preview");
|
|
36052
|
+
const figure = document.createElement("figure");
|
|
36053
|
+
const image = document.createElement("img");
|
|
36054
|
+
const caption = document.createElement("figcaption");
|
|
36055
|
+
const close = document.createElement("button");
|
|
36056
|
+
close.type = "button";
|
|
36057
|
+
close.className = "image-lightbox-close";
|
|
36058
|
+
close.textContent = "×";
|
|
36059
|
+
close.setAttribute("aria-label", "Close image preview");
|
|
36060
|
+
close.addEventListener("click", () => imageLightbox.close());
|
|
36061
|
+
imageLightbox.addEventListener("click", (event) => {
|
|
36062
|
+
if (event.target === imageLightbox) imageLightbox.close();
|
|
36063
|
+
});
|
|
36064
|
+
figure.append(image, caption);
|
|
36065
|
+
imageLightbox.append(close, figure);
|
|
36066
|
+
document.body.append(imageLightbox);
|
|
34578
36067
|
}
|
|
36068
|
+
const image = imageLightbox.querySelector("img");
|
|
36069
|
+
const caption = imageLightbox.querySelector("figcaption");
|
|
36070
|
+
image.src = src;
|
|
36071
|
+
image.alt = alt || "";
|
|
36072
|
+
caption.textContent = alt || "";
|
|
36073
|
+
caption.hidden = !alt;
|
|
36074
|
+
if (!imageLightbox.open) imageLightbox.showModal();
|
|
34579
36075
|
}
|
|
34580
36076
|
|
|
34581
36077
|
function appendImage(parent, part) {
|
|
@@ -34586,7 +36082,14 @@ function appendImage(parent, part) {
|
|
|
34586
36082
|
img.style.maxWidth = "100%";
|
|
34587
36083
|
img.style.borderRadius = "0.6rem";
|
|
34588
36084
|
img.src = `data:${part.mimeType || "image/png"};base64,${part.data || part.content || ""}`;
|
|
34589
|
-
|
|
36085
|
+
// Click/Enter opens the image at full size (transcript images used to be view-only thumbnails).
|
|
36086
|
+
const button = make("button", "image-block-button");
|
|
36087
|
+
button.type = "button";
|
|
36088
|
+
button.title = "Open image at full size";
|
|
36089
|
+
button.setAttribute("aria-label", "Open image at full size");
|
|
36090
|
+
button.append(img);
|
|
36091
|
+
button.addEventListener("click", () => openImageLightbox(img.src, "attached image"));
|
|
36092
|
+
wrapper.append(button);
|
|
34590
36093
|
parent.append(wrapper);
|
|
34591
36094
|
}
|
|
34592
36095
|
|
|
@@ -34664,7 +36167,7 @@ async function sendLiveActionFeedback(item) {
|
|
|
34664
36167
|
if (isCurrentTabContext(tabContext)) addEvent(`sent ${ACTION_FEEDBACK_REACTIONS[item.reaction]?.icon || "feedback"} action feedback as live steering`);
|
|
34665
36168
|
}
|
|
34666
36169
|
|
|
34667
|
-
function setActionFeedback(message, messageIndex, reaction) {
|
|
36170
|
+
async function setActionFeedback(message, messageIndex, reaction) {
|
|
34668
36171
|
const tabId = activeTabId;
|
|
34669
36172
|
if (!tabId || !ACTION_FEEDBACK_REACTIONS[reaction]) return;
|
|
34670
36173
|
const key = actionFeedbackKey(message, messageIndex);
|
|
@@ -34672,7 +36175,7 @@ function setActionFeedback(message, messageIndex, reaction) {
|
|
|
34672
36175
|
const existing = map.get(key);
|
|
34673
36176
|
let comment = existing?.comment || "";
|
|
34674
36177
|
if (reaction === "down") {
|
|
34675
|
-
const nextComment =
|
|
36178
|
+
const nextComment = await appPromptText({ title: "What should Pi avoid?", summary: "Optional note sent with the thumbs-down feedback.", defaultValue: comment, confirmLabel: "Send feedback" });
|
|
34676
36179
|
if (nextComment === null) return;
|
|
34677
36180
|
comment = nextComment.trim();
|
|
34678
36181
|
}
|
|
@@ -34769,7 +36272,7 @@ function renderActionFeedbackControls(bubble, message, messageIndex) {
|
|
|
34769
36272
|
button.addEventListener("click", (event) => {
|
|
34770
36273
|
event.preventDefault();
|
|
34771
36274
|
event.stopPropagation();
|
|
34772
|
-
setActionFeedback(message, messageIndex, reaction);
|
|
36275
|
+
setActionFeedback(message, messageIndex, reaction).catch((error) => addEvent(error.message || String(error), "error"));
|
|
34773
36276
|
});
|
|
34774
36277
|
controls.append(button);
|
|
34775
36278
|
}
|
|
@@ -34875,7 +36378,7 @@ function renderContent(parent, content, { markdown = false } = {}) {
|
|
|
34875
36378
|
|
|
34876
36379
|
function messageTitle(message) {
|
|
34877
36380
|
if (message.role === "assistant") return message.title || "final output";
|
|
34878
|
-
if (message.title) return message.title;
|
|
36381
|
+
if (message.title) return message.repeatCount > 1 ? `${message.title} (×${message.repeatCount})` : message.title;
|
|
34879
36382
|
if (message.role === "thinking") return "thinking";
|
|
34880
36383
|
if (message.role === "toolCall") return `tool call: ${message.toolName || "unknown"}`;
|
|
34881
36384
|
if (message.role === "toolExecution") return toolExecutionTitle(message);
|
|
@@ -34920,7 +36423,7 @@ function visibleThinkingText(text) {
|
|
|
34920
36423
|
return value;
|
|
34921
36424
|
}
|
|
34922
36425
|
|
|
34923
|
-
function renderThinkingMarkdown(block, text) {
|
|
36426
|
+
function renderThinkingMarkdown(block, text, { complete = false } = {}) {
|
|
34924
36427
|
if (!block) return;
|
|
34925
36428
|
block._rawThinkingText = String(text || "");
|
|
34926
36429
|
const selectionSnapshot = captureChatTextSelection(block);
|
|
@@ -34931,8 +36434,11 @@ function renderThinkingMarkdown(block, text) {
|
|
|
34931
36434
|
messageKey: bubble?.dataset?.transcriptMessageKey || bubble?.dataset?.itemKey || "live:thinking",
|
|
34932
36435
|
kind: "assistant-thinking",
|
|
34933
36436
|
text: block._rawThinkingText,
|
|
36437
|
+
complete,
|
|
34934
36438
|
stableBoundary: streamingMarkdownStableBoundary,
|
|
34935
36439
|
renderInto: renderMarkdownInto,
|
|
36440
|
+
renderLiveTail: renderStreamingMarkdownLiveTail,
|
|
36441
|
+
appendLiveTail: appendStreamingMarkdownLiveTail,
|
|
34936
36442
|
});
|
|
34937
36443
|
restoreChatTextSelection(selectionSnapshot);
|
|
34938
36444
|
}
|
|
@@ -35123,8 +36629,44 @@ function assistantFinalOutputPart(part) {
|
|
|
35123
36629
|
return null;
|
|
35124
36630
|
}
|
|
35125
36631
|
|
|
36632
|
+
function latestPersistedAssistantFailureTimestamp(messages = latestMessages) {
|
|
36633
|
+
const lastUserIndex = (messages || []).findLastIndex((message) => message?.role === "user");
|
|
36634
|
+
for (let index = (messages || []).length - 1; index > lastUserIndex; index -= 1) {
|
|
36635
|
+
const message = messages[index];
|
|
36636
|
+
if (message?.role === "assistant" && message.stopReason === "error") return messageTimestampMs(message) || Date.now();
|
|
36637
|
+
}
|
|
36638
|
+
return 0;
|
|
36639
|
+
}
|
|
36640
|
+
|
|
36641
|
+
function assistantFailureDisplayMessage(message, base) {
|
|
36642
|
+
if (message?.stopReason === "error") {
|
|
36643
|
+
return {
|
|
36644
|
+
...base,
|
|
36645
|
+
role: "error",
|
|
36646
|
+
title: "assistant error",
|
|
36647
|
+
level: "error",
|
|
36648
|
+
content: describeAssistantFailure(String(message.errorMessage || "The assistant request failed without an error message.").trim()),
|
|
36649
|
+
persistedFailure: true,
|
|
36650
|
+
actions: assistantFailureActions(),
|
|
36651
|
+
};
|
|
36652
|
+
}
|
|
36653
|
+
if (message?.stopReason === "aborted") {
|
|
36654
|
+
return { ...base, role: "native", title: "aborted", level: "warn", content: "This turn was aborted before it finished.", persistedFailure: true };
|
|
36655
|
+
}
|
|
36656
|
+
return null;
|
|
36657
|
+
}
|
|
36658
|
+
|
|
35126
36659
|
function assistantDisplayMessages(message) {
|
|
35127
36660
|
if (message?.role !== "assistant") return [message];
|
|
36661
|
+
const failure = assistantFailureDisplayMessage(message, { timestamp: message.timestamp });
|
|
36662
|
+
if (failure) {
|
|
36663
|
+
const rest = assistantDisplayMessagesWithoutFailure({ ...message, stopReason: undefined });
|
|
36664
|
+
return [...rest, failure];
|
|
36665
|
+
}
|
|
36666
|
+
return assistantDisplayMessagesWithoutFailure(message);
|
|
36667
|
+
}
|
|
36668
|
+
|
|
36669
|
+
function assistantDisplayMessagesWithoutFailure(message) {
|
|
35128
36670
|
const base = { timestamp: message.timestamp };
|
|
35129
36671
|
const content = message.content;
|
|
35130
36672
|
if (typeof content === "string") {
|
|
@@ -35662,7 +37204,6 @@ function cleanupLiveToolRunsForMessages(messages = latestMessages) {
|
|
|
35662
37204
|
for (const id of liveToolRuns.keys()) {
|
|
35663
37205
|
if (results.has(id)) {
|
|
35664
37206
|
liveToolRuns.delete(id);
|
|
35665
|
-
cancelQueuedLiveToolRunRender(id);
|
|
35666
37207
|
}
|
|
35667
37208
|
}
|
|
35668
37209
|
}
|
|
@@ -36460,6 +38001,11 @@ function handleToolExecutionEnd(event) {
|
|
|
36460
38001
|
if (run) renderLiveToolRun(run);
|
|
36461
38002
|
}
|
|
36462
38003
|
|
|
38004
|
+
function thinkingDisclosurePreviewText(message, charLimit = 140) {
|
|
38005
|
+
const raw = visibleThinkingText(message?.thinking || textFromContent(message?.content));
|
|
38006
|
+
return speakableTextFromMarkdown(raw).slice(0, Math.max(0, charLimit));
|
|
38007
|
+
}
|
|
38008
|
+
|
|
36463
38009
|
function toolResultPreviewText(message, lineLimit = 10) {
|
|
36464
38010
|
const text = textFromContent(message?.content).replace(/\s+$/g, "");
|
|
36465
38011
|
if (!text) return "(empty tool result)";
|
|
@@ -36563,7 +38109,8 @@ function createMessageBubble(message, { streaming = false, messageIndex = -1, tr
|
|
|
36563
38109
|
if (role === "user") bubble.dataset.userPrompt = "true";
|
|
36564
38110
|
}
|
|
36565
38111
|
if (itemKey) bubble.dataset.itemKey = itemKey;
|
|
36566
|
-
const
|
|
38112
|
+
const collapsibleThinking = !streaming && !compactTranscript && message.role === "thinking" && !compactThinkingAggregate;
|
|
38113
|
+
const isCollapsibleOutput = compactThinkingAggregate || collapsibleThinking || (!streaming && (message.role === "toolResult" || message.role === "bashExecution" || message.role === "compactionSummary"));
|
|
36567
38114
|
|
|
36568
38115
|
const hideMessageHeader = message.role === "assistant" && !isCollapsibleOutput;
|
|
36569
38116
|
if (hideMessageHeader) bubble.setAttribute("aria-label", messageTitle(message));
|
|
@@ -36605,6 +38152,15 @@ function createMessageBubble(message, { streaming = false, messageIndex = -1, tr
|
|
|
36605
38152
|
const defaultExpanded = message.compactThinkingDefaultExpanded === true;
|
|
36606
38153
|
details.open = compactThinkingDisclosureExpanded(message.compactThinkingKey, defaultExpanded);
|
|
36607
38154
|
if (message.compactThinkingKey) details.addEventListener("toggle", () => setCompactThinkingDisclosureExpanded(message.compactThinkingKey, details.open, defaultExpanded));
|
|
38155
|
+
} else if (collapsibleThinking) {
|
|
38156
|
+
// Persisted thinking starts folded (a high-effort model can dominate the transcript with it);
|
|
38157
|
+
// each block remembers its own state per tab, like the compact-mode aggregate does.
|
|
38158
|
+
const thinkingKey = `thinking:${itemKey || messageIndex}:${segmentId}`;
|
|
38159
|
+
details.classList.add("thinking-disclosure");
|
|
38160
|
+
details.open = compactThinkingDisclosureExpanded(thinkingKey, false);
|
|
38161
|
+
details.addEventListener("toggle", () => setCompactThinkingDisclosureExpanded(thinkingKey, details.open, false));
|
|
38162
|
+
const previewText = thinkingDisclosurePreviewText(message);
|
|
38163
|
+
if (previewText) header.append(make("span", "thinking-disclosure-preview", previewText));
|
|
36608
38164
|
} else if (shouldOpenMessageCollapseByDefault(message)) details.open = true;
|
|
36609
38165
|
details.append(header, body);
|
|
36610
38166
|
bubble.append(details);
|
|
@@ -36618,6 +38174,22 @@ function createMessageBubble(message, { streaming = false, messageIndex = -1, tr
|
|
|
36618
38174
|
} else {
|
|
36619
38175
|
bubble.append(header, body);
|
|
36620
38176
|
}
|
|
38177
|
+
if (Array.isArray(message.actions) && message.actions.length) {
|
|
38178
|
+
const actions = make("div", "message-actions");
|
|
38179
|
+
for (const action of message.actions) {
|
|
38180
|
+
if (!action?.label) continue;
|
|
38181
|
+
const button = make("button", `message-action-button${action.primary ? " primary" : ""}`, action.label);
|
|
38182
|
+
button.type = "button";
|
|
38183
|
+
if (action.title) button.title = action.title;
|
|
38184
|
+
button.addEventListener("click", (event) => {
|
|
38185
|
+
event.preventDefault();
|
|
38186
|
+
event.stopPropagation();
|
|
38187
|
+
Promise.resolve(action.run?.()).catch((error) => addEvent(error?.message || String(error), "error"));
|
|
38188
|
+
});
|
|
38189
|
+
actions.append(button);
|
|
38190
|
+
}
|
|
38191
|
+
if (actions.childElementCount) (bubble.querySelector(":scope > .message-body") || bubble).after(actions);
|
|
38192
|
+
}
|
|
36621
38193
|
ownTranscriptBubble(bubble, body, message, { itemKey, streaming, transient, segmentId });
|
|
36622
38194
|
ensureToolInteractionDelegation();
|
|
36623
38195
|
if (message.role !== "workflowStatusStack") attachMessageCopyButton(bubble, message, body);
|
|
@@ -36713,7 +38285,7 @@ function appendTranscriptMessage(message, { streaming = false, messageIndex = -1
|
|
|
36713
38285
|
if (displayMessage.role === "toolCall" && displayMessage.toolCallId) {
|
|
36714
38286
|
transcriptMessage = toolExecutionMessageFromCall(displayMessage);
|
|
36715
38287
|
}
|
|
36716
|
-
if (compactTranscript && transcriptMessage.role !== "assistant") return;
|
|
38288
|
+
if (compactTranscript && transcriptMessage.role !== "assistant" && !transcriptMessage.persistedFailure) return;
|
|
36717
38289
|
if (transcriptMessage.role === "thinking" && !thinkingOutputVisible) return;
|
|
36718
38290
|
const created = appendMessage(transcriptMessage, {
|
|
36719
38291
|
streaming: false,
|
|
@@ -36848,7 +38420,11 @@ function createRunIndicatorBubble() {
|
|
|
36848
38420
|
pulse.setAttribute("aria-hidden", "true");
|
|
36849
38421
|
runIndicatorText = make("span", "run-indicator-text");
|
|
36850
38422
|
runIndicatorMeta = make("span", "run-indicator-meta");
|
|
36851
|
-
|
|
38423
|
+
// Elapsed time ticks every second; keep it out of the accessibility tree so the polite live
|
|
38424
|
+
// region only announces real activity changes, not "run time 12s / 13s / …".
|
|
38425
|
+
runIndicatorElapsed = make("span", "run-indicator-elapsed");
|
|
38426
|
+
runIndicatorElapsed.setAttribute("aria-hidden", "true");
|
|
38427
|
+
row.append(pulse, runIndicatorText, runIndicatorMeta, runIndicatorElapsed);
|
|
36852
38428
|
body.append(row);
|
|
36853
38429
|
runIndicatorBubble.append(body);
|
|
36854
38430
|
}
|
|
@@ -36865,8 +38441,10 @@ function updateRunIndicatorBubble() {
|
|
|
36865
38441
|
const headline = runIndicatorHeadline();
|
|
36866
38442
|
if (runIndicatorText.textContent !== headline) runIndicatorText.textContent = headline;
|
|
36867
38443
|
const detail = runIndicatorDetail();
|
|
36868
|
-
const meta =
|
|
38444
|
+
const meta = detail;
|
|
36869
38445
|
if (runIndicatorMeta.textContent !== meta) runIndicatorMeta.textContent = meta;
|
|
38446
|
+
const elapsed = runIndicatorShowsElapsed() ? ` · run time ${formatRunIndicatorElapsed()}` : "";
|
|
38447
|
+
if (runIndicatorElapsed && runIndicatorElapsed.textContent !== elapsed) runIndicatorElapsed.textContent = elapsed;
|
|
36870
38448
|
}
|
|
36871
38449
|
|
|
36872
38450
|
function removeRunIndicatorBubble() {
|
|
@@ -36875,6 +38453,7 @@ function removeRunIndicatorBubble() {
|
|
|
36875
38453
|
runIndicatorBubble = null;
|
|
36876
38454
|
runIndicatorText = null;
|
|
36877
38455
|
runIndicatorMeta = null;
|
|
38456
|
+
runIndicatorElapsed = null;
|
|
36878
38457
|
}
|
|
36879
38458
|
|
|
36880
38459
|
function renderRunIndicator({ scroll = false } = {}) {
|
|
@@ -37159,7 +38738,11 @@ function orderedTranscriptItems() {
|
|
|
37159
38738
|
if (resultId && assistantToolCallIds.has(resultId)) return;
|
|
37160
38739
|
items.push({ message, messageIndex: index, transient: false, timestampMs: messageTimestampMs(message), order: index });
|
|
37161
38740
|
});
|
|
38741
|
+
const persistedFailureAt = latestPersistedAssistantFailureTimestamp(latestMessages);
|
|
37162
38742
|
transientMessages.forEach((message, index) => {
|
|
38743
|
+
// Once Pi's authoritative transcript carries the failed assistant turn (stopReason error), the
|
|
38744
|
+
// live "Assistant error" cards for the same failure are redundant.
|
|
38745
|
+
if (persistedFailureAt && message?.role === "error" && message?.title === "Assistant error" && messageTimestampMs(message) <= persistedFailureAt + 5000) return;
|
|
37163
38746
|
items.push({ message, messageIndex: index, transient: true, timestampMs: messageTimestampMs(message), order: latestMessages.length + index });
|
|
37164
38747
|
});
|
|
37165
38748
|
let liveOrder = latestMessages.length + transientMessages.length;
|
|
@@ -37590,7 +39173,11 @@ function applyNativeSlashCommandEffects(response, message, tabContext = activeTa
|
|
|
37590
39173
|
if (warning) addEvent(String(warning), "warn");
|
|
37591
39174
|
}
|
|
37592
39175
|
for (const toast of data.toasts || []) {
|
|
37593
|
-
if (toast?.message)
|
|
39176
|
+
if (!toast?.message) continue;
|
|
39177
|
+
const level = toast.level || "info";
|
|
39178
|
+
addEvent(String(toast.message), level);
|
|
39179
|
+
// Extensions asked for a toast explicitly; info/success levels are not auto-surfaced by addEvent.
|
|
39180
|
+
if (level !== "warn" && level !== "error") showNoticeToast(String(toast.message), level);
|
|
37594
39181
|
}
|
|
37595
39182
|
|
|
37596
39183
|
if (data.copyText) {
|
|
@@ -37646,12 +39233,29 @@ function applyNativeSlashCommandEffects(response, message, tabContext = activeTa
|
|
|
37646
39233
|
if (refresh.includes("themes")) initializeThemes().catch((error) => addEvent(error.message || String(error), "error"));
|
|
37647
39234
|
}
|
|
37648
39235
|
|
|
37649
|
-
function addTransientMessage({ role = "notice", title, content, level = "info", ...details }) {
|
|
39236
|
+
function addTransientMessage({ role = "notice", title, content, level = "info", key = "", ...details }) {
|
|
39237
|
+
// `key` upserts (e.g. one live "auto retry" card that counts down instead of one card per
|
|
39238
|
+
// attempt); identical consecutive error/warn cards collapse into one with a repeat counter.
|
|
39239
|
+
const last = transientMessages[transientMessages.length - 1];
|
|
39240
|
+
if (key) {
|
|
39241
|
+
const existing = transientMessages.findLast((message) => message?.key === key);
|
|
39242
|
+
if (existing) {
|
|
39243
|
+
Object.assign(existing, { role, title, level, content, ...details, timestamp: Date.now() });
|
|
39244
|
+
renderAllMessages();
|
|
39245
|
+
return;
|
|
39246
|
+
}
|
|
39247
|
+
} 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) {
|
|
39248
|
+
last.repeatCount = (last.repeatCount || 1) + 1;
|
|
39249
|
+
last.timestamp = Date.now();
|
|
39250
|
+
renderAllMessages();
|
|
39251
|
+
return;
|
|
39252
|
+
}
|
|
37650
39253
|
transientMessages.push({
|
|
37651
39254
|
role,
|
|
37652
39255
|
title,
|
|
37653
39256
|
level,
|
|
37654
39257
|
content,
|
|
39258
|
+
key,
|
|
37655
39259
|
...details,
|
|
37656
39260
|
timestamp: Date.now(),
|
|
37657
39261
|
});
|
|
@@ -37659,11 +39263,37 @@ function addTransientMessage({ role = "notice", title, content, level = "info",
|
|
|
37659
39263
|
renderAllMessages();
|
|
37660
39264
|
}
|
|
37661
39265
|
|
|
37662
|
-
function surfaceRuntimeDiagnostic(title, content, level = "error") {
|
|
39266
|
+
function surfaceRuntimeDiagnostic(title, content, level = "error", { actions = null } = {}) {
|
|
37663
39267
|
const message = String(content || "").trim();
|
|
37664
39268
|
if (!message) return;
|
|
37665
|
-
addEvent(message, level);
|
|
37666
|
-
addTransientMessage({ role: level === "error" ? "error" : "warn", title, content: message, level });
|
|
39269
|
+
addEvent(message, level, { notify: false }); // the transcript card below is the visible feedback
|
|
39270
|
+
addTransientMessage({ role: level === "error" ? "error" : "warn", title, content: message, level, ...(actions ? { actions } : {}) });
|
|
39271
|
+
}
|
|
39272
|
+
|
|
39273
|
+
// Recovery actions for a failed assistant turn: retry the last prompt as-is, or pick another model.
|
|
39274
|
+
function assistantFailureActions(tabId = activeTabId) {
|
|
39275
|
+
const entry = tabId ? lastUserPromptByTab.get(tabId) : null;
|
|
39276
|
+
const actions = [];
|
|
39277
|
+
if (entry?.text) {
|
|
39278
|
+
actions.push({
|
|
39279
|
+
label: "Retry",
|
|
39280
|
+
title: "Send the last prompt again",
|
|
39281
|
+
primary: true,
|
|
39282
|
+
run: () => sendPrompt("prompt", entry.text, { targetTabId: tabId }),
|
|
39283
|
+
});
|
|
39284
|
+
}
|
|
39285
|
+
actions.push({ label: "Change model…", title: "Choose another model for this tab (Ctrl/Cmd+L)", run: () => openNativeModelSelector() });
|
|
39286
|
+
return actions;
|
|
39287
|
+
}
|
|
39288
|
+
|
|
39289
|
+
// Provider errors are terse ("Connection error."). Add the model/provider so the user knows what
|
|
39290
|
+
// failed and where to look (LM Studio not running, wrong base URL, expired key, …).
|
|
39291
|
+
function describeAssistantFailure(message, state = currentState) {
|
|
39292
|
+
const model = state?.model;
|
|
39293
|
+
const text = String(message || "").trim();
|
|
39294
|
+
if (!model?.provider) return text;
|
|
39295
|
+
const where = `${model.provider}/${model.id || ""}`.replace(/\/$/, "");
|
|
39296
|
+
return text.includes(where) ? text : `${text} (model ${where})`;
|
|
37667
39297
|
}
|
|
37668
39298
|
|
|
37669
39299
|
function stderrDiagnosticLevel(content) {
|
|
@@ -37896,7 +39526,40 @@ async function sendBtwPromptFromButton() {
|
|
|
37896
39526
|
await sendBtwQuestion(question, { clearComposerDraft: true });
|
|
37897
39527
|
}
|
|
37898
39528
|
|
|
39529
|
+
// Hover/focus-opened composer menus need an explicit "dismissed" state: after Escape or an item
|
|
39530
|
+
// choice the pointer usually still rests on the trigger (and the trigger keeps focus), so without
|
|
39531
|
+
// this the panel would immediately pop open again and Escape would appear broken.
|
|
39532
|
+
function armComposerMenuDismissal(container) {
|
|
39533
|
+
if (!container?.classList) return;
|
|
39534
|
+
const hovering = container.matches(":hover");
|
|
39535
|
+
const clear = () => {
|
|
39536
|
+
container.classList.remove("menu-dismissed");
|
|
39537
|
+
container.removeEventListener("pointerleave", clear);
|
|
39538
|
+
container.removeEventListener("focusout", onFocusOut);
|
|
39539
|
+
};
|
|
39540
|
+
const onFocusOut = () => setTimeout(() => {
|
|
39541
|
+
// Still hovered: keep the dismissal until the pointer leaves as well.
|
|
39542
|
+
if (!container.contains(document.activeElement) && !container.matches(":hover")) clear();
|
|
39543
|
+
}, 0);
|
|
39544
|
+
const focusedInside = container.contains(document.activeElement);
|
|
39545
|
+
if (!hovering && !focusedInside) return; // nothing would reopen it; no need to suppress
|
|
39546
|
+
container.classList.add("menu-dismissed");
|
|
39547
|
+
container.addEventListener("pointerleave", () => {
|
|
39548
|
+
if (!container.contains(document.activeElement)) clear();
|
|
39549
|
+
}, { once: true });
|
|
39550
|
+
container.addEventListener("focusout", onFocusOut);
|
|
39551
|
+
}
|
|
39552
|
+
|
|
39553
|
+
function composerMenuDismissed(container) {
|
|
39554
|
+
return Boolean(container?.classList?.contains("menu-dismissed"));
|
|
39555
|
+
}
|
|
39556
|
+
|
|
39557
|
+
function clearComposerMenuDismissal(container) {
|
|
39558
|
+
container?.classList?.remove("menu-dismissed");
|
|
39559
|
+
}
|
|
39560
|
+
|
|
37899
39561
|
function setPublishMenuOpen(open) {
|
|
39562
|
+
if (open && composerMenuDismissed(elements.publishButton?.parentElement)) return;
|
|
37900
39563
|
if (open && followUpQueueOpen) setFollowUpQueueOpen(false);
|
|
37901
39564
|
publishMenuOpen = !!open;
|
|
37902
39565
|
elements.publishButton.setAttribute("aria-expanded", publishMenuOpen ? "true" : "false");
|
|
@@ -37907,6 +39570,7 @@ function setPublishMenuOpen(open) {
|
|
|
37907
39570
|
}
|
|
37908
39571
|
|
|
37909
39572
|
function setNativeCommandMenuOpen(open) {
|
|
39573
|
+
if (open && composerMenuDismissed(elements.nativeCommandMenuButton?.parentElement)) return;
|
|
37910
39574
|
if (open && followUpQueueOpen) setFollowUpQueueOpen(false);
|
|
37911
39575
|
nativeCommandMenuOpen = !!open;
|
|
37912
39576
|
elements.nativeCommandMenuButton.setAttribute("aria-expanded", nativeCommandMenuOpen ? "true" : "false");
|
|
@@ -37917,6 +39581,7 @@ function setNativeCommandMenuOpen(open) {
|
|
|
37917
39581
|
}
|
|
37918
39582
|
|
|
37919
39583
|
function setAppRunnerMenuOpen(open) {
|
|
39584
|
+
if (open && composerMenuDismissed(elements.appRunnerMenuButton?.parentElement)) return;
|
|
37920
39585
|
if (open && followUpQueueOpen) setFollowUpQueueOpen(false);
|
|
37921
39586
|
appRunnerMenuOpen = !!open;
|
|
37922
39587
|
elements.appRunnerMenuButton?.setAttribute("aria-expanded", appRunnerMenuOpen ? "true" : "false");
|
|
@@ -37927,6 +39592,7 @@ function setAppRunnerMenuOpen(open) {
|
|
|
37927
39592
|
}
|
|
37928
39593
|
|
|
37929
39594
|
function setOptionsMenuOpen(open) {
|
|
39595
|
+
if (open && composerMenuDismissed(elements.optionsMenuButton?.parentElement)) return;
|
|
37930
39596
|
if (open && followUpQueueOpen) setFollowUpQueueOpen(false);
|
|
37931
39597
|
optionsMenuOpen = !!open;
|
|
37932
39598
|
elements.optionsMenuButton.setAttribute("aria-expanded", optionsMenuOpen ? "true" : "false");
|
|
@@ -38745,6 +40411,16 @@ function renderOptionalFeatureMigrationSurface() {
|
|
|
38745
40411
|
ensureOptionalFeatureMigrationRenderTimer();
|
|
38746
40412
|
return;
|
|
38747
40413
|
}
|
|
40414
|
+
// A healthy "ready" audit is not actionable: don't cover the header with a banner on every
|
|
40415
|
+
// page load. The summary stays available in Optional features and the Events log; only a
|
|
40416
|
+
// deferred migration (restorable companions) still surfaces here.
|
|
40417
|
+
if (snapshot.phase === "ready" && !optionalFeatureRestartNotice && !(summary.migratable > 0) && !conflicts.length) {
|
|
40418
|
+
clearOptionalFeatureReadyDismissTimer();
|
|
40419
|
+
surface.replaceChildren();
|
|
40420
|
+
surface.hidden = true;
|
|
40421
|
+
ensureOptionalFeatureMigrationRenderTimer();
|
|
40422
|
+
return;
|
|
40423
|
+
}
|
|
38748
40424
|
if (noticeDismissKey && optionalFeatureMigrationDismissedNoticeKey === noticeDismissKey) {
|
|
38749
40425
|
surface.replaceChildren();
|
|
38750
40426
|
surface.hidden = true;
|
|
@@ -39534,11 +41210,14 @@ function renderOptionalFeatureControls() {
|
|
|
39534
41210
|
}
|
|
39535
41211
|
|
|
39536
41212
|
const hasGitWorkflow = isOptionalFeatureEnabled("gitWorkflow");
|
|
39537
|
-
|
|
41213
|
+
// Committing/pushing is a core expectation: keep the entry point visible (disabled, with the
|
|
41214
|
+
// install hint) when the companion package is merely missing; hide it only when the user
|
|
41215
|
+
// explicitly disabled the feature.
|
|
41216
|
+
elements.gitWorkflowButton.hidden = !hasGitWorkflow && isOptionalFeatureDisabled("gitWorkflow");
|
|
39538
41217
|
setOptionalControlState(
|
|
39539
41218
|
elements.gitWorkflowButton,
|
|
39540
41219
|
hasGitWorkflow,
|
|
39541
|
-
optionalFeatureUnavailableMessage("gitWorkflow"),
|
|
41220
|
+
`${optionalFeatureUnavailableMessage("gitWorkflow")} Until then, stage and review changes from the Git panel or the CHANGES footer chip.`,
|
|
39542
41221
|
);
|
|
39543
41222
|
|
|
39544
41223
|
elements.releaseNpmButton.hidden = !isOptionalFeatureEnabled("releaseNpm");
|
|
@@ -40361,18 +42040,120 @@ function nativeSelectorMatches(item, query) {
|
|
|
40361
42040
|
.some((value) => String(value).toLowerCase().includes(needle));
|
|
40362
42041
|
}
|
|
40363
42042
|
|
|
42043
|
+
// Keyboard navigation for native selector dialogs (/model, /theme, /resume, …):
|
|
42044
|
+
// the search box owns focus, ArrowUp/Down move a visible highlight, Enter selects
|
|
42045
|
+
// the highlighted choice, Home/End jump. The highlight defaults to the current
|
|
42046
|
+
// choice (when unfiltered) so Enter is never destructive by surprise.
|
|
42047
|
+
let nativeSelectorHighlightIndex = -1;
|
|
42048
|
+
|
|
42049
|
+
function nativeSelectorItemButtons() {
|
|
42050
|
+
return Array.from(elements.nativeCommandBody.querySelectorAll(".native-selector-item:not([disabled])"));
|
|
42051
|
+
}
|
|
42052
|
+
|
|
42053
|
+
function syncNativeSelectorHighlight({ scroll = true } = {}) {
|
|
42054
|
+
const buttons = nativeSelectorItemButtons();
|
|
42055
|
+
if (!buttons.length) {
|
|
42056
|
+
nativeSelectorHighlightIndex = -1;
|
|
42057
|
+
elements.nativeCommandSearch.removeAttribute("aria-activedescendant");
|
|
42058
|
+
return null;
|
|
42059
|
+
}
|
|
42060
|
+
nativeSelectorHighlightIndex = Math.min(Math.max(nativeSelectorHighlightIndex, 0), buttons.length - 1);
|
|
42061
|
+
let highlighted = null;
|
|
42062
|
+
buttons.forEach((button, index) => {
|
|
42063
|
+
const on = index === nativeSelectorHighlightIndex;
|
|
42064
|
+
button.classList.toggle("keyboard-active", on);
|
|
42065
|
+
button.setAttribute("aria-selected", on ? "true" : "false");
|
|
42066
|
+
if (on) highlighted = button;
|
|
42067
|
+
});
|
|
42068
|
+
if (highlighted) {
|
|
42069
|
+
elements.nativeCommandSearch.setAttribute("aria-activedescendant", highlighted.id);
|
|
42070
|
+
if (scroll) highlighted.scrollIntoView({ block: "nearest" });
|
|
42071
|
+
}
|
|
42072
|
+
return highlighted;
|
|
42073
|
+
}
|
|
42074
|
+
|
|
42075
|
+
function moveNativeSelectorHighlight(delta, { absolute = false } = {}) {
|
|
42076
|
+
const buttons = nativeSelectorItemButtons();
|
|
42077
|
+
if (!buttons.length) return;
|
|
42078
|
+
const last = buttons.length - 1;
|
|
42079
|
+
let next = absolute ? delta : nativeSelectorHighlightIndex + delta;
|
|
42080
|
+
if (next < 0) next = absolute ? 0 : last;
|
|
42081
|
+
if (next > last) next = absolute ? last : 0;
|
|
42082
|
+
nativeSelectorHighlightIndex = next;
|
|
42083
|
+
syncNativeSelectorHighlight();
|
|
42084
|
+
}
|
|
42085
|
+
|
|
42086
|
+
function activateNativeSelectorHighlight() {
|
|
42087
|
+
const highlighted = syncNativeSelectorHighlight({ scroll: false });
|
|
42088
|
+
if (!highlighted) return false;
|
|
42089
|
+
highlighted.click();
|
|
42090
|
+
return true;
|
|
42091
|
+
}
|
|
42092
|
+
|
|
42093
|
+
function handleNativeSelectorSearchKeydown(event) {
|
|
42094
|
+
if (event.isComposing || elements.nativeCommandSearch.hidden) return;
|
|
42095
|
+
if (!nativeSelectorItemButtons().length) return;
|
|
42096
|
+
switch (event.key) {
|
|
42097
|
+
case "ArrowDown":
|
|
42098
|
+
event.preventDefault();
|
|
42099
|
+
moveNativeSelectorHighlight(1);
|
|
42100
|
+
return;
|
|
42101
|
+
case "ArrowUp":
|
|
42102
|
+
event.preventDefault();
|
|
42103
|
+
moveNativeSelectorHighlight(-1);
|
|
42104
|
+
return;
|
|
42105
|
+
case "Home":
|
|
42106
|
+
if (elements.nativeCommandSearch.value) return;
|
|
42107
|
+
event.preventDefault();
|
|
42108
|
+
moveNativeSelectorHighlight(0, { absolute: true });
|
|
42109
|
+
return;
|
|
42110
|
+
case "End":
|
|
42111
|
+
if (elements.nativeCommandSearch.value) return;
|
|
42112
|
+
event.preventDefault();
|
|
42113
|
+
moveNativeSelectorHighlight(Number.MAX_SAFE_INTEGER, { absolute: true });
|
|
42114
|
+
return;
|
|
42115
|
+
case "PageDown":
|
|
42116
|
+
event.preventDefault();
|
|
42117
|
+
moveNativeSelectorHighlight(8);
|
|
42118
|
+
return;
|
|
42119
|
+
case "PageUp":
|
|
42120
|
+
event.preventDefault();
|
|
42121
|
+
moveNativeSelectorHighlight(-8);
|
|
42122
|
+
return;
|
|
42123
|
+
case "Enter":
|
|
42124
|
+
if (event.shiftKey || event.altKey || event.ctrlKey || event.metaKey) return;
|
|
42125
|
+
event.preventDefault();
|
|
42126
|
+
activateNativeSelectorHighlight();
|
|
42127
|
+
return;
|
|
42128
|
+
default:
|
|
42129
|
+
}
|
|
42130
|
+
}
|
|
42131
|
+
|
|
40364
42132
|
function renderNativeSelectorItems(items, { emptyText = "No choices.", onSelect, activeId, numbered = false } = {}) {
|
|
40365
42133
|
const query = elements.nativeCommandSearch.value.trim();
|
|
40366
42134
|
const filtered = items.filter((item) => nativeSelectorMatches(item, query));
|
|
40367
42135
|
elements.nativeCommandBody.replaceChildren();
|
|
42136
|
+
elements.nativeCommandSearch.removeAttribute("aria-activedescendant");
|
|
40368
42137
|
if (!filtered.length) {
|
|
42138
|
+
nativeSelectorHighlightIndex = -1;
|
|
40369
42139
|
elements.nativeCommandBody.append(make("div", "native-command-empty muted", emptyText));
|
|
40370
42140
|
return;
|
|
40371
42141
|
}
|
|
40372
42142
|
const list = make("div", "native-selector-list");
|
|
42143
|
+
list.setAttribute("role", "listbox");
|
|
42144
|
+
list.id = "nativeSelectorList";
|
|
42145
|
+
let lastGroup = null;
|
|
40373
42146
|
for (const [index, item] of filtered.entries()) {
|
|
42147
|
+
if (item.group && item.group !== lastGroup && !item.badge) {
|
|
42148
|
+
const heading = make("div", "native-selector-group", item.group);
|
|
42149
|
+
heading.setAttribute("role", "presentation");
|
|
42150
|
+
list.append(heading);
|
|
42151
|
+
}
|
|
42152
|
+
if (item.group) lastGroup = item.group;
|
|
40374
42153
|
const button = make("button", `native-selector-item${item.id === activeId ? " active" : ""}`);
|
|
40375
42154
|
button.type = "button";
|
|
42155
|
+
button.id = `nativeSelectorItem-${index}`;
|
|
42156
|
+
button.setAttribute("role", "option");
|
|
40376
42157
|
button.disabled = item.disabled === true;
|
|
40377
42158
|
if (typeof item.pressed === "boolean") button.setAttribute("aria-pressed", String(item.pressed));
|
|
40378
42159
|
button.addEventListener("click", () => onSelect?.(item));
|
|
@@ -40402,6 +42183,12 @@ function renderNativeSelectorItems(items, { emptyText = "No choices.", onSelect,
|
|
|
40402
42183
|
list.append(button);
|
|
40403
42184
|
}
|
|
40404
42185
|
elements.nativeCommandBody.append(list);
|
|
42186
|
+
// Unfiltered: highlight (and reveal) the current choice; filtered: the best match on top.
|
|
42187
|
+
const enabled = nativeSelectorItemButtons();
|
|
42188
|
+
const currentIndex = query ? -1 : enabled.findIndex((button) => button.classList.contains("active"));
|
|
42189
|
+
nativeSelectorHighlightIndex = currentIndex >= 0 ? currentIndex : 0;
|
|
42190
|
+
const highlighted = syncNativeSelectorHighlight({ scroll: false });
|
|
42191
|
+
if (highlighted && !query && currentIndex >= 0) queueMicrotask(() => highlighted.scrollIntoView({ block: "center" }));
|
|
40405
42192
|
}
|
|
40406
42193
|
|
|
40407
42194
|
function setNativeActionBusy(button, busy, label = "Working…") {
|
|
@@ -40426,10 +42213,17 @@ async function openNativeModelSelector() {
|
|
|
40426
42213
|
id: modelOptionLabel(model),
|
|
40427
42214
|
label: modelOptionLabel(model),
|
|
40428
42215
|
description: model.name || model.description || "",
|
|
40429
|
-
meta:
|
|
42216
|
+
meta: [
|
|
42217
|
+
model.contextWindow ? `context ${formatFooterTokenCount(model.contextWindow)}` : "",
|
|
42218
|
+
model.reasoning ? "reasoning" : "",
|
|
42219
|
+
Array.isArray(model.input) && model.input.includes("image") ? "images" : "",
|
|
42220
|
+
].filter(Boolean).join(" · ") || model.provider,
|
|
42221
|
+
group: model.provider,
|
|
40430
42222
|
model,
|
|
40431
42223
|
badge: modelOptionLabel(model) === activeId ? "current" : "",
|
|
40432
42224
|
}));
|
|
42225
|
+
// The current model goes first so it is visible without scrolling through hundreds of rows.
|
|
42226
|
+
items.sort((a, b) => (b.badge === "current") - (a.badge === "current"));
|
|
40433
42227
|
const render = () => renderNativeSelectorItems(items, {
|
|
40434
42228
|
emptyText: "No models match this filter.",
|
|
40435
42229
|
activeId,
|
|
@@ -41340,6 +43134,7 @@ async function openNativeGitWorkflowSetupDialog({ onSaved } = {}) {
|
|
|
41340
43134
|
}
|
|
41341
43135
|
|
|
41342
43136
|
const configuredModelKey = `${preferences.generation?.provider || ""}/${preferences.generation?.modelId || ""}`;
|
|
43137
|
+
const configuredFallbackKey = `${preferences.generation?.fallback?.provider || ""}/${preferences.generation?.fallback?.modelId || ""}`;
|
|
41343
43138
|
const activeModelKey = gitWorkflowSetupModelKey(currentState?.model);
|
|
41344
43139
|
const modelKeys = new Set(models.map(gitWorkflowSetupModelKey));
|
|
41345
43140
|
const initialModelKey = modelKeys.has(configuredModelKey)
|
|
@@ -41347,14 +43142,21 @@ async function openNativeGitWorkflowSetupDialog({ onSaved } = {}) {
|
|
|
41347
43142
|
: modelKeys.has(activeModelKey)
|
|
41348
43143
|
? activeModelKey
|
|
41349
43144
|
: gitWorkflowSetupModelKey(models[0]);
|
|
43145
|
+
const initialFallbackKey = modelKeys.has(configuredFallbackKey) && configuredFallbackKey !== initialModelKey ? configuredFallbackKey : "";
|
|
41350
43146
|
const modelOptions = models.map((model) => ({
|
|
41351
43147
|
value: gitWorkflowSetupModelKey(model),
|
|
41352
43148
|
label: `${gitWorkflowSetupModelKey(model)}${model.name && model.name !== model.id ? ` · ${model.name}` : ""}`,
|
|
41353
43149
|
}));
|
|
43150
|
+
const fallbackModelOptions = (primaryKey) => [
|
|
43151
|
+
{ value: "", label: "No fallback" },
|
|
43152
|
+
...modelOptions.filter((option) => option.value !== primaryKey),
|
|
43153
|
+
];
|
|
41354
43154
|
|
|
41355
43155
|
const controls = {
|
|
41356
|
-
model: nativeSettingSelect("Git-writing model", initialModelKey, modelOptions, "Exact authenticated provider/model used for commit messages, branch names, and PR descriptions.", { label: "required", tone: "safety" }),
|
|
41357
|
-
thinking: nativeSettingSelect("
|
|
43156
|
+
model: nativeSettingSelect("Primary Git-writing model", initialModelKey, modelOptions, "Exact authenticated provider/model normally used for commit messages, branch names, and PR descriptions.", { label: "required", tone: "safety" }),
|
|
43157
|
+
thinking: nativeSettingSelect("Primary reasoning effort", preferences.generation?.thinkingLevel || "low", SETTINGS_THINKING_OPTIONS, "Only levels supported by the primary model are shown. Low is recommended for routine commit messages.", { label: "required", tone: "safety" }),
|
|
43158
|
+
fallbackModel: nativeSettingSelect("Fallback model", initialFallbackKey, fallbackModelOptions(initialModelKey), "Optional. After a final primary model-generation failure, Guided Git tries this different model once.", { label: "optional", tone: "browser" }),
|
|
43159
|
+
fallbackThinking: nativeSettingSelect("Fallback reasoning effort", preferences.generation?.fallback?.thinkingLevel || "low", SETTINGS_THINKING_OPTIONS, "Uses only levels supported by the fallback model and is disabled when No fallback is selected.", { label: "optional", tone: "browser" }),
|
|
41358
43160
|
language: nativeSettingSelect("Generated language", preferences.commit?.language || "en", [
|
|
41359
43161
|
{ value: "en", label: "English" },
|
|
41360
43162
|
{ value: "de", label: "German" },
|
|
@@ -41397,13 +43199,30 @@ async function openNativeGitWorkflowSetupDialog({ onSaved } = {}) {
|
|
|
41397
43199
|
const levels = thinkingLevelsForModel(controls.model.select.value);
|
|
41398
43200
|
replaceNativeSettingSelectOptions(controls.thinking.select, levels, current);
|
|
41399
43201
|
};
|
|
41400
|
-
|
|
43202
|
+
const syncFallbackThinkingLevels = () => {
|
|
43203
|
+
const fallbackKey = controls.fallbackModel.select.value;
|
|
43204
|
+
const current = controls.fallbackThinking.select.value || preferences.generation?.fallback?.thinkingLevel || "low";
|
|
43205
|
+
const levels = fallbackKey ? thinkingLevelsForModel(fallbackKey) : [preferences.generation?.fallback?.thinkingLevel || "low"];
|
|
43206
|
+
replaceNativeSettingSelectOptions(controls.fallbackThinking.select, levels, current);
|
|
43207
|
+
controls.fallbackThinking.select.disabled = !fallbackKey;
|
|
43208
|
+
};
|
|
43209
|
+
const syncFallbackModelOptions = () => {
|
|
43210
|
+
const current = controls.fallbackModel.select.value;
|
|
43211
|
+
replaceNativeSettingSelectOptions(controls.fallbackModel.select, fallbackModelOptions(controls.model.select.value), current);
|
|
43212
|
+
syncFallbackThinkingLevels();
|
|
43213
|
+
};
|
|
43214
|
+
controls.model.select.addEventListener("change", () => {
|
|
43215
|
+
syncThinkingLevels();
|
|
43216
|
+
syncFallbackModelOptions();
|
|
43217
|
+
});
|
|
43218
|
+
controls.fallbackModel.select.addEventListener("change", syncFallbackThinkingLevels);
|
|
41401
43219
|
syncThinkingLevels();
|
|
43220
|
+
syncFallbackModelOptions();
|
|
41402
43221
|
|
|
41403
43222
|
const body = make("div", "native-settings-panel");
|
|
41404
43223
|
body.append(
|
|
41405
43224
|
nativeSettingsNote("Persistence", `Saved globally in ${data.path || "the Pi Web UI settings file"}. Credentials are never stored here.`),
|
|
41406
|
-
nativeSettingsSection("Generation profile", "
|
|
43225
|
+
nativeSettingsSection("Generation profile", "Choose the required primary profile and an optional one-shot fallback with its own effort.", [controls.model, controls.thinking, controls.fallbackModel, controls.fallbackThinking], { open: true }),
|
|
41407
43226
|
nativeSettingsSection("Commit style", "Conventional Commit output preferences.", [controls.language, controls.defaultVariant, controls.scope], { open: true }),
|
|
41408
43227
|
nativeSettingsSection("Workflow safety", "Staging, review, delivery, and verification defaults; push and PR confirmation remain mandatory.", [controls.staging, controls.reviewProcess, controls.delivery, controls.verification], { open: true }),
|
|
41409
43228
|
);
|
|
@@ -41416,7 +43235,11 @@ async function openNativeGitWorkflowSetupDialog({ onSaved } = {}) {
|
|
|
41416
43235
|
setNativeCommandError("");
|
|
41417
43236
|
try {
|
|
41418
43237
|
const selectedModel = models.find((model) => gitWorkflowSetupModelKey(model) === controls.model.select.value);
|
|
41419
|
-
if (!selectedModel) throw new Error("Select an available Git-writing model.");
|
|
43238
|
+
if (!selectedModel) throw new Error("Select an available primary Git-writing model.");
|
|
43239
|
+
const selectedFallback = models.find((model) => gitWorkflowSetupModelKey(model) === controls.fallbackModel.select.value) || null;
|
|
43240
|
+
if (selectedFallback && gitWorkflowSetupModelKey(selectedFallback) === gitWorkflowSetupModelKey(selectedModel)) {
|
|
43241
|
+
throw new Error("Select a fallback model different from the primary model.");
|
|
43242
|
+
}
|
|
41420
43243
|
const response = await nativeCommandApi("/api/git-workflow/preferences", {
|
|
41421
43244
|
method: "POST",
|
|
41422
43245
|
body: {
|
|
@@ -41426,6 +43249,11 @@ async function openNativeGitWorkflowSetupDialog({ onSaved } = {}) {
|
|
|
41426
43249
|
modelId: selectedModel.id,
|
|
41427
43250
|
thinkingLevel: controls.thinking.select.value,
|
|
41428
43251
|
unavailablePolicy: "ask",
|
|
43252
|
+
fallback: {
|
|
43253
|
+
provider: selectedFallback?.provider || "",
|
|
43254
|
+
modelId: selectedFallback?.id || "",
|
|
43255
|
+
thinkingLevel: controls.fallbackThinking.select.value || preferences.generation?.fallback?.thinkingLevel || "low",
|
|
43256
|
+
},
|
|
41429
43257
|
},
|
|
41430
43258
|
commit: {
|
|
41431
43259
|
language: controls.language.select.value,
|
|
@@ -41443,7 +43271,7 @@ async function openNativeGitWorkflowSetupDialog({ onSaved } = {}) {
|
|
|
41443
43271
|
addTransientMessage({
|
|
41444
43272
|
role: "native",
|
|
41445
43273
|
title: "/git-workflow-setup",
|
|
41446
|
-
content: `Guided Git setup saved
|
|
43274
|
+
content: `Guided Git setup saved. Primary: ${gitWorkflowSetupModelKey(selectedModel)} at ${controls.thinking.select.value} effort. ${selectedFallback ? `Fallback: ${gitWorkflowSetupModelKey(selectedFallback)} at ${controls.fallbackThinking.select.value} effort (one attempt after a final primary generation failure).` : "Fallback: none."}`,
|
|
41447
43275
|
level: "info",
|
|
41448
43276
|
});
|
|
41449
43277
|
closeNativeCommandDialog();
|
|
@@ -41877,8 +43705,9 @@ function openNativeNameDialog() {
|
|
|
41877
43705
|
});
|
|
41878
43706
|
}
|
|
41879
43707
|
|
|
41880
|
-
async function openNativeResumeSelector(scope = "current") {
|
|
41881
|
-
openNativeCommandDialog({ title: "
|
|
43708
|
+
async function openNativeResumeSelector(scope = "current", { query = "" } = {}) {
|
|
43709
|
+
openNativeCommandDialog({ title: "Resume a session", message: "Select a session, then resume, rename metadata, or delete it.", searchPlaceholder: "Filter sessions…" });
|
|
43710
|
+
if (query) elements.nativeCommandSearch.value = query;
|
|
41882
43711
|
renderNativeLoading("Loading sessions…");
|
|
41883
43712
|
const selectedScope = scope === "all" ? "all" : "current";
|
|
41884
43713
|
let selectedItem = null;
|
|
@@ -41903,13 +43732,13 @@ async function openNativeResumeSelector(scope = "current") {
|
|
|
41903
43732
|
|
|
41904
43733
|
const renameButton = addNativeCommandAction("Rename", async () => {
|
|
41905
43734
|
if (!selectedItem) return;
|
|
41906
|
-
const nextName =
|
|
43735
|
+
const nextName = await appPromptText({ title: "Rename session", summary: "Display name stored in the session metadata.", defaultValue: selectedItem.session.name || selectedItem.label || "", confirmLabel: "Rename" });
|
|
41907
43736
|
if (nextName === null) return;
|
|
41908
43737
|
setNativeCommandError("");
|
|
41909
43738
|
try {
|
|
41910
43739
|
const result = await nativeCommandApi("/api/session-rename", { method: "POST", body: { sessionPath: selectedItem.session.path, name: nextName } });
|
|
41911
43740
|
addTransientMessage({ role: "native", title: "/resume", content: result.data?.message || "Renamed session metadata.", level: "info" });
|
|
41912
|
-
await openNativeResumeSelector(selectedScope);
|
|
43741
|
+
await openNativeResumeSelector(selectedScope, { query: elements.nativeCommandSearch.value });
|
|
41913
43742
|
} catch (error) {
|
|
41914
43743
|
setNativeCommandError(error.message || String(error));
|
|
41915
43744
|
}
|
|
@@ -41928,7 +43757,7 @@ async function openNativeResumeSelector(scope = "current") {
|
|
|
41928
43757
|
try {
|
|
41929
43758
|
const result = await nativeCommandApi("/api/session-delete", { method: "POST", body: { sessionPath: selectedItem.session.path, confirmed: true } });
|
|
41930
43759
|
addTransientMessage({ role: "native", title: "/resume", content: result.data?.message || "Session deleted.", level: "warn" });
|
|
41931
|
-
await openNativeResumeSelector(selectedScope);
|
|
43760
|
+
await openNativeResumeSelector(selectedScope, { query: elements.nativeCommandSearch.value });
|
|
41932
43761
|
} catch (error) {
|
|
41933
43762
|
setNativeCommandError(error.message || String(error));
|
|
41934
43763
|
resumeDeleteArmed = false;
|
|
@@ -41947,7 +43776,7 @@ async function openNativeResumeSelector(scope = "current") {
|
|
|
41947
43776
|
id: session.path,
|
|
41948
43777
|
label: session.name || session.firstMessage || session.id || session.path,
|
|
41949
43778
|
description: session.firstMessage || "(no messages)",
|
|
41950
|
-
meta: `${session.cwd || "unknown cwd"} · ${session.messageCount || 0} messages · ${session.modified
|
|
43779
|
+
meta: `${session.cwd || "unknown cwd"} · ${session.messageCount || 0} messages · ${session.modified ? formatRelativeDate(session.modified) : "unknown time"}`,
|
|
41951
43780
|
badge: session.current ? "current" : "",
|
|
41952
43781
|
disabled: session.current,
|
|
41953
43782
|
session,
|
|
@@ -42797,6 +44626,7 @@ function acceptOutputModeAcknowledgement(event) {
|
|
|
42797
44626
|
}
|
|
42798
44627
|
|
|
42799
44628
|
function transitionNormalLiveOutputToCompact() {
|
|
44629
|
+
flushNormalStreamRenders("output-mode-transition");
|
|
42800
44630
|
compactLiveState = seedFastOutputLiveState({ text: streamRawText, thinking: streamThinkingRawText });
|
|
42801
44631
|
setStreamRawText("");
|
|
42802
44632
|
setStreamThinkingRawText("");
|
|
@@ -42817,6 +44647,8 @@ function transitionCompactLiveOutputToNormal(tabContext = activeTabContext()) {
|
|
|
42817
44647
|
|
|
42818
44648
|
function applyOutputModeControl(event, tabContext = activeTabContext()) {
|
|
42819
44649
|
if (event?.protocolVersion !== 1 || !["normal", "compact-v1"].includes(event.activeMode)) return false;
|
|
44650
|
+
flushNormalStreamRenders("output-mode-change");
|
|
44651
|
+
fallbackStreamDerivedOutput("output-mode-change");
|
|
42820
44652
|
const previousMode = activeOutputMode;
|
|
42821
44653
|
if (previousMode === "normal" && event.activeMode === "compact-v1") {
|
|
42822
44654
|
transitionNormalLiveOutputToCompact();
|
|
@@ -42844,23 +44676,67 @@ function removeStreamBubble() {
|
|
|
42844
44676
|
renderRunIndicator({ scroll: false });
|
|
42845
44677
|
}
|
|
42846
44678
|
|
|
42847
|
-
function
|
|
42848
|
-
|
|
44679
|
+
function ensureStreamDerivedOutputState() {
|
|
44680
|
+
const todoProgressDetected = isOptionalFeatureDetected("todoProgressWidget");
|
|
44681
|
+
if (!streamDerivedOutputState) {
|
|
44682
|
+
streamDerivedOutputState = createStreamDerivedOutputState({
|
|
44683
|
+
todoProgressDetected,
|
|
44684
|
+
shadow: !!streamIsolationDebugLedger,
|
|
44685
|
+
});
|
|
44686
|
+
} else {
|
|
44687
|
+
streamDerivedOutputState.setTodoProgressDetected(todoProgressDetected);
|
|
44688
|
+
}
|
|
44689
|
+
return streamDerivedOutputState;
|
|
44690
|
+
}
|
|
44691
|
+
|
|
44692
|
+
function recordStreamDerivedOutputDiagnostic(diagnostic, ms = 0) {
|
|
44693
|
+
if (!streamIsolationDebugLedger || (!diagnostic.scannedCodeUnits && !diagnostic.fallbackReason && !diagnostic.shadowMismatch)) return;
|
|
44694
|
+
const bytes = diagnostic.scannedCodeUnits * 2;
|
|
44695
|
+
recordStreamProfileDiagnostic({ type: "derive", ms, bytes });
|
|
44696
|
+
if (diagnostic.fallbackReason) recordStreamProfileDiagnostic({ type: "derive-fallback", reason: diagnostic.fallbackReason, bytes });
|
|
44697
|
+
if (diagnostic.shadowMismatch) recordStreamProfileDiagnostic({ type: "derive-shadow-mismatch", reason: diagnostic.fallbackReason || "shadow-mismatch" });
|
|
44698
|
+
}
|
|
44699
|
+
|
|
44700
|
+
function captureStreamDerivedOutputProfile(startedAt) {
|
|
44701
|
+
recordStreamDerivedOutputDiagnostic(
|
|
44702
|
+
ensureStreamDerivedOutputState().takeDiagnostics(),
|
|
44703
|
+
streamIsolationDebugLedger ? performance.now() - startedAt : 0,
|
|
44704
|
+
);
|
|
44705
|
+
}
|
|
44706
|
+
|
|
44707
|
+
function resetStreamDerivedOutputState(reason = "reset") {
|
|
44708
|
+
if (!streamDerivedOutputState) return;
|
|
44709
|
+
streamDerivedOutputState.reset({
|
|
44710
|
+
todoProgressDetected: isOptionalFeatureDetected("todoProgressWidget"),
|
|
44711
|
+
reason,
|
|
44712
|
+
});
|
|
44713
|
+
recordStreamDerivedOutputDiagnostic(streamDerivedOutputState.takeDiagnostics());
|
|
44714
|
+
}
|
|
44715
|
+
|
|
44716
|
+
function fallbackStreamDerivedOutput(reason) {
|
|
44717
|
+
if (!streamRawText || !streamDerivedOutputState) return;
|
|
44718
|
+
const profileStart = streamIsolationDebugLedger ? performance.now() : 0;
|
|
44719
|
+
ensureStreamDerivedOutputState().replace(streamRawText, { reason, force: true });
|
|
44720
|
+
captureStreamDerivedOutputProfile(profileStart);
|
|
42849
44721
|
}
|
|
42850
44722
|
|
|
42851
|
-
function setStreamRawText(text) {
|
|
44723
|
+
function setStreamRawText(text, { reason = "snapshot" } = {}) {
|
|
42852
44724
|
const nextText = String(text || "");
|
|
42853
44725
|
if (nextText === streamRawText) return false;
|
|
44726
|
+
const profileStart = streamIsolationDebugLedger ? performance.now() : 0;
|
|
42854
44727
|
streamRawText = nextText;
|
|
42855
|
-
|
|
44728
|
+
ensureStreamDerivedOutputState().replace(nextText, { reason });
|
|
44729
|
+
captureStreamDerivedOutputProfile(profileStart);
|
|
42856
44730
|
return true;
|
|
42857
44731
|
}
|
|
42858
44732
|
|
|
42859
44733
|
function appendStreamRawText(delta) {
|
|
42860
44734
|
const text = String(delta || "");
|
|
42861
44735
|
if (!text) return false;
|
|
44736
|
+
const profileStart = streamIsolationDebugLedger ? performance.now() : 0;
|
|
42862
44737
|
streamRawText += text;
|
|
42863
|
-
|
|
44738
|
+
ensureStreamDerivedOutputState().append(text);
|
|
44739
|
+
captureStreamDerivedOutputProfile(profileStart);
|
|
42864
44740
|
return true;
|
|
42865
44741
|
}
|
|
42866
44742
|
|
|
@@ -42882,16 +44758,13 @@ function syncStreamRawTextFromUpdate(event, update) {
|
|
|
42882
44758
|
}
|
|
42883
44759
|
|
|
42884
44760
|
function streamDerivedText() {
|
|
42885
|
-
|
|
42886
|
-
|
|
42887
|
-
|
|
42888
|
-
|
|
42889
|
-
|
|
42890
|
-
streamDerivedTextCache = { rawText: streamRawText, assistantText, thinkingFormat, finalText };
|
|
42891
|
-
if (streamIsolationDebugLedger) {
|
|
42892
|
-
recordStreamProfileDiagnostic({ type: "derive", ms: performance.now() - profileStart, bytes: streamDiagnosticBytes(streamRawText) });
|
|
44761
|
+
const state = ensureStreamDerivedOutputState();
|
|
44762
|
+
if (state.value().rawText !== streamRawText) {
|
|
44763
|
+
const profileStart = streamIsolationDebugLedger ? performance.now() : 0;
|
|
44764
|
+
state.replace(streamRawText, { reason: "state-divergence" });
|
|
44765
|
+
captureStreamDerivedOutputProfile(profileStart);
|
|
42893
44766
|
}
|
|
42894
|
-
return
|
|
44767
|
+
return state.value();
|
|
42895
44768
|
}
|
|
42896
44769
|
|
|
42897
44770
|
function streamRenderableAssistantText() {
|
|
@@ -42966,27 +44839,28 @@ function scheduleStreamBubbleHide() {
|
|
|
42966
44839
|
}, delayMs);
|
|
42967
44840
|
}
|
|
42968
44841
|
|
|
42969
|
-
function syncStreamingThinkingFormat() {
|
|
44842
|
+
function syncStreamingThinkingFormat({ complete = false } = {}) {
|
|
42970
44843
|
const parsed = streamDerivedText().thinkingFormat;
|
|
42971
44844
|
if (!parsed?.hasThinkingFormat) return null;
|
|
42972
44845
|
const thinking = visibleThinkingText(parsed.thinkingText);
|
|
42973
|
-
if (thinking) setStreamingThinkingText(thinking);
|
|
44846
|
+
if (thinking) setStreamingThinkingText(thinking, { complete: complete || parsed.complete });
|
|
42974
44847
|
if (parsed.complete && streamThinkingBubble) streamThinkingBubble.classList.add("complete");
|
|
42975
44848
|
return parsed;
|
|
42976
44849
|
}
|
|
42977
44850
|
|
|
42978
|
-
function renderStreamingAssistantText() {
|
|
42979
|
-
const thinkingFormat = syncStreamingThinkingFormat();
|
|
44851
|
+
function renderStreamingAssistantText({ complete = false } = {}) {
|
|
44852
|
+
const thinkingFormat = syncStreamingThinkingFormat({ complete });
|
|
42980
44853
|
const finalText = thinkingFormat?.hasThinkingFormat ? streamDerivedText().finalText : streamRenderableAssistantText();
|
|
42981
44854
|
if (finalText) {
|
|
42982
44855
|
ensureStreamBubble();
|
|
42983
|
-
renderStreamingMarkdown(streamText, finalText);
|
|
44856
|
+
renderStreamingMarkdown(streamText, finalText, { complete });
|
|
42984
44857
|
} else {
|
|
42985
44858
|
scheduleStreamBubbleHide();
|
|
42986
44859
|
}
|
|
42987
44860
|
}
|
|
42988
44861
|
|
|
42989
44862
|
function suppressStreamingAssistantTextBeforeToolCall() {
|
|
44863
|
+
flushNormalStreamRenders("tool-call-boundary");
|
|
42990
44864
|
setStreamRawText("");
|
|
42991
44865
|
removeStreamBubble();
|
|
42992
44866
|
}
|
|
@@ -43081,14 +44955,14 @@ function showStreamingThinking(initialText = "") {
|
|
|
43081
44955
|
}
|
|
43082
44956
|
|
|
43083
44957
|
function resetStreamBubble({ preserveCompact = false } = {}) {
|
|
44958
|
+
cancelNormalStreamRenders();
|
|
43084
44959
|
resetCompactLiveOutput({ remove: !preserveCompact });
|
|
43085
44960
|
cancelStreamBubbleHide();
|
|
43086
44961
|
streamBubble = null;
|
|
43087
44962
|
streamText = null;
|
|
43088
44963
|
streamRawText = "";
|
|
43089
44964
|
streamThinkingRawText = "";
|
|
43090
|
-
|
|
43091
|
-
streamMarkdownState = null;
|
|
44965
|
+
resetStreamDerivedOutputState("reset");
|
|
43092
44966
|
streamBubbleVisibleSince = 0;
|
|
43093
44967
|
streamToolCallSeen = false;
|
|
43094
44968
|
resetStreamingToolCallState({ remove: true });
|
|
@@ -43254,11 +45128,11 @@ function assistantThinkingTextFromMessage(message, { streaming = false } = {}) {
|
|
|
43254
45128
|
return parts.length ? parts.join("\n\n") : "";
|
|
43255
45129
|
}
|
|
43256
45130
|
|
|
43257
|
-
function setStreamingThinkingText(text) {
|
|
45131
|
+
function setStreamingThinkingText(text, { complete = false } = {}) {
|
|
43258
45132
|
const thinking = visibleThinkingText(text);
|
|
43259
45133
|
if (!thinkingOutputVisible || !thinking) return false;
|
|
43260
45134
|
showStreamingThinking("");
|
|
43261
|
-
if (streamThinking) renderThinkingMarkdown(streamThinking, thinking);
|
|
45135
|
+
if (streamThinking) renderThinkingMarkdown(streamThinking, thinking, { complete });
|
|
43262
45136
|
return true;
|
|
43263
45137
|
}
|
|
43264
45138
|
|
|
@@ -43283,16 +45157,17 @@ function appendStreamThinkingText(delta) {
|
|
|
43283
45157
|
return true;
|
|
43284
45158
|
}
|
|
43285
45159
|
|
|
43286
|
-
function syncStreamingThinkingFromUpdate(event, update, { placeholder = "" } = {}) {
|
|
45160
|
+
function syncStreamingThinkingFromUpdate(event, update, { placeholder = "", render = true } = {}) {
|
|
43287
45161
|
if (!thinkingOutputVisible) return true;
|
|
43288
45162
|
const delta = thinkingDeltaText(update);
|
|
43289
45163
|
if (update.type === "thinking_delta" && delta) {
|
|
43290
45164
|
appendStreamThinkingText(delta);
|
|
43291
|
-
return setStreamingThinkingText(streamThinkingRawText || placeholder);
|
|
45165
|
+
return render ? setStreamingThinkingText(streamThinkingRawText || placeholder) : true;
|
|
43292
45166
|
}
|
|
43293
45167
|
if (update.type === "thinking_start") {
|
|
43294
45168
|
if (delta) setStreamThinkingRawText(delta);
|
|
43295
|
-
|
|
45169
|
+
if (!streamThinkingRawText) return false;
|
|
45170
|
+
return render ? setStreamingThinkingText(streamThinkingRawText || placeholder) : true;
|
|
43296
45171
|
}
|
|
43297
45172
|
if (update.type === "thinking_end") {
|
|
43298
45173
|
if (delta) setStreamThinkingRawText(delta, { reconcile: true });
|
|
@@ -43300,12 +45175,12 @@ function syncStreamingThinkingFromUpdate(event, update, { placeholder = "" } = {
|
|
|
43300
45175
|
const fallback = streamingThinkingTextFallback(event);
|
|
43301
45176
|
if (fallback !== null) setStreamThinkingRawText(fallback, { reconcile: true });
|
|
43302
45177
|
}
|
|
43303
|
-
return setStreamingThinkingText(streamThinkingRawText || placeholder);
|
|
45178
|
+
return render ? setStreamingThinkingText(streamThinkingRawText || placeholder, { complete: true }) : true;
|
|
43304
45179
|
}
|
|
43305
45180
|
const fallback = streamingThinkingTextFallback(event);
|
|
43306
45181
|
if (fallback === null) return false;
|
|
43307
45182
|
setStreamThinkingRawText(fallback);
|
|
43308
|
-
return setStreamingThinkingText(streamThinkingRawText || placeholder);
|
|
45183
|
+
return render ? setStreamingThinkingText(streamThinkingRawText || placeholder) : true;
|
|
43309
45184
|
}
|
|
43310
45185
|
|
|
43311
45186
|
function assistantStreamErrorMessage(event, update = event?.assistantMessageEvent || {}) {
|
|
@@ -43322,20 +45197,20 @@ function assistantStreamErrorMessage(event, update = event?.assistantMessageEven
|
|
|
43322
45197
|
function handleMessageUpdate(event) {
|
|
43323
45198
|
if (compactOutputActive() && handleCompactMessageUpdate(event)) return;
|
|
43324
45199
|
const update = event.assistantMessageEvent || {};
|
|
43325
|
-
if (update.type === "thinking_start") {
|
|
43326
|
-
syncStreamingThinkingFromUpdate(event, update);
|
|
43327
|
-
|
|
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
|
-
}
|
|
45200
|
+
if (update.type === "thinking_start" || update.type === "thinking_delta") {
|
|
45201
|
+
syncStreamingThinkingFromUpdate(event, update, { render: false });
|
|
45202
|
+
if (thinkingOutputVisible && streamThinkingRawText) thinkingStreamRenderScheduler.request({ complete: false });
|
|
43334
45203
|
} else if (update.type === "thinking_end") {
|
|
43335
|
-
|
|
45204
|
+
syncStreamingThinkingFromUpdate(event, update, { render: false });
|
|
45205
|
+
if (thinkingOutputVisible && streamThinkingRawText) {
|
|
45206
|
+
thinkingStreamRenderScheduler.request({ complete: true });
|
|
45207
|
+
thinkingStreamRenderScheduler.flushNow("thinking_end");
|
|
45208
|
+
}
|
|
43336
45209
|
} else if (update.type === "text_delta" || update.type === "text_end") {
|
|
43337
45210
|
syncStreamRawTextFromUpdate(event, update);
|
|
43338
|
-
|
|
45211
|
+
if (update.type === "text_end") fallbackStreamDerivedOutput("settlement:text_end");
|
|
45212
|
+
assistantStreamRenderScheduler.request({ complete: update.type === "text_end" });
|
|
45213
|
+
if (update.type === "text_end") assistantStreamRenderScheduler.flushNow("text_end");
|
|
43339
45214
|
} else if (update.type === "toolcall_start") {
|
|
43340
45215
|
streamToolCallSeen = true;
|
|
43341
45216
|
suppressStreamingAssistantTextBeforeToolCall();
|
|
@@ -43793,6 +45668,7 @@ function renderModelSearchResults(models = []) {
|
|
|
43793
45668
|
);
|
|
43794
45669
|
button.addEventListener("click", () => {
|
|
43795
45670
|
if (elements.modelSelect) elements.modelSelect.value = value;
|
|
45671
|
+
setControlsPendingModel(value);
|
|
43796
45672
|
renderModelSearchResults(models);
|
|
43797
45673
|
});
|
|
43798
45674
|
button.addEventListener("dblclick", () => elements.setModelButton?.click());
|
|
@@ -43856,9 +45732,23 @@ function hideModelSearchInput() {
|
|
|
43856
45732
|
scheduleDeferredUiFlushAfterDropdownClose();
|
|
43857
45733
|
}
|
|
43858
45734
|
|
|
45735
|
+
function setControlsPendingModel(value) {
|
|
45736
|
+
controlsPendingModelValue = value || "";
|
|
45737
|
+
elements.setModelButton?.classList.toggle("pending", Boolean(controlsPendingModelValue));
|
|
45738
|
+
if (elements.setModelButton) elements.setModelButton.title = controlsPendingModelValue ? "Apply the selected model (not applied yet)" : "Apply selected model";
|
|
45739
|
+
}
|
|
45740
|
+
|
|
45741
|
+
function setControlsPendingThinking(value) {
|
|
45742
|
+
controlsPendingThinkingValue = value || "";
|
|
45743
|
+
elements.setThinkingButton?.classList.toggle("pending", Boolean(controlsPendingThinkingValue));
|
|
45744
|
+
if (elements.setThinkingButton) elements.setThinkingButton.title = controlsPendingThinkingValue ? "Apply the selected thinking effort (not applied yet)" : "Apply selected thinking effort";
|
|
45745
|
+
}
|
|
45746
|
+
|
|
43859
45747
|
function syncModelSelectToState() {
|
|
43860
45748
|
if (!currentState?.model || !elements.modelSelect.options.length) return;
|
|
43861
45749
|
const value = JSON.stringify({ provider: currentState.model.provider, modelId: currentState.model.id });
|
|
45750
|
+
if (controlsPendingModelValue && controlsPendingModelValue === value) setControlsPendingModel("");
|
|
45751
|
+
if (controlsPendingModelValue) return; // keep the user's unapplied choice visible
|
|
43862
45752
|
for (const option of elements.modelSelect.options) {
|
|
43863
45753
|
if (option.value === value) {
|
|
43864
45754
|
elements.modelSelect.value = value;
|
|
@@ -43986,6 +45876,8 @@ function getCommandTrigger() {
|
|
|
43986
45876
|
if (!match) return null;
|
|
43987
45877
|
|
|
43988
45878
|
const query = match[2] || "";
|
|
45879
|
+
// "/etc/hosts" or "/tmp/x.txt" mid-sentence is a path, not a slash command.
|
|
45880
|
+
if (query.includes("/")) return null;
|
|
43989
45881
|
return {
|
|
43990
45882
|
start: cursor - query.length - 1,
|
|
43991
45883
|
end: cursor,
|
|
@@ -44094,6 +45986,15 @@ function cancelBangSuggestionRequest() {
|
|
|
44094
45986
|
function showCommandSuggestionList() {
|
|
44095
45987
|
elements.commandSuggest.hidden = false;
|
|
44096
45988
|
elements.promptInput?.setAttribute("aria-expanded", "true");
|
|
45989
|
+
const hasChoices = elements.commandSuggest.querySelector(".command-suggest-item") !== null;
|
|
45990
|
+
let hint = elements.commandSuggest.querySelector(".command-suggest-hint");
|
|
45991
|
+
if (hasChoices && !hint) {
|
|
45992
|
+
hint = make("div", "command-suggest-hint", "↑↓ navigate · Enter or Tab accept · Esc close");
|
|
45993
|
+
hint.setAttribute("aria-hidden", "true");
|
|
45994
|
+
elements.commandSuggest.append(hint);
|
|
45995
|
+
} else if (!hasChoices && hint) {
|
|
45996
|
+
hint.remove();
|
|
45997
|
+
}
|
|
44097
45998
|
}
|
|
44098
45999
|
|
|
44099
46000
|
function hideCommandSuggestions() {
|
|
@@ -44257,6 +46158,9 @@ async function renderPathSuggestions(trigger, { keepIndex = false } = {}) {
|
|
|
44257
46158
|
elements.commandSuggest.setAttribute("aria-busy", "true");
|
|
44258
46159
|
|
|
44259
46160
|
try {
|
|
46161
|
+
// Debounce keystrokes: one directory scan per pause instead of one per character.
|
|
46162
|
+
await new Promise((resolve) => setTimeout(resolve, PATH_SUGGEST_DEBOUNCE_MS));
|
|
46163
|
+
if (requestSerial !== pathSuggestRequestSerial || controller.signal.aborted) return;
|
|
44260
46164
|
const response = await api(`/api/path-suggestions?query=${encodeURIComponent(trigger.query)}`, { signal: controller.signal });
|
|
44261
46165
|
if (requestSerial !== pathSuggestRequestSerial || document.activeElement !== elements.promptInput) return;
|
|
44262
46166
|
pathSuggestions = normalizePathSuggestions(response.data?.suggestions || []);
|
|
@@ -44546,6 +46450,16 @@ function commandPaletteCoreItems() {
|
|
|
44546
46450
|
{ kind: "Pi", label: "/scoped-models", description: "Manage model cycling scope", keywords: "models cycle ctrl p", run: () => runNativeCommandMenu("/scoped-models") },
|
|
44547
46451
|
{ kind: "Pi", label: "/tools", description: "Manage active tools", keywords: "capabilities", run: () => runNativeCommandMenu("/tools") },
|
|
44548
46452
|
{ kind: "Pi", label: "/skills", description: "Manage active skills", keywords: "system prompt", run: () => runNativeCommandMenu("/skills") },
|
|
46453
|
+
{ kind: "Pi", label: "/theme", description: "Choose the Web UI theme", keywords: "dark light colors appearance", run: () => openNativeThemeSelector() },
|
|
46454
|
+
{ 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() },
|
|
46455
|
+
{ kind: "Git", label: "Git changes", description: "Review and stage local changes with diffs", keywords: "git diff stage unstage discard status", run: () => openGitChangesDialog() },
|
|
46456
|
+
{ kind: "Action", label: "Files panel", description: "Open the Files section of the Control Deck", keywords: "tree browse project explorer", run: () => revealSidePanelSectionById("files") },
|
|
46457
|
+
{ kind: "Action", label: "Git panel", description: "Open the Git section of the Control Deck", keywords: "repository status history", run: () => revealSidePanelSectionById("git") },
|
|
46458
|
+
{ kind: "Action", label: "Events log", description: "Open the Events section of the Control Deck", keywords: "errors warnings log diagnostics", run: () => revealEventsSection() },
|
|
46459
|
+
{ 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 }) },
|
|
46460
|
+
{ 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 }) },
|
|
46461
|
+
{ kind: "Action", label: "Show all controls", description: "Restore every hidden button and input tag", keywords: "visibility hidden restore controls buttons", run: () => showAllControls() },
|
|
46462
|
+
{ kind: "Action", label: "Reset control visibility", description: "Return hidden/visible controls to the defaults", keywords: "visibility defaults controls buttons", run: () => resetControlVisibilityDefaults() },
|
|
44549
46463
|
];
|
|
44550
46464
|
if (tabs.length) {
|
|
44551
46465
|
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 +46518,32 @@ function buildCommandPaletteItems() {
|
|
|
44604
46518
|
];
|
|
44605
46519
|
}
|
|
44606
46520
|
|
|
46521
|
+
// Ranking: label prefix > label word-start > label contains > description/keywords only.
|
|
46522
|
+
// Ties keep catalog order (actions, tabs, models, commands), so results stay predictable.
|
|
46523
|
+
function paletteItemScore(item, query) {
|
|
46524
|
+
const label = paletteText(item.label);
|
|
46525
|
+
const tokens = query.split(/\s+/).filter(Boolean);
|
|
46526
|
+
let score = 0;
|
|
46527
|
+
for (const token of tokens) {
|
|
46528
|
+
if (label.startsWith(token)) score += 40;
|
|
46529
|
+
else if (label.replace(/^\//, "").startsWith(token)) score += 36;
|
|
46530
|
+
else if (new RegExp(`(^|[\\s/_-])${token.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`).test(label)) score += 24;
|
|
46531
|
+
else if (label.includes(token)) score += 12;
|
|
46532
|
+
else score += 1;
|
|
46533
|
+
}
|
|
46534
|
+
return score;
|
|
46535
|
+
}
|
|
46536
|
+
|
|
44607
46537
|
function filteredCommandPaletteItems() {
|
|
44608
46538
|
const query = paletteText(elements.commandPaletteInput?.value || "").trim();
|
|
44609
46539
|
const items = buildCommandPaletteItems();
|
|
44610
|
-
|
|
46540
|
+
if (!query) return items.slice(0, 80);
|
|
46541
|
+
return items
|
|
46542
|
+
.map((item, index) => ({ item, index, score: paletteItemMatches(item, query) ? paletteItemScore(item, query) : -1 }))
|
|
46543
|
+
.filter((entry) => entry.score >= 0)
|
|
46544
|
+
.sort((a, b) => b.score - a.score || a.index - b.index)
|
|
46545
|
+
.slice(0, 80)
|
|
46546
|
+
.map((entry) => entry.item);
|
|
44611
46547
|
}
|
|
44612
46548
|
|
|
44613
46549
|
function setCommandPaletteIndex(index) {
|
|
@@ -44711,6 +46647,7 @@ function reportRefreshFailures(results, prefix = "") {
|
|
|
44711
46647
|
|
|
44712
46648
|
async function refreshAll(tabContext = activeTabContext()) {
|
|
44713
46649
|
if (!tabContext.tabId) return;
|
|
46650
|
+
noteRecentFullRefresh();
|
|
44714
46651
|
const results = await Promise.allSettled([
|
|
44715
46652
|
refreshState(tabContext),
|
|
44716
46653
|
refreshMessages(tabContext),
|
|
@@ -44802,7 +46739,16 @@ async function reconcileForegroundState(reason = "resume") {
|
|
|
44802
46739
|
renderMobilePhoneExperience();
|
|
44803
46740
|
}
|
|
44804
46741
|
|
|
46742
|
+
// A tab activation/boot just ran the full refresh; the immediately following "event stream
|
|
46743
|
+
// reconnect" and "page show" signals would otherwise repeat every catalog fetch a second time.
|
|
46744
|
+
let recentFullRefreshFreshUntil = 0;
|
|
46745
|
+
|
|
46746
|
+
function noteRecentFullRefresh() {
|
|
46747
|
+
recentFullRefreshFreshUntil = performance.now() + 3_000;
|
|
46748
|
+
}
|
|
46749
|
+
|
|
44805
46750
|
function scheduleForegroundReconcile(reason = "resume", delay = FOREGROUND_RECONCILE_DELAY_MS) {
|
|
46751
|
+
if ((reason === "event stream reconnect" || reason === "page show") && performance.now() < recentFullRefreshFreshUntil && !foregroundTranscriptCatchUpRequired) return;
|
|
44806
46752
|
clearTimeout(foregroundReconcileTimer);
|
|
44807
46753
|
foregroundReconcileTimer = setTimeout(() => {
|
|
44808
46754
|
foregroundReconcileTimer = null;
|
|
@@ -45057,10 +47003,31 @@ function clearPromptFromShortcut() {
|
|
|
45057
47003
|
if (document.activeElement !== input) return false;
|
|
45058
47004
|
if (input.selectionStart !== input.selectionEnd) return false;
|
|
45059
47005
|
if (!input.value) return false;
|
|
45060
|
-
input.value
|
|
47006
|
+
const previous = input.value;
|
|
47007
|
+
// Go through the editing command so the browser's own Ctrl+Z can bring the text back.
|
|
47008
|
+
let cleared = false;
|
|
47009
|
+
try {
|
|
47010
|
+
input.select();
|
|
47011
|
+
cleared = document.execCommand("delete");
|
|
47012
|
+
} catch {
|
|
47013
|
+
cleared = false;
|
|
47014
|
+
}
|
|
47015
|
+
if (!cleared || input.value) input.value = "";
|
|
45061
47016
|
resizePromptInput();
|
|
45062
47017
|
renderCommandSuggestions();
|
|
45063
47018
|
addEvent("prompt cleared", "info");
|
|
47019
|
+
offerUndo({
|
|
47020
|
+
message: "Prompt cleared (Ctrl/Cmd+C with nothing selected).",
|
|
47021
|
+
undo: () => {
|
|
47022
|
+
input.value = previous;
|
|
47023
|
+
resizePromptInput();
|
|
47024
|
+
renderCommandSuggestions();
|
|
47025
|
+
input.focus({ preventScroll: true });
|
|
47026
|
+
input.setSelectionRange(previous.length, previous.length);
|
|
47027
|
+
},
|
|
47028
|
+
successMessage: "Prompt restored.",
|
|
47029
|
+
timeoutMs: 8000,
|
|
47030
|
+
});
|
|
45064
47031
|
return true;
|
|
45065
47032
|
}
|
|
45066
47033
|
|
|
@@ -45437,13 +47404,15 @@ function handleExtensionUiRequest(request) {
|
|
|
45437
47404
|
if (request.statusText) {
|
|
45438
47405
|
statusEntries.set(statusKey, request.statusText);
|
|
45439
47406
|
if (statusKey === GIT_FOOTER_WEBUI_STATUS_KEY) {
|
|
45440
|
-
const
|
|
47407
|
+
const footerPayload = parseGitFooterWebuiPayloadRaw(request.statusText);
|
|
47408
|
+
const validPayload = !!footerPayload;
|
|
45441
47409
|
cacheGitFooterWebuiPayload(request.statusText, request.tabId);
|
|
45442
47410
|
settleGitFooterPayload(
|
|
45443
47411
|
request.tabId || activeTabId,
|
|
45444
47412
|
validPayload ? "ready" : "failed",
|
|
45445
47413
|
validPayload ? "" : "Git footer returned invalid status data — refresh to retry",
|
|
45446
47414
|
);
|
|
47415
|
+
if (footerPayload) syncClaudeUsageFromGitFooterPayload(footerPayload);
|
|
45447
47416
|
}
|
|
45448
47417
|
} else {
|
|
45449
47418
|
statusEntries.delete(statusKey);
|
|
@@ -45946,24 +47915,25 @@ function supervisorContinuityKey(event, fallbackTabId = activeTabId) {
|
|
|
45946
47915
|
function scheduleSupervisorContinuityRefresh(event, { gap = false } = {}) {
|
|
45947
47916
|
const tabContext = activeTabContext(event?.tabId || activeTabId);
|
|
45948
47917
|
const key = supervisorContinuityKey(event, tabContext.tabId);
|
|
45949
|
-
if (!key || !tabContext.tabId || !isCurrentTabContext(tabContext)) return;
|
|
47918
|
+
if (!key || !tabContext.tabId || !isCurrentTabContext(tabContext) || closingTerminalTabIds.has(tabContext.tabId)) return;
|
|
45950
47919
|
|
|
45951
47920
|
if (gap && !supervisorGapWarnings.has(key)) {
|
|
45952
47921
|
supervisorGapWarnings.add(key);
|
|
45953
|
-
addEvent("Buffered live output may be incomplete; refreshing tabs, state, and transcript from Pi.", "
|
|
47922
|
+
addEvent("Buffered live output may be incomplete; refreshing tabs, state, and transcript from Pi.", "info");
|
|
45954
47923
|
}
|
|
45955
47924
|
if (supervisorContinuityRefreshes.has(key)) return;
|
|
45956
47925
|
|
|
45957
47926
|
const timer = setTimeout(async () => {
|
|
45958
47927
|
try {
|
|
47928
|
+
if (closingTerminalTabIds.has(tabContext.tabId)) return;
|
|
45959
47929
|
const results = await Promise.allSettled([refreshTabs()]);
|
|
45960
|
-
if (isCurrentTabContext(tabContext)) {
|
|
47930
|
+
if (isCurrentTabContext(tabContext) && !closingTerminalTabIds.has(tabContext.tabId)) {
|
|
45961
47931
|
results.push(...(await Promise.allSettled([
|
|
45962
47932
|
refreshState(tabContext),
|
|
45963
47933
|
refreshMessages(tabContext, { authoritative: true }),
|
|
45964
47934
|
])));
|
|
45965
47935
|
}
|
|
45966
|
-
if (!isCurrentTabContext(tabContext)) return;
|
|
47936
|
+
if (!isCurrentTabContext(tabContext) || closingTerminalTabIds.has(tabContext.tabId)) return;
|
|
45967
47937
|
for (const result of results) {
|
|
45968
47938
|
if (result.status === "rejected") addEvent(`continuity refresh failed: ${result.reason?.message || String(result.reason)}`, "error");
|
|
45969
47939
|
}
|
|
@@ -46022,6 +47992,7 @@ const TRANSCRIPT_STREAM_BARRIER_EVENT_TYPES = new Set([
|
|
|
46022
47992
|
function beginForegroundTranscriptCatchUp() {
|
|
46023
47993
|
foregroundTranscriptCatchUpRequired = true;
|
|
46024
47994
|
backgroundReconnectSnapshotFresh = false;
|
|
47995
|
+
flushNormalStreamRenders("visibility-hidden");
|
|
46025
47996
|
streamOutputController.cancel();
|
|
46026
47997
|
if (!eventSource) return;
|
|
46027
47998
|
eventStreamPausedForBackground = true;
|
|
@@ -46046,6 +48017,10 @@ function dispatchTranscriptStreamEvent(event) {
|
|
|
46046
48017
|
function flushTranscriptStreamBarrier(event) {
|
|
46047
48018
|
if (!TRANSCRIPT_STREAM_BARRIER_EVENT_TYPES.has(event?.type)) return;
|
|
46048
48019
|
streamOutputController.barrier(event.type);
|
|
48020
|
+
if (["message_end", "agent_end", "agent_settled", "compaction_end", "pi_process_exit", "pi_process_error"].includes(event.type)) {
|
|
48021
|
+
fallbackStreamDerivedOutput(`settlement:${event.type}`);
|
|
48022
|
+
}
|
|
48023
|
+
flushNormalStreamRenders(event.type);
|
|
46049
48024
|
reconcileUnknownTranscriptEvidenceAtBarrier(event);
|
|
46050
48025
|
if (event.type === "pi_process_exit" || event.type === "pi_process_error") streamOutputController.cancel();
|
|
46051
48026
|
}
|
|
@@ -46080,6 +48055,7 @@ function handleEvent(event) {
|
|
|
46080
48055
|
// the same run identity semantics as the foreground tab.
|
|
46081
48056
|
if (event?.type === "agent_start") beginToolBoundaryRun(event);
|
|
46082
48057
|
if (eventMayAffectSkillUsage(event)) trackSkillsFromEvent(event);
|
|
48058
|
+
if (handleGitWorkflowFallbackLifecycleEvent(event)) return;
|
|
46083
48059
|
if (!eventTargetsActiveTab(event)) {
|
|
46084
48060
|
handleInactiveTabEvent(event);
|
|
46085
48061
|
return;
|
|
@@ -46172,12 +48148,18 @@ function handleEvent(event) {
|
|
|
46172
48148
|
}
|
|
46173
48149
|
break;
|
|
46174
48150
|
}
|
|
46175
|
-
case "webui_app_runner_update":
|
|
46176
|
-
|
|
48151
|
+
case "webui_app_runner_update": {
|
|
48152
|
+
const runTabId = event.tabId || activeTabId;
|
|
48153
|
+
const previousRun = appRunnerDataByTab.get(runTabId)?.activeRun || null;
|
|
48154
|
+
setAppRunnerData(runTabId, { cwd: event.cwd, activeRun: event.activeRun });
|
|
46177
48155
|
renderAppRunnerControls();
|
|
46178
|
-
|
|
46179
|
-
|
|
48156
|
+
// A chatty dev server sends several updates per second; append only the new lines to the
|
|
48157
|
+
// existing widget instead of rebuilding every widget and the tab strip each time.
|
|
48158
|
+
if (!patchAppRunnerWidgetInPlace(runTabId, previousRun, event.activeRun)) renderWidgets();
|
|
48159
|
+
const runningChanged = Boolean(previousRun && appRunnerIsRunning(previousRun)) !== Boolean(event.activeRun && appRunnerIsRunning(event.activeRun));
|
|
48160
|
+
if (!previousRun !== !event.activeRun || runningChanged || previousRun?.id !== event.activeRun?.id) renderTabs();
|
|
46180
48161
|
break;
|
|
48162
|
+
}
|
|
46181
48163
|
case "webui_git_changed":
|
|
46182
48164
|
invalidateGitPanelRepository(event.root);
|
|
46183
48165
|
break;
|
|
@@ -46276,7 +48258,7 @@ function handleEvent(event) {
|
|
|
46276
48258
|
if (!assistantErrorSurfacedThisRun && event.willRetry !== true) {
|
|
46277
48259
|
const message = assistantErrorFromAgentEnd(event);
|
|
46278
48260
|
if (message) {
|
|
46279
|
-
surfaceRuntimeDiagnostic("Assistant error", message);
|
|
48261
|
+
surfaceRuntimeDiagnostic("Assistant error", describeAssistantFailure(message), "error", { actions: assistantFailureActions(event.tabId || activeTabId) });
|
|
46280
48262
|
assistantErrorSurfacedThisRun = true;
|
|
46281
48263
|
}
|
|
46282
48264
|
}
|
|
@@ -46296,7 +48278,7 @@ function handleEvent(event) {
|
|
|
46296
48278
|
streamMessageActive = false;
|
|
46297
48279
|
if (event.message?.role === "assistant" && event.message.stopReason === "error") {
|
|
46298
48280
|
const message = String(event.message.errorMessage || streamProviderErrorText || "The assistant request failed without an error message.").trim();
|
|
46299
|
-
surfaceRuntimeDiagnostic("Assistant error", message);
|
|
48281
|
+
surfaceRuntimeDiagnostic("Assistant error", describeAssistantFailure(message), "error", { actions: assistantFailureActions(event.tabId || activeTabId) });
|
|
46300
48282
|
assistantErrorSurfacedThisRun = true;
|
|
46301
48283
|
}
|
|
46302
48284
|
streamProviderErrorText = "";
|
|
@@ -46323,7 +48305,7 @@ function handleEvent(event) {
|
|
|
46323
48305
|
handleToolExecutionStart(event);
|
|
46324
48306
|
}
|
|
46325
48307
|
setRunIndicatorActivity(`Running tool: ${runIndicatorToolName(event.toolName)}…`);
|
|
46326
|
-
if (claimToolBoundaryRecord(event, "log:start")) addEvent(
|
|
48308
|
+
if (claimToolBoundaryRecord(event, "log:start")) addEvent(...toolLifecycleEventArguments(event, "start"));
|
|
46327
48309
|
break;
|
|
46328
48310
|
case "tool_execution_end": {
|
|
46329
48311
|
if (voiceConversationActiveFor(event.tabId || activeTabId)) voiceConversation.setAssistantActivity({ toolRunning: false });
|
|
@@ -46343,7 +48325,7 @@ function handleEvent(event) {
|
|
|
46343
48325
|
handleToolExecutionEnd(event);
|
|
46344
48326
|
}
|
|
46345
48327
|
setRunIndicatorActivity(`Tool ${runIndicatorToolName(event.toolName)} ${event.isError ? "failed" : "finished"}; waiting for the agent's next step…`);
|
|
46346
|
-
if (claimToolBoundaryRecord(event, "log:end")) addEvent(
|
|
48328
|
+
if (claimToolBoundaryRecord(event, "log:end")) addEvent(...toolLifecycleEventArguments(event, "finish"));
|
|
46347
48329
|
// Compact tool shells deliberately defer rich body construction to the
|
|
46348
48330
|
// final transcript reconciliation; normal mode retains its live card.
|
|
46349
48331
|
scheduleSemanticReconcile({ footerData: true }, tabContext);
|
|
@@ -46399,22 +48381,24 @@ function handleEvent(event) {
|
|
|
46399
48381
|
const seconds = Math.max(0, Math.ceil(Number(event.delayMs || 0) / 1000));
|
|
46400
48382
|
const retryText = `Retrying (${event.attempt || "?"}/${event.maxAttempts || "?"}) in ${seconds}s after: ${event.errorMessage || "model/provider error"}`;
|
|
46401
48383
|
setRunIndicatorActivity(retryText);
|
|
46402
|
-
addEvent(retryText, "warn");
|
|
46403
|
-
addTransientMessage({ role: "warn", title: "auto retry", content: retryText, level: "warn" });
|
|
48384
|
+
addEvent(retryText, "warn", { notify: false });
|
|
48385
|
+
addTransientMessage({ role: "warn", title: "auto retry", content: retryText, level: "warn", key: "auto-retry" });
|
|
46404
48386
|
break;
|
|
46405
48387
|
}
|
|
46406
48388
|
case "auto_retry_end":
|
|
46407
48389
|
if (event.success === false) {
|
|
46408
48390
|
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" });
|
|
48391
|
+
addEvent(retryError, "error", { notify: false });
|
|
48392
|
+
addTransientMessage({ role: "error", title: "auto retry failed", content: describeAssistantFailure(retryError), level: "error", key: "auto-retry", actions: assistantFailureActions(event.tabId || activeTabId) });
|
|
46411
48393
|
} else {
|
|
46412
48394
|
addEvent(`retry recovered after ${event.attempt || "?"} attempt(s)`);
|
|
48395
|
+
transientMessages = transientMessages.filter((message) => message?.key !== "auto-retry");
|
|
48396
|
+
renderAllMessages();
|
|
46413
48397
|
}
|
|
46414
48398
|
break;
|
|
46415
48399
|
case "extension_error": {
|
|
46416
48400
|
const message = `${event.extensionPath || "extension"}${event.event ? ` during ${event.event}` : ""}: ${event.error || "unknown extension error"}`;
|
|
46417
|
-
addEvent(message, "error");
|
|
48401
|
+
addEvent(message, "error", { notify: false });
|
|
46418
48402
|
addTransientMessage({ role: "error", title: "extension error", content: message, level: "error" });
|
|
46419
48403
|
break;
|
|
46420
48404
|
}
|
|
@@ -46452,9 +48436,12 @@ function handleEvent(event) {
|
|
|
46452
48436
|
}
|
|
46453
48437
|
|
|
46454
48438
|
function connectEvents(tabContext = activeTabContext(), { requestedMode = "auto", fallbackAttempted = false } = {}) {
|
|
48439
|
+
flushNormalStreamRenders("reconnect");
|
|
48440
|
+
cancelNormalStreamRenders();
|
|
46455
48441
|
eventSource?.close();
|
|
46456
48442
|
eventSource = null;
|
|
46457
48443
|
streamOutputController.cancel();
|
|
48444
|
+
fallbackStreamDerivedOutput("reconnect");
|
|
46458
48445
|
resetCompactLiveOutput();
|
|
46459
48446
|
activeOutputMode = "normal";
|
|
46460
48447
|
outputModeAcknowledged = false;
|
|
@@ -46486,7 +48473,9 @@ function connectEvents(tabContext = activeTabContext(), { requestedMode = "auto"
|
|
|
46486
48473
|
source.onerror = () => {
|
|
46487
48474
|
if (eventSource !== source || !isCurrentTabContext(tabContext)) return;
|
|
46488
48475
|
streamOutputController.flush();
|
|
48476
|
+
flushNormalStreamRenders("disconnect");
|
|
46489
48477
|
streamOutputController.cancel();
|
|
48478
|
+
fallbackStreamDerivedOutput("disconnect");
|
|
46490
48479
|
if (compactOutputActive()) compactLiveScheduler.flushNow();
|
|
46491
48480
|
addEvent("event stream disconnected; browser will retry", "warn");
|
|
46492
48481
|
fetch("/api/health", { cache: "no-store" }).catch((error) => setBackendOffline(true, error));
|
|
@@ -46515,12 +48504,22 @@ elements.promptListSaveButton?.addEventListener("click", saveDisplayedPromptList
|
|
|
46515
48504
|
elements.promptListRunListButton?.addEventListener("click", () => runDisplayedPromptList());
|
|
46516
48505
|
elements.promptListCloseButton?.addEventListener("click", () => elements.promptListDialog?.close());
|
|
46517
48506
|
elements.promptListDialog?.querySelector("form")?.addEventListener("submit", (event) => event.preventDefault());
|
|
46518
|
-
elements.attachmentTextCancelButton?.addEventListener("click", closeTextAttachmentEditor);
|
|
48507
|
+
elements.attachmentTextCancelButton?.addEventListener("click", () => closeTextAttachmentEditor());
|
|
46519
48508
|
elements.attachmentTextSaveButton?.addEventListener("click", saveTextAttachmentEdit);
|
|
46520
48509
|
elements.attachmentTextEditor?.addEventListener("input", () => {
|
|
48510
|
+
if (activeTextAttachmentEditor) activeTextAttachmentEditor.dirty = true;
|
|
46521
48511
|
renderTextAttachmentEditorMeta();
|
|
46522
48512
|
setAttachmentTextStatus("Unsaved attachment edits.", "warn");
|
|
46523
48513
|
});
|
|
48514
|
+
elements.attachmentTextDialog?.addEventListener("cancel", (event) => {
|
|
48515
|
+
if (!activeTextAttachmentEditor?.dirty) return;
|
|
48516
|
+
event.preventDefault();
|
|
48517
|
+
confirmDiscardEdits({ what: "unsaved attachment edits", target: "The attachment text" }).then((confirmed) => {
|
|
48518
|
+
if (!confirmed) return;
|
|
48519
|
+
if (activeTextAttachmentEditor) activeTextAttachmentEditor.dirty = false;
|
|
48520
|
+
elements.attachmentTextDialog.close();
|
|
48521
|
+
});
|
|
48522
|
+
});
|
|
46524
48523
|
elements.attachmentTextDialog?.addEventListener("close", () => {
|
|
46525
48524
|
activeTextAttachmentEditor = null;
|
|
46526
48525
|
if (elements.attachmentTextEditor) elements.attachmentTextEditor.value = "";
|
|
@@ -46532,9 +48531,21 @@ elements.attachmentTextDialog?.addEventListener("keydown", (event) => {
|
|
|
46532
48531
|
if (!elements.attachmentTextSaveButton?.disabled) saveTextAttachmentEdit();
|
|
46533
48532
|
});
|
|
46534
48533
|
elements.attachmentTextDialog?.querySelector("form")?.addEventListener("submit", (event) => event.preventDefault());
|
|
46535
|
-
elements.skillEditorCancelButton?.addEventListener("click", closeSkillEditor);
|
|
48534
|
+
elements.skillEditorCancelButton?.addEventListener("click", () => closeSkillEditor());
|
|
46536
48535
|
elements.skillEditorSaveButton?.addEventListener("click", saveSkillEditor);
|
|
46537
|
-
elements.skillEditorText?.addEventListener("input", () =>
|
|
48536
|
+
elements.skillEditorText?.addEventListener("input", () => {
|
|
48537
|
+
if (activeSkillEditor) activeSkillEditor.dirty = true;
|
|
48538
|
+
setSkillEditorStatus("Unsaved skill edits.", "warn");
|
|
48539
|
+
});
|
|
48540
|
+
elements.skillEditorDialog?.addEventListener("cancel", (event) => {
|
|
48541
|
+
if (!activeSkillEditor?.dirty) return;
|
|
48542
|
+
event.preventDefault();
|
|
48543
|
+
confirmDiscardEdits({ what: "unsaved skill edits", target: activeSkillEditor?.path || activeSkillEditor?.name || "SKILL.md" }).then((confirmed) => {
|
|
48544
|
+
if (!confirmed) return;
|
|
48545
|
+
if (activeSkillEditor) activeSkillEditor.dirty = false;
|
|
48546
|
+
elements.skillEditorDialog.close();
|
|
48547
|
+
});
|
|
48548
|
+
});
|
|
46538
48549
|
elements.skillEditorDialog?.addEventListener("close", () => {
|
|
46539
48550
|
activeSkillEditor = null;
|
|
46540
48551
|
if (elements.skillEditorText) elements.skillEditorText.value = "";
|
|
@@ -46626,6 +48637,18 @@ elements.btwButton?.addEventListener("click", () => sendBtwPromptFromButton());
|
|
|
46626
48637
|
elements.terminalTabsToggleButton.addEventListener("click", () => {
|
|
46627
48638
|
setMobileTabsExpanded(!document.body.classList.contains("mobile-tabs-expanded"), { restoreFocus: true });
|
|
46628
48639
|
});
|
|
48640
|
+
// Tablist keyboard semantics: Left/Right/Home/End move focus between terminal tabs.
|
|
48641
|
+
elements.tabBar?.addEventListener("keydown", (event) => {
|
|
48642
|
+
if (!["ArrowLeft", "ArrowRight", "Home", "End"].includes(event.key) || event.altKey || event.ctrlKey || event.metaKey) return;
|
|
48643
|
+
const tabsInStrip = [...elements.tabBar.querySelectorAll('[role="tab"]')].filter((node) => !node.disabled && node.offsetParent !== null);
|
|
48644
|
+
const index = tabsInStrip.indexOf(document.activeElement);
|
|
48645
|
+
if (index === -1) return;
|
|
48646
|
+
event.preventDefault();
|
|
48647
|
+
const next = event.key === "Home" ? 0
|
|
48648
|
+
: event.key === "End" ? tabsInStrip.length - 1
|
|
48649
|
+
: (index + (event.key === "ArrowRight" ? 1 : -1) + tabsInStrip.length) % tabsInStrip.length;
|
|
48650
|
+
tabsInStrip[next]?.focus({ preventScroll: false });
|
|
48651
|
+
});
|
|
46629
48652
|
elements.newTabButton.addEventListener("click", (event) => {
|
|
46630
48653
|
event.stopPropagation();
|
|
46631
48654
|
openNewTabMenu();
|
|
@@ -46679,6 +48702,7 @@ elements.gitWorkflowButton.addEventListener("click", () => {
|
|
|
46679
48702
|
});
|
|
46680
48703
|
const publishMenuContainer = elements.publishButton.parentElement;
|
|
46681
48704
|
elements.publishButton.addEventListener("click", () => {
|
|
48705
|
+
clearComposerMenuDismissal(elements.publishButton.parentElement);
|
|
46682
48706
|
setNativeCommandMenuOpen(false);
|
|
46683
48707
|
setAppRunnerMenuOpen(false);
|
|
46684
48708
|
setOptionsMenuOpen(false);
|
|
@@ -46704,6 +48728,7 @@ publishMenuContainer?.addEventListener("focusout", () => {
|
|
|
46704
48728
|
});
|
|
46705
48729
|
const nativeCommandMenuContainer = elements.nativeCommandMenuButton.parentElement;
|
|
46706
48730
|
elements.nativeCommandMenuButton.addEventListener("click", () => {
|
|
48731
|
+
clearComposerMenuDismissal(elements.nativeCommandMenuButton.parentElement);
|
|
46707
48732
|
setPublishMenuOpen(false);
|
|
46708
48733
|
setAppRunnerMenuOpen(false);
|
|
46709
48734
|
setOptionsMenuOpen(false);
|
|
@@ -46771,6 +48796,7 @@ appRunnerMenuContainer?.addEventListener("focusout", () => {
|
|
|
46771
48796
|
});
|
|
46772
48797
|
const optionsMenuContainer = elements.optionsMenuButton.parentElement;
|
|
46773
48798
|
elements.optionsMenuButton.addEventListener("click", () => {
|
|
48799
|
+
clearComposerMenuDismissal(elements.optionsMenuButton.parentElement);
|
|
46774
48800
|
setPublishMenuOpen(false);
|
|
46775
48801
|
setNativeCommandMenuOpen(false);
|
|
46776
48802
|
setAppRunnerMenuOpen(false);
|
|
@@ -46945,6 +48971,13 @@ elements.nativeCommandDialog.addEventListener("cancel", (event) => {
|
|
|
46945
48971
|
event.preventDefault();
|
|
46946
48972
|
closeNativeCommandDialog();
|
|
46947
48973
|
});
|
|
48974
|
+
// The dialog form uses method="dialog"; without this, Enter inside the filter box (or any
|
|
48975
|
+
// settings text field) implicitly submits and closes the dialog without choosing anything.
|
|
48976
|
+
elements.nativeCommandDialog.querySelector("form")?.addEventListener("submit", (event) => {
|
|
48977
|
+
event.preventDefault();
|
|
48978
|
+
if (document.activeElement === elements.nativeCommandSearch) activateNativeSelectorHighlight();
|
|
48979
|
+
});
|
|
48980
|
+
elements.nativeCommandSearch.addEventListener("keydown", handleNativeSelectorSearchKeydown);
|
|
46948
48981
|
elements.nativeCommandDialog.addEventListener("close", () => {
|
|
46949
48982
|
elements.nativeCommandSearch.oninput = null;
|
|
46950
48983
|
nativeSettingsDirty = false;
|
|
@@ -46952,6 +48985,18 @@ elements.nativeCommandDialog.addEventListener("close", () => {
|
|
|
46952
48985
|
});
|
|
46953
48986
|
elements.undoToastButton?.addEventListener("click", () => runOfferedUndo());
|
|
46954
48987
|
elements.undoToastDismissButton?.addEventListener("click", dismissUndoToast);
|
|
48988
|
+
elements.textPromptDialog?.querySelector("form")?.addEventListener("submit", (event) => {
|
|
48989
|
+
event.preventDefault();
|
|
48990
|
+
submitTextPrompt();
|
|
48991
|
+
});
|
|
48992
|
+
elements.textPromptCancelButton?.addEventListener("click", () => finishTextPrompt(null));
|
|
48993
|
+
elements.textPromptDialog?.addEventListener("cancel", (event) => {
|
|
48994
|
+
event.preventDefault();
|
|
48995
|
+
finishTextPrompt(null);
|
|
48996
|
+
});
|
|
48997
|
+
elements.textPromptDialog?.addEventListener("close", () => {
|
|
48998
|
+
if (activeTextPromptResolve) finishTextPrompt(null);
|
|
48999
|
+
});
|
|
46955
49000
|
elements.confirmationCancelButton?.addEventListener("click", () => finishApplicationConfirmation(false));
|
|
46956
49001
|
elements.confirmationConfirmButton?.addEventListener("click", () => finishApplicationConfirmation(true));
|
|
46957
49002
|
elements.gitPullErrorMergeButton?.addEventListener("click", () => integrateGitPullDivergence("merge"));
|
|
@@ -47049,7 +49094,21 @@ function abortButtonHoldSeconds() {
|
|
|
47049
49094
|
}
|
|
47050
49095
|
|
|
47051
49096
|
function abortButtonReadyTitle() {
|
|
47052
|
-
return `Hold Esc or the Abort button for ${abortButtonHoldSeconds()}
|
|
49097
|
+
return `Hold Esc or the Abort button for about ${abortButtonHoldSeconds()} second to abort the active Pi run`;
|
|
49098
|
+
}
|
|
49099
|
+
|
|
49100
|
+
// A quick tap/click on Abort deliberately does nothing (the hold prevents accidental aborts), but
|
|
49101
|
+
// silently doing nothing reads as "broken". Show what to do for a moment instead.
|
|
49102
|
+
function showAbortTapHint() {
|
|
49103
|
+
if (!isAbortAvailable() || isAbortLongPressActive() || abortRequestInFlight) return;
|
|
49104
|
+
clearTimeout(abortTapHintTimer);
|
|
49105
|
+
elements.abortButton.classList.add("tap-hint");
|
|
49106
|
+
elements.abortButton.textContent = "Hold to abort";
|
|
49107
|
+
abortTapHintTimer = setTimeout(() => {
|
|
49108
|
+
abortTapHintTimer = null;
|
|
49109
|
+
elements.abortButton.classList.remove("tap-hint");
|
|
49110
|
+
if (!isAbortLongPressActive() && !abortRequestInFlight) elements.abortButton.textContent = "Abort";
|
|
49111
|
+
}, ABORT_TAP_HINT_MS);
|
|
47053
49112
|
}
|
|
47054
49113
|
|
|
47055
49114
|
function suppressEmptyPromptEscapeAction({ untilKeyup = false, graceMs = EMPTY_PROMPT_ESCAPE_AFTER_ABORT_GRACE_MS } = {}) {
|
|
@@ -47157,7 +49216,7 @@ function resetAbortLongPressAffordance() {
|
|
|
47157
49216
|
abortLongPressReleasePending = false;
|
|
47158
49217
|
elements.abortButton.classList.remove("long-pressing");
|
|
47159
49218
|
elements.abortButton.style.removeProperty("--abort-long-press-duration");
|
|
47160
|
-
if (!abortRequestInFlight) {
|
|
49219
|
+
if (!abortRequestInFlight && !abortTapHintTimer) {
|
|
47161
49220
|
elements.abortButton.textContent = "Abort";
|
|
47162
49221
|
elements.abortButton.title = isAbortAvailable() ? abortButtonReadyTitle() : "Abort is available while Pi is running";
|
|
47163
49222
|
elements.abortButton.setAttribute("aria-label", elements.abortButton.title);
|
|
@@ -47168,6 +49227,7 @@ async function abortActiveRun({ source = "button" } = {}) {
|
|
|
47168
49227
|
if (abortRequestInFlight || !isAbortAvailable()) return;
|
|
47169
49228
|
const tabContext = activeTabContext();
|
|
47170
49229
|
streamOutputController.barrier("user-abort");
|
|
49230
|
+
flushNormalStreamRenders("user-abort");
|
|
47171
49231
|
reconcileUnknownTranscriptEvidenceAtBarrier({ type: "user_abort", tabId: tabContext.tabId });
|
|
47172
49232
|
abortRequestInFlight = true;
|
|
47173
49233
|
resetAbortLongPressAffordance();
|
|
@@ -47237,7 +49297,11 @@ elements.abortButton.addEventListener("keyup", (event) => {
|
|
|
47237
49297
|
});
|
|
47238
49298
|
elements.abortButton.addEventListener("click", (event) => {
|
|
47239
49299
|
event.preventDefault();
|
|
47240
|
-
if (abortLongPressHandled)
|
|
49300
|
+
if (abortLongPressHandled) {
|
|
49301
|
+
abortLongPressHandled = false;
|
|
49302
|
+
return;
|
|
49303
|
+
}
|
|
49304
|
+
showAbortTapHint();
|
|
47241
49305
|
});
|
|
47242
49306
|
elements.newSessionButton.addEventListener("click", async () => {
|
|
47243
49307
|
setComposerActionsOpen(false);
|
|
@@ -47300,6 +49364,8 @@ elements.modelSearchInput?.addEventListener("keydown", (event) => {
|
|
|
47300
49364
|
elements.modelSearchInput.focus();
|
|
47301
49365
|
}
|
|
47302
49366
|
});
|
|
49367
|
+
elements.modelSelect?.addEventListener("change", () => setControlsPendingModel(elements.modelSelect.value));
|
|
49368
|
+
elements.thinkingSelect?.addEventListener("change", () => setControlsPendingThinking(elements.thinkingSelect.value));
|
|
47303
49369
|
elements.setModelButton.addEventListener("click", async () => {
|
|
47304
49370
|
if (!elements.modelSelect.value) return;
|
|
47305
49371
|
const tabContext = activeTabContext();
|
|
@@ -47307,6 +49373,7 @@ elements.setModelButton.addEventListener("click", async () => {
|
|
|
47307
49373
|
const selected = JSON.parse(elements.modelSelect.value);
|
|
47308
49374
|
const response = await api("/api/model", { method: "POST", body: selected, tabId: tabContext.tabId });
|
|
47309
49375
|
if (isCurrentTabContext(tabContext)) {
|
|
49376
|
+
setControlsPendingModel("");
|
|
47310
49377
|
applyOptimisticModelSelection(response.data || selected, tabContext);
|
|
47311
49378
|
await refreshState(tabContext);
|
|
47312
49379
|
}
|
|
@@ -47319,13 +49386,15 @@ elements.setThinkingButton.addEventListener("click", async () => {
|
|
|
47319
49386
|
try {
|
|
47320
49387
|
const response = await api("/api/thinking", { method: "POST", body: { level: elements.thinkingSelect.value }, tabId: tabContext.tabId });
|
|
47321
49388
|
if (isCurrentTabContext(tabContext)) {
|
|
49389
|
+
setControlsPendingThinking("");
|
|
47322
49390
|
applyOptimisticThinkingSelection(response.data, tabContext);
|
|
47323
49391
|
if (response.data?.pending) {
|
|
47324
49392
|
addEvent(response.data.message || `Thinking level ${response.data.level} will apply to the next prompt.`, "info");
|
|
47325
49393
|
} else if (response.data?.level) {
|
|
47326
49394
|
const requested = response.data.requestedLevel;
|
|
47327
49395
|
const effective = response.data.level;
|
|
47328
|
-
|
|
49396
|
+
if (requested && requested !== effective) addEvent(`Thinking level set to ${effective}: the active model does not support ${requested}.`, "warn");
|
|
49397
|
+
else addEvent(`Thinking level set to ${effective}.`, "info");
|
|
47329
49398
|
}
|
|
47330
49399
|
await refreshState(tabContext);
|
|
47331
49400
|
}
|
|
@@ -47656,6 +49725,9 @@ document.addEventListener("pointerdown", (event) => {
|
|
|
47656
49725
|
if (elements.gitFooterContextMenu && !elements.gitFooterContextMenu.hidden && !event.target?.closest?.(".git-footer-context-menu")) {
|
|
47657
49726
|
closeGitFooterContextMenu();
|
|
47658
49727
|
}
|
|
49728
|
+
if (elements.eventTreeContextMenu && !elements.eventTreeContextMenu.hidden && !event.target?.closest?.(".event-tree-context-menu")) {
|
|
49729
|
+
closeEventTreeContextMenu();
|
|
49730
|
+
}
|
|
47659
49731
|
}, { passive: true });
|
|
47660
49732
|
document.addEventListener("pointermove", (event) => {
|
|
47661
49733
|
if (openTerminalTabGroupKey && !event.target?.closest?.(".terminal-tab-group")) {
|
|
@@ -47676,6 +49748,13 @@ function shouldHandleNativeAppShortcut(event) {
|
|
|
47676
49748
|
return event.target === elements.promptInput || !isTextEntryTarget(event.target);
|
|
47677
49749
|
}
|
|
47678
49750
|
|
|
49751
|
+
// TUI-parity chords (Ctrl+P model cycle, Ctrl+T thinking output, Ctrl+O tool output, Ctrl+C
|
|
49752
|
+
// clear, Shift+Tab thinking level) only apply while the composer has focus. Elsewhere they must
|
|
49753
|
+
// keep their browser meaning (print, reverse Tab navigation, copy, …).
|
|
49754
|
+
function isComposerScopedShortcutTarget(event) {
|
|
49755
|
+
return event.target === elements.promptInput;
|
|
49756
|
+
}
|
|
49757
|
+
|
|
47679
49758
|
function handleNativeAppShortcut(event) {
|
|
47680
49759
|
if (!shouldHandleNativeAppShortcut(event)) return;
|
|
47681
49760
|
const key = event.key;
|
|
@@ -47692,6 +49771,17 @@ function handleNativeAppShortcut(event) {
|
|
|
47692
49771
|
openNativeModelSelector();
|
|
47693
49772
|
return;
|
|
47694
49773
|
}
|
|
49774
|
+
if (!ctrlOrMeta && !event.metaKey && event.altKey && key === "Enter") {
|
|
49775
|
+
event.preventDefault();
|
|
49776
|
+
if (hasComposerPayload()) sendPrompt("follow-up");
|
|
49777
|
+
return;
|
|
49778
|
+
}
|
|
49779
|
+
if (!ctrlOrMeta && event.altKey && key === "ArrowUp") {
|
|
49780
|
+
event.preventDefault();
|
|
49781
|
+
restoreQueuedMessagesToComposerFromShortcut();
|
|
49782
|
+
return;
|
|
49783
|
+
}
|
|
49784
|
+
if (!isComposerScopedShortcutTarget(event)) return;
|
|
47695
49785
|
if (ctrlOrMeta && !event.altKey && lowerKey === "p") {
|
|
47696
49786
|
event.preventDefault();
|
|
47697
49787
|
cycleModelFromShortcut(event.shiftKey ? "backward" : "forward");
|
|
@@ -47714,16 +49804,6 @@ function handleNativeAppShortcut(event) {
|
|
|
47714
49804
|
if (!event.ctrlKey && !event.metaKey && !event.altKey && event.shiftKey && key === "Tab") {
|
|
47715
49805
|
event.preventDefault();
|
|
47716
49806
|
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
49807
|
}
|
|
47728
49808
|
}
|
|
47729
49809
|
|
|
@@ -47884,6 +49964,8 @@ elements.chatSearchNextButton?.addEventListener("click", () => stepChatSearch(1)
|
|
|
47884
49964
|
elements.chatSearchCloseButton?.addEventListener("click", closeChatSearch);
|
|
47885
49965
|
window.addEventListener("keydown", (event) => {
|
|
47886
49966
|
if ((event.ctrlKey || event.metaKey) && !event.altKey && !event.shiftKey && event.key.toLowerCase() === "f") {
|
|
49967
|
+
// Inside a modal dialog (settings, palette, pickers) leave the browser's own find alone.
|
|
49968
|
+
if (document.querySelector("dialog[open]")) return;
|
|
47887
49969
|
event.preventDefault();
|
|
47888
49970
|
if (activeFileViewer && elements.fileViewerPane?.contains(event.target)) openFileViewerSearch();
|
|
47889
49971
|
else openChatSearch();
|
|
@@ -47893,6 +49975,7 @@ window.addEventListener("keydown", (event) => {
|
|
|
47893
49975
|
window.addEventListener("keydown", handleNativeAppShortcut, { capture: true });
|
|
47894
49976
|
document.addEventListener("visibilitychange", () => {
|
|
47895
49977
|
if (document.visibilityState === "visible") {
|
|
49978
|
+
flushNormalStreamRenders("visibility-recovery");
|
|
47896
49979
|
scheduleForegroundReconcile("visibility resume", 0);
|
|
47897
49980
|
refreshSubagents().finally(() => scheduleRefreshSubagents());
|
|
47898
49981
|
} else {
|
|
@@ -47994,18 +50077,26 @@ window.addEventListener("keydown", (event) => {
|
|
|
47994
50077
|
}
|
|
47995
50078
|
if (publishMenuOpen) {
|
|
47996
50079
|
setPublishMenuOpen(false);
|
|
50080
|
+
armComposerMenuDismissal(elements.publishButton?.parentElement);
|
|
50081
|
+
elements.publishButton?.focus({ preventScroll: true });
|
|
47997
50082
|
return;
|
|
47998
50083
|
}
|
|
47999
50084
|
if (nativeCommandMenuOpen) {
|
|
48000
50085
|
setNativeCommandMenuOpen(false);
|
|
50086
|
+
armComposerMenuDismissal(elements.nativeCommandMenuButton?.parentElement);
|
|
50087
|
+
elements.nativeCommandMenuButton?.focus({ preventScroll: true });
|
|
48001
50088
|
return;
|
|
48002
50089
|
}
|
|
48003
50090
|
if (appRunnerMenuOpen) {
|
|
48004
50091
|
setAppRunnerMenuOpen(false);
|
|
50092
|
+
armComposerMenuDismissal(elements.appRunnerMenuButton?.parentElement);
|
|
50093
|
+
elements.appRunnerMenuButton?.focus({ preventScroll: true });
|
|
48005
50094
|
return;
|
|
48006
50095
|
}
|
|
48007
50096
|
if (optionsMenuOpen) {
|
|
48008
50097
|
setOptionsMenuOpen(false);
|
|
50098
|
+
armComposerMenuDismissal(elements.optionsMenuButton?.parentElement);
|
|
50099
|
+
elements.optionsMenuButton?.focus({ preventScroll: true });
|
|
48009
50100
|
return;
|
|
48010
50101
|
}
|
|
48011
50102
|
if (conversationVoiceMenuOpen) {
|
|
@@ -48117,7 +50208,7 @@ elements.refreshCodexUsageButton?.addEventListener("click", () => {
|
|
|
48117
50208
|
refreshCodexUsage({ forceAuthRefresh: true }).finally(() => scheduleRefreshCodexUsage());
|
|
48118
50209
|
});
|
|
48119
50210
|
elements.refreshClaudeUsageButton?.addEventListener("click", () => {
|
|
48120
|
-
refreshClaudeUsage().finally(() => scheduleRefreshClaudeUsage());
|
|
50211
|
+
refreshClaudeUsage({ forceCli: true }).finally(() => scheduleRefreshClaudeUsage());
|
|
48121
50212
|
});
|
|
48122
50213
|
elements.fileTreeRefreshButton?.addEventListener("click", () => refreshFileTreeRoot().catch((error) => addEvent(error.message || String(error), "error")));
|
|
48123
50214
|
elements.fileTreeRoot?.addEventListener("keydown", handleFileTreeKeydown);
|
|
@@ -48135,6 +50226,59 @@ elements.fileTreeSearchInput?.addEventListener("keydown", (event) => {
|
|
|
48135
50226
|
}
|
|
48136
50227
|
});
|
|
48137
50228
|
elements.fileTreeSearchClearButton?.addEventListener("click", () => clearFileTreeSearch({ focus: true }));
|
|
50229
|
+
syncEventDisplayModeUi();
|
|
50230
|
+
syncEventFilterUi();
|
|
50231
|
+
elements.eventFilterSelect?.addEventListener("change", () => setEventFilter(elements.eventFilterSelect.value));
|
|
50232
|
+
elements.eventLog?.addEventListener("contextmenu", (event) => {
|
|
50233
|
+
const line = event.target?.closest?.(".event") || null;
|
|
50234
|
+
if (!line && event.target !== elements.eventLog) return;
|
|
50235
|
+
showEventTreeContextMenu(event, line);
|
|
50236
|
+
});
|
|
50237
|
+
elements.eventLog?.addEventListener("keydown", (event) => {
|
|
50238
|
+
if (event.key !== "ContextMenu" && !(event.shiftKey && event.key === "F10")) return;
|
|
50239
|
+
const line = event.target?.closest?.(".event");
|
|
50240
|
+
if (!line || !elements.eventLog.contains(line)) return;
|
|
50241
|
+
const rect = line.getBoundingClientRect();
|
|
50242
|
+
showEventTreeContextMenu({
|
|
50243
|
+
preventDefault: () => event.preventDefault(),
|
|
50244
|
+
stopPropagation: () => event.stopPropagation(),
|
|
50245
|
+
clientX: rect.left + Math.min(rect.width, 24),
|
|
50246
|
+
clientY: rect.bottom,
|
|
50247
|
+
}, line);
|
|
50248
|
+
});
|
|
50249
|
+
elements.eventTreeContextMenu?.addEventListener("keydown", (event) => {
|
|
50250
|
+
const items = [...elements.eventTreeContextMenu.querySelectorAll('[role="menuitem"]:not([disabled]):not([hidden]), [role="menuitemradio"]:not([disabled]):not([hidden])')];
|
|
50251
|
+
const index = items.indexOf(document.activeElement);
|
|
50252
|
+
if (event.key === "Escape") {
|
|
50253
|
+
event.preventDefault();
|
|
50254
|
+
closeEventTreeContextMenu();
|
|
50255
|
+
} else if (event.key === "ArrowDown" || event.key === "ArrowUp") {
|
|
50256
|
+
event.preventDefault();
|
|
50257
|
+
const direction = event.key === "ArrowDown" ? 1 : -1;
|
|
50258
|
+
items[(Math.max(0, index) + direction + items.length) % items.length]?.focus({ preventScroll: true });
|
|
50259
|
+
} else if (event.key === "Home" || event.key === "End") {
|
|
50260
|
+
event.preventDefault();
|
|
50261
|
+
items[event.key === "Home" ? 0 : items.length - 1]?.focus({ preventScroll: true });
|
|
50262
|
+
}
|
|
50263
|
+
});
|
|
50264
|
+
elements.eventDisplayDetailedAction?.addEventListener("click", () => {
|
|
50265
|
+
setEventDisplayMode("detailed");
|
|
50266
|
+
closeEventTreeContextMenu();
|
|
50267
|
+
});
|
|
50268
|
+
elements.eventDisplayCompactAction?.addEventListener("click", () => {
|
|
50269
|
+
setEventDisplayMode("compact");
|
|
50270
|
+
closeEventTreeContextMenu();
|
|
50271
|
+
});
|
|
50272
|
+
elements.eventTreeContextMenuAction?.addEventListener("click", () => void navigateEventTreeBoundary());
|
|
50273
|
+
window.addEventListener("storage", (event) => {
|
|
50274
|
+
if (event.key === EVENT_DISPLAY_MODE_STORAGE_KEY) setEventDisplayMode(event.newValue, { persist: false });
|
|
50275
|
+
if (event.key === EVENT_FILTER_STORAGE_KEY) setEventFilter(event.newValue, { persist: false });
|
|
50276
|
+
});
|
|
50277
|
+
window.addEventListener("resize", () => closeEventTreeContextMenu(), { passive: true });
|
|
50278
|
+
document.addEventListener("scroll", () => {
|
|
50279
|
+
if (!eventTreeContextMenuState || performance.now() - eventTreeContextMenuState.openedAt < 100) return;
|
|
50280
|
+
closeEventTreeContextMenu();
|
|
50281
|
+
}, { capture: true, passive: true });
|
|
48138
50282
|
elements.fileContextMenu?.addEventListener("keydown", (event) => {
|
|
48139
50283
|
const items = [...elements.fileContextMenu.querySelectorAll('[role="menuitem"]:not([disabled])')];
|
|
48140
50284
|
const index = items.indexOf(document.activeElement);
|
|
@@ -48209,10 +50353,23 @@ elements.visibilityContextMenu?.addEventListener("click", (event) => {
|
|
|
48209
50353
|
return;
|
|
48210
50354
|
}
|
|
48211
50355
|
const action = button.dataset.visibilityMenuAction;
|
|
48212
|
-
if (action === "
|
|
50356
|
+
if (action === "open-setup") {
|
|
50357
|
+
const trigger = visibilityContextMenuState?.trigger;
|
|
50358
|
+
closeVisibilityContextMenu({ returnFocus: false });
|
|
50359
|
+
openControlVisibilitySetupDialog(trigger);
|
|
50360
|
+
} else if (action === "hide") {
|
|
48213
50361
|
const entryId = visibilityContextMenuState?.entryId;
|
|
48214
|
-
|
|
48215
|
-
|
|
50362
|
+
closeVisibilityContextMenu({ returnFocus: false });
|
|
50363
|
+
if (entryId) {
|
|
50364
|
+
const label = CONTROL_VISIBILITY_REGISTRY.get(entryId)?.label || "control";
|
|
50365
|
+
setControlVisibilityHidden(entryId, true);
|
|
50366
|
+
elements.promptInput?.focus({ preventScroll: true });
|
|
50367
|
+
offerUndo({
|
|
50368
|
+
message: `Hid ${label}. Right-click a toolbar area (or use the command palette) to show hidden controls again.`,
|
|
50369
|
+
undo: () => setControlVisibilityHidden(entryId, false),
|
|
50370
|
+
successMessage: `${label} is visible again.`,
|
|
50371
|
+
});
|
|
50372
|
+
}
|
|
48216
50373
|
} else if (action === "show-all") {
|
|
48217
50374
|
closeVisibilityContextMenu();
|
|
48218
50375
|
showAllControls();
|
|
@@ -48221,6 +50378,28 @@ elements.visibilityContextMenu?.addEventListener("click", (event) => {
|
|
|
48221
50378
|
resetControlVisibilityDefaults();
|
|
48222
50379
|
}
|
|
48223
50380
|
});
|
|
50381
|
+
elements.controlVisibilitySetupBody?.addEventListener("change", (event) => {
|
|
50382
|
+
const checkbox = event.target?.closest?.("[data-visibility-setup-id]");
|
|
50383
|
+
if (!(checkbox instanceof HTMLInputElement)) return;
|
|
50384
|
+
const entry = CONTROL_VISIBILITY_REGISTRY.get(checkbox.dataset.visibilitySetupId);
|
|
50385
|
+
if (!entry) return;
|
|
50386
|
+
setControlVisibilityHidden(entry.id, !checkbox.checked);
|
|
50387
|
+
refreshControlVisibilitySetupDialog();
|
|
50388
|
+
setControlVisibilitySetupStatus(`${entry.label} is ${checkbox.checked ? "shown" : "hidden"} by preference.`);
|
|
50389
|
+
});
|
|
50390
|
+
elements.controlVisibilitySetupShowAllButton?.addEventListener("click", () => {
|
|
50391
|
+
showAllControls();
|
|
50392
|
+
refreshControlVisibilitySetupDialog();
|
|
50393
|
+
setControlVisibilitySetupStatus("All optional controls are shown by preference.");
|
|
50394
|
+
});
|
|
50395
|
+
elements.controlVisibilitySetupResetButton?.addEventListener("click", () => {
|
|
50396
|
+
resetControlVisibilityDefaults();
|
|
50397
|
+
refreshControlVisibilitySetupDialog();
|
|
50398
|
+
setControlVisibilitySetupStatus("Control visibility was reset to its defaults.");
|
|
50399
|
+
});
|
|
50400
|
+
elements.controlVisibilitySetupCloseButton?.addEventListener("click", () => elements.controlVisibilitySetupDialog?.close());
|
|
50401
|
+
elements.controlVisibilitySetupDialog?.querySelector("form")?.addEventListener("submit", (event) => event.preventDefault());
|
|
50402
|
+
elements.controlVisibilitySetupDialog?.addEventListener("close", restoreControlVisibilitySetupFocus);
|
|
48224
50403
|
elements.gitFooterContextMenu?.addEventListener("keydown", (event) => {
|
|
48225
50404
|
const items = [...elements.gitFooterContextMenu.querySelectorAll('[role="menuitem"]:not([disabled])')];
|
|
48226
50405
|
const index = items.indexOf(document.activeElement);
|
|
@@ -48245,6 +50424,7 @@ elements.gitFooterContextMenu?.addEventListener("click", (event) => {
|
|
|
48245
50424
|
if (action === "disable") void disableGitFooterContextChip(state.key, state.label);
|
|
48246
50425
|
else if (action === "visibility") openGitFooterVisibilityDialog();
|
|
48247
50426
|
});
|
|
50427
|
+
elements.fileTreeNewFileButton?.addEventListener("click", () => createFileTreeEntry(null, "file").catch((error) => addEvent(error.message || String(error), "error")));
|
|
48248
50428
|
elements.fileContextMenu?.addEventListener("click", (event) => {
|
|
48249
50429
|
const button = event.target?.closest?.("[data-file-menu-action]");
|
|
48250
50430
|
if (!button) return;
|
|
@@ -48255,6 +50435,8 @@ elements.fileContextMenu?.addEventListener("click", (event) => {
|
|
|
48255
50435
|
if (action === "open-default") openPathInDefaultEditor(entry.path).catch((error) => addEvent(error.message || String(error), "error"));
|
|
48256
50436
|
else if (action === "open-webui") openFileTreeEntryInWebui(entry).catch((error) => addEvent(error.message || String(error), "error"));
|
|
48257
50437
|
else if (action === "move") moveFileTreeEntry(entry).catch((error) => addEvent(error.message || String(error), "error"));
|
|
50438
|
+
else if (action === "new-file") createFileTreeEntry(entry, "file").catch((error) => addEvent(error.message || String(error), "error"));
|
|
50439
|
+
else if (action === "new-folder") createFileTreeEntry(entry, "directory").catch((error) => addEvent(error.message || String(error), "error"));
|
|
48258
50440
|
else if (action === "delete") deleteFileTreeEntry(entry).catch((error) => addEvent(error.message || String(error), "error"));
|
|
48259
50441
|
});
|
|
48260
50442
|
elements.fileViewerOpenDefaultButton?.addEventListener("click", () => openPathInDefaultEditor(currentFileViewerPath()));
|
|
@@ -48267,7 +50449,20 @@ elements.terminalTabsResizeHandle?.addEventListener("keydown", handleTerminalTab
|
|
|
48267
50449
|
elements.fileViewerResizeHandle?.addEventListener("pointerdown", beginFileViewerResize);
|
|
48268
50450
|
elements.fileViewerResizeHandle?.addEventListener("keydown", handleFileViewerResizeKeydown);
|
|
48269
50451
|
elements.fileViewerSaveButton?.addEventListener("click", () => saveActiveFileViewer());
|
|
48270
|
-
elements.fileViewerCloseButton?.addEventListener("click",
|
|
50452
|
+
elements.fileViewerCloseButton?.addEventListener("click", async () => {
|
|
50453
|
+
if (activeFileViewer?.dirty && !(await confirmDiscardEdits({ what: "unsaved file edits", target: activeFileViewer.path }))) return;
|
|
50454
|
+
closeFileViewer();
|
|
50455
|
+
});
|
|
50456
|
+
// Reload/close with unsaved file edits or a non-empty composer asks first (browser-native prompt).
|
|
50457
|
+
window.addEventListener("pagehide", () => persistDesktopDrafts());
|
|
50458
|
+
window.addEventListener("beforeunload", (event) => {
|
|
50459
|
+
persistDesktopDrafts();
|
|
50460
|
+
// Text drafts are persisted above; only unsaved file edits and file attachments would be lost.
|
|
50461
|
+
const attachmentsPending = activeTabId ? attachmentsForTab(activeTabId).some((attachment) => attachment?.file) : false;
|
|
50462
|
+
if (!activeFileViewer?.dirty && !attachmentsPending) return;
|
|
50463
|
+
event.preventDefault();
|
|
50464
|
+
event.returnValue = "";
|
|
50465
|
+
});
|
|
48271
50466
|
elements.fileViewerChangesModeButton?.addEventListener("click", () => setFileViewerMode("changes"));
|
|
48272
50467
|
elements.fileViewerSourceModeButton?.addEventListener("click", () => setFileViewerMode("source"));
|
|
48273
50468
|
elements.fileViewerPreviewModeButton?.addEventListener("click", () => setFileViewerMode("preview"));
|
|
@@ -48367,9 +50562,60 @@ elements.promptInput.addEventListener("paste", handleAttachmentPaste);
|
|
|
48367
50562
|
elements.composer.addEventListener("dragover", handleComposerDragOver);
|
|
48368
50563
|
elements.composer.addEventListener("dragleave", handleComposerDragLeave);
|
|
48369
50564
|
elements.composer.addEventListener("drop", handleComposerDrop);
|
|
50565
|
+
// A file dropped anywhere else (transcript, panels, empty chrome) must never navigate the tab
|
|
50566
|
+
// away from the app; treat the whole window as an attachment drop zone unless a more specific
|
|
50567
|
+
// target (composer, file tree) already handled it.
|
|
50568
|
+
window.addEventListener("dragover", (event) => {
|
|
50569
|
+
if (event.defaultPrevented || !isFileDrag(event)) return;
|
|
50570
|
+
event.preventDefault();
|
|
50571
|
+
if (event.dataTransfer) event.dataTransfer.dropEffect = "copy";
|
|
50572
|
+
});
|
|
50573
|
+
window.addEventListener("drop", (event) => {
|
|
50574
|
+
if (event.defaultPrevented || !isFileDrag(event)) return;
|
|
50575
|
+
event.preventDefault();
|
|
50576
|
+
elements.composer.classList.remove("drag-over");
|
|
50577
|
+
addAttachmentFiles(event.dataTransfer?.files, "drop");
|
|
50578
|
+
});
|
|
50579
|
+
|
|
50580
|
+
// Enter accepts the highlighted suggestion (like Tab) unless the token already equals it,
|
|
50581
|
+
// in which case Enter falls through to send. Ctrl/Cmd+Enter always sends.
|
|
50582
|
+
function highlightedSuggestionAlreadyTyped() {
|
|
50583
|
+
const index = commandSuggestIndex;
|
|
50584
|
+
if (suggestionMode === "path") {
|
|
50585
|
+
const suggestion = pathSuggestions[index];
|
|
50586
|
+
const trigger = getPathTrigger();
|
|
50587
|
+
if (!suggestion || !trigger) return true;
|
|
50588
|
+
const typed = String(trigger.query || "").replace(/\\/g, "/");
|
|
50589
|
+
const target = String(suggestion.path || "").replace(/\\/g, "/");
|
|
50590
|
+
return typed === target || typed === target.replace(/\/$/, "");
|
|
50591
|
+
}
|
|
50592
|
+
if (suggestionMode === "bang") {
|
|
50593
|
+
const suggestion = bangSuggestions[index];
|
|
50594
|
+
const trigger = getBangTrigger();
|
|
50595
|
+
if (!suggestion || !trigger) return true;
|
|
50596
|
+
const typed = `${trigger.bangPrefix || ""}${trigger.query || ""}`;
|
|
50597
|
+
return typed === String(suggestion.insertText || "");
|
|
50598
|
+
}
|
|
50599
|
+
const command = commandSuggestions[index];
|
|
50600
|
+
const trigger = getCommandTrigger();
|
|
50601
|
+
if (!command || !trigger) return true;
|
|
50602
|
+
const typed = String(trigger.query || "").toLowerCase();
|
|
50603
|
+
return typed === String(command.name || "").toLowerCase() || typed === String(command.invokeName || "").toLowerCase();
|
|
50604
|
+
}
|
|
50605
|
+
|
|
50606
|
+
function shouldAcceptSuggestionFromEnter(event) {
|
|
50607
|
+
if (event.key !== "Enter" || event.shiftKey || event.ctrlKey || event.metaKey || event.altKey || event.isComposing) return false;
|
|
50608
|
+
if (elements.commandSuggest.hidden || activeSuggestionCount() === 0) return false;
|
|
50609
|
+
return !highlightedSuggestionAlreadyTyped();
|
|
50610
|
+
}
|
|
48370
50611
|
|
|
48371
50612
|
elements.promptInput.addEventListener("keydown", (event) => {
|
|
48372
50613
|
if (event.defaultPrevented || insertNumpadDecimal(event)) return;
|
|
50614
|
+
if (shouldAcceptSuggestionFromEnter(event)) {
|
|
50615
|
+
event.preventDefault();
|
|
50616
|
+
insertCommandSuggestion();
|
|
50617
|
+
return;
|
|
50618
|
+
}
|
|
48373
50619
|
if (shouldSendPromptFromEnter(event)) {
|
|
48374
50620
|
event.preventDefault();
|
|
48375
50621
|
hideCommandSuggestions();
|
|
@@ -48378,12 +50624,12 @@ elements.promptInput.addEventListener("keydown", (event) => {
|
|
|
48378
50624
|
}
|
|
48379
50625
|
|
|
48380
50626
|
if (!elements.commandSuggest.hidden) {
|
|
48381
|
-
if (event.key === "ArrowDown") {
|
|
50627
|
+
if (event.key === "ArrowDown" && activeSuggestionCount() > 0) {
|
|
48382
50628
|
event.preventDefault();
|
|
48383
50629
|
setActiveCommandSuggestion(commandSuggestIndex + 1);
|
|
48384
50630
|
return;
|
|
48385
50631
|
}
|
|
48386
|
-
if (event.key === "ArrowUp") {
|
|
50632
|
+
if (event.key === "ArrowUp" && activeSuggestionCount() > 0) {
|
|
48387
50633
|
event.preventDefault();
|
|
48388
50634
|
setActiveCommandSuggestion(commandSuggestIndex - 1);
|
|
48389
50635
|
return;
|
|
@@ -48410,7 +50656,8 @@ elements.promptInput.addEventListener("keydown", (event) => {
|
|
|
48410
50656
|
|
|
48411
50657
|
elements.promptInput.addEventListener("input", () => {
|
|
48412
50658
|
resetPromptHistoryNavigation();
|
|
48413
|
-
|
|
50659
|
+
// Typed text always stays editable in the composer; only large pastes become attachments
|
|
50660
|
+
// (handleAttachmentPaste). Ripping a prompt out mid-typing was surprising and lossy.
|
|
48414
50661
|
resizePromptInput();
|
|
48415
50662
|
renderCommandSuggestions();
|
|
48416
50663
|
scheduleMobileContinuityPersist();
|