@firstpick/pi-package-webui 0.8.5 → 0.8.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 +18 -584
- package/bin/pi-webui-launcher.mjs +22 -0
- package/bin/pi-webui-update-supervisor.mjs +86 -0
- package/bin/pi-webui.mjs +933 -554
- package/index.ts +16 -6
- package/lib/component-update-state.mjs +21 -0
- package/lib/git-workflow-preferences.mjs +20 -2
- package/lib/optional-feature-catalog.mjs +1 -0
- package/lib/sampling-parameter-capabilities.mjs +160 -0
- package/lib/session-summary-core.mjs +4 -3
- package/lib/session-summary-preferences.mjs +16 -1
- package/lib/subagent-launch-slots.mjs +14 -2
- package/lib/trust-boundaries.mjs +16 -0
- package/lib/update/executor.mjs +99 -0
- package/lib/update/journal.mjs +175 -0
- package/lib/update/owners.mjs +70 -0
- package/lib/update/plan.mjs +134 -0
- package/lib/update/resolver.mjs +168 -0
- package/lib/update/supervisor.mjs +238 -0
- package/lib/update/verify.mjs +52 -0
- package/lib/update-commands.mjs +25 -13
- package/lib/webui-workspaces.mjs +17 -1
- package/lib/workspace-session-summaries.mjs +400 -0
- package/package.json +4 -4
- package/public/app.js +2487 -349
- package/public/index.html +200 -51
- package/public/middle-button-drag-scroll.mjs +154 -0
- package/public/sampling-parameter-controls.mjs +361 -0
- package/public/service-worker.js +5 -1
- package/public/stream-output-controller.mjs +327 -0
- package/public/styles.css +666 -71
- package/public/theme-contract.mjs +244 -0
- package/session-summary.ts +164 -4
- package/tests/aur-review-widget-static.test.mjs +2 -1
- package/tests/boot-failure-diagnostics.test.mjs +3 -3
- package/tests/browser/control-deck-component-updates.spec.mjs +20 -22
- package/tests/browser/interaction-continuity.spec.mjs +2 -2
- package/tests/browser/middle-button-drag-scroll.spec.mjs +145 -0
- package/tests/browser/persistent-ui-layout.spec.mjs +68 -23
- package/tests/browser/sampling-tooltip.spec.mjs +228 -0
- package/tests/browser/session-summary.spec.mjs +131 -3
- package/tests/browser/stream-output-isolation.spec.mjs +510 -0
- package/tests/browser/update-reconnect.spec.mjs +92 -0
- package/tests/codex-fast-mode-static.test.mjs +2 -2
- package/tests/common-options-submenus-interaction-static.test.mjs +172 -0
- package/tests/common-options-submenus-markup-static.test.mjs +152 -0
- package/tests/component-update-api-static.test.mjs +22 -61
- package/tests/composer-action-grid-reorder-static.test.mjs +3 -3
- package/tests/control-deck-component-updates-static.test.mjs +13 -237
- package/tests/durable-rpc-supervisor-harness.test.mjs +3 -1
- package/tests/fast-mode-client-static.test.mjs +3 -2
- package/tests/feature-decision-output-popup-static.test.mjs +2 -2
- package/tests/feature-system-prompt-optional-feature-static.test.mjs +49 -0
- package/tests/fixtures/fake-pi.mjs +269 -2
- package/tests/fixtures/update/tree-timeout-descendant.mjs +6 -0
- package/tests/fixtures/update/tree-timeout-parent.mjs +11 -0
- package/tests/git-footer-context-menu-static.test.mjs +58 -0
- package/tests/git-workflow-preferences.test.mjs +7 -1
- package/tests/guided-git-aur-review.test.mjs +4 -3
- package/tests/http-endpoints-harness.test.mjs +274 -23
- package/tests/middle-button-drag-scroll-static.test.mjs +24 -0
- package/tests/middle-button-drag-scroll.test.mjs +170 -0
- package/tests/mobile-continuity-tablet-static.test.mjs +3 -3
- package/tests/mobile-foundation-static.test.mjs +5 -6
- package/tests/mobile-phone-experience-static.test.mjs +1 -1
- package/tests/mobile-static.test.mjs +85 -50
- package/tests/native-parity.test.mjs +1 -1
- package/tests/open-issue-wizard-static.test.mjs +2 -3
- package/tests/optional-feature-migration-frontend.test.mjs +9 -5
- package/tests/persistent-ui-layout-static.test.mjs +13 -2
- package/tests/questionnaire-dialog.test.mjs +3 -3
- package/tests/remote-auth-settings-harness.test.mjs +43 -0
- package/tests/rpc-supervisor-host.test.mjs +11 -2
- package/tests/safety-guard-auto-review-harness.test.mjs +117 -0
- package/tests/safety-guard-auto-review-static.test.mjs +34 -0
- package/tests/sampling-native-controls-user-flow.test.mjs +752 -0
- package/tests/sampling-parameter-capabilities.test.mjs +167 -0
- package/tests/sampling-parameter-controls.test.mjs +241 -0
- package/tests/session-sampling-helper.test.mjs +228 -0
- package/tests/session-sampling-http.test.mjs +168 -0
- package/tests/session-sampling-ui-static.test.mjs +370 -0
- package/tests/session-summary-core.test.mjs +205 -10
- package/tests/side-panel-section-height-removal-static.test.mjs +34 -0
- package/tests/side-panel-section-reorder-static.test.mjs +3 -3
- package/tests/staged-content-hash-contract.test.mjs +52 -11
- package/tests/stream-lifecycle-core.test.mjs +134 -0
- package/tests/stream-output-controller.test.mjs +252 -0
- package/tests/stream-output-isolation-static.test.mjs +89 -0
- package/tests/streaming-ui-coupling.test.mjs +50 -0
- package/tests/subagent-gate-visibility.test.mjs +1 -1
- package/tests/subagent-launch-slots-static.test.mjs +1 -1
- package/tests/subagent-launch-slots.test.mjs +18 -1
- package/tests/theme-contract.test.mjs +104 -0
- package/tests/theme-customizer-static.test.mjs +82 -0
- package/tests/theme-scheme-mode.test.mjs +15 -0
- package/tests/ui-layout-settings.test.mjs +18 -1
- package/tests/update-api-harness.test.mjs +111 -0
- package/tests/update-commands.test.mjs +15 -45
- package/tests/update-executor-process-tree-harness.test.mjs +22 -0
- package/tests/update-journal-harness.test.mjs +59 -0
- package/tests/update-lock-multiprocess-harness.test.mjs +46 -0
- package/tests/update-owners.test.mjs +27 -0
- package/tests/update-plan.test.mjs +58 -0
- package/tests/update-resolver.test.mjs +56 -0
- package/tests/update-supervisor-harness.test.mjs +57 -0
- package/tests/update-tab-restore-harness.test.mjs +24 -0
- package/tests/update-verify.test.mjs +31 -0
- package/tests/workspace-files-live-updates-static.test.mjs +13 -4
- package/tests/workspace-session-summaries.test.mjs +288 -0
- package/webui-rpc-helper.mjs +119 -0
package/public/app.js
CHANGED
|
@@ -9,6 +9,20 @@ 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 { createStreamOutputController } from "./stream-output-controller.mjs";
|
|
13
|
+
import { installMiddleButtonDragScroll } from "./middle-button-drag-scroll.mjs";
|
|
14
|
+
import { PI_THEME_EXPORT_FIELDS, THEME_TOKEN_GROUPS, canonicalizeTheme, serializeTheme, themeColorToRgb, validateTheme } from "./theme-contract.mjs";
|
|
15
|
+
import {
|
|
16
|
+
SAMPLING_PARAMETER_CATALOG,
|
|
17
|
+
buildSamplingParametersFromDraft,
|
|
18
|
+
createSamplingControlDraft,
|
|
19
|
+
samplingControlDraftEquals,
|
|
20
|
+
samplingParameterCapability,
|
|
21
|
+
samplingParameterSliderValue,
|
|
22
|
+
splitSamplingParameters,
|
|
23
|
+
summarizePreservedSamplingParameters,
|
|
24
|
+
validateSamplingControlDraft,
|
|
25
|
+
} from "./sampling-parameter-controls.mjs";
|
|
12
26
|
|
|
13
27
|
const $ = (selector) => document.querySelector(selector);
|
|
14
28
|
|
|
@@ -18,9 +32,7 @@ const elements = {
|
|
|
18
32
|
webuiDevBadge: $("#webuiDevBadge"),
|
|
19
33
|
tabBar: $("#tabBar"),
|
|
20
34
|
terminalTabsToggleButton: $("#terminalTabsToggleButton"),
|
|
21
|
-
splitTabButton: $("#splitTabButton"),
|
|
22
35
|
workspaceSaveButton: $("#workspaceSaveButton"),
|
|
23
|
-
summaryHeaderButton: $("#summaryHeaderButton"),
|
|
24
36
|
newTabMenu: $("#newTabMenu"),
|
|
25
37
|
newTabButton: $("#newTabButton"),
|
|
26
38
|
newTabMenuPanel: $("#newTabMenuPanel"),
|
|
@@ -140,7 +152,6 @@ const elements = {
|
|
|
140
152
|
remoteMicStreamingConsentButton: $("#remoteMicStreamingConsentButton"),
|
|
141
153
|
newSessionButton: $("#newSessionButton"),
|
|
142
154
|
compactButton: $("#compactButton"),
|
|
143
|
-
summaryActionButton: $("#summaryActionButton"),
|
|
144
155
|
workflowModeControls: $("#workflowModeControls"),
|
|
145
156
|
workflowModeButton: $("#workflowModeButton"),
|
|
146
157
|
workflowOverlayOpenButton: $("#workflowOverlayOpenButton"),
|
|
@@ -218,6 +229,26 @@ const elements = {
|
|
|
218
229
|
themeSearchResults: $("#themeSearchResults"),
|
|
219
230
|
themeSelect: $("#themeSelect"),
|
|
220
231
|
themeSchemeToggle: $("#themeSchemeToggle"),
|
|
232
|
+
themeCustomizeButton: $("#themeCustomizeButton"),
|
|
233
|
+
themeCustomizerDialog: $("#themeCustomizerDialog"),
|
|
234
|
+
themeCustomizerName: $("#themeCustomizerName"),
|
|
235
|
+
themeCustomizerScope: $("#themeCustomizerScope"),
|
|
236
|
+
themeCustomizerProjectOption: $("#themeCustomizerProjectOption"),
|
|
237
|
+
themeCustomizerScopeHint: $("#themeCustomizerScopeHint"),
|
|
238
|
+
themeCustomizerSourceBadge: $("#themeCustomizerSourceBadge"),
|
|
239
|
+
themeCustomizerVisualFields: $("#themeCustomizerVisualFields"),
|
|
240
|
+
themeCustomizerThinkingMax: $("#themeCustomizerThinkingMax"),
|
|
241
|
+
themeCustomizerVars: $("#themeCustomizerVars"),
|
|
242
|
+
themeCustomizerExportFields: $("#themeCustomizerExportFields"),
|
|
243
|
+
themeCustomizerJson: $("#themeCustomizerJson"),
|
|
244
|
+
themeCustomizerPreview: $("#themeCustomizerPreview"),
|
|
245
|
+
themeCustomizerStatus: $("#themeCustomizerStatus"),
|
|
246
|
+
themeCustomizerOverwrite: $("#themeCustomizerOverwrite"),
|
|
247
|
+
themeCustomizerOverwriteMessage: $("#themeCustomizerOverwriteMessage"),
|
|
248
|
+
themeCustomizerOverwriteButton: $("#themeCustomizerOverwriteButton"),
|
|
249
|
+
themeCustomizerCancelButton: $("#themeCustomizerCancelButton"),
|
|
250
|
+
themeCustomizerResetButton: $("#themeCustomizerResetButton"),
|
|
251
|
+
themeCustomizerSaveButton: $("#themeCustomizerSaveButton"),
|
|
221
252
|
backgroundInput: $("#backgroundInput"),
|
|
222
253
|
backgroundChooseButton: $("#backgroundChooseButton"),
|
|
223
254
|
backgroundClearButton: $("#backgroundClearButton"),
|
|
@@ -296,6 +327,7 @@ const elements = {
|
|
|
296
327
|
fileSelectionSendButton: $("#fileSelectionSendButton"),
|
|
297
328
|
fileContextMenu: $("#fileContextMenu"),
|
|
298
329
|
sidePanelContextMenu: $("#sidePanelContextMenu"),
|
|
330
|
+
gitFooterContextMenu: $("#gitFooterContextMenu"),
|
|
299
331
|
sidePanelResizeHandle: $("#sidePanelResizeHandle"),
|
|
300
332
|
toggleSidePanelButton: $("#toggleSidePanelButton"),
|
|
301
333
|
sidePanelExpandButton: $("#sidePanelExpandButton"),
|
|
@@ -320,6 +352,13 @@ const elements = {
|
|
|
320
352
|
issueWizardBotButton: $("#issueWizardBotButton"),
|
|
321
353
|
issueWizardBotHint: $("#issueWizardBotHint"),
|
|
322
354
|
stateDetails: $("#stateDetails"),
|
|
355
|
+
samplingParametersSupport: $("#samplingParametersSupport"),
|
|
356
|
+
samplingParametersControls: $("#samplingParametersControls"),
|
|
357
|
+
samplingParametersPreserved: $("#samplingParametersPreserved"),
|
|
358
|
+
applySamplingParametersButton: $("#applySamplingParametersButton"),
|
|
359
|
+
resetSamplingParametersButton: $("#resetSamplingParametersButton"),
|
|
360
|
+
reloadSamplingParametersButton: $("#reloadSamplingParametersButton"),
|
|
361
|
+
samplingParametersStatus: $("#samplingParametersStatus"),
|
|
323
362
|
subagentsStatus: $("#subagentsStatus"),
|
|
324
363
|
subagentsAutoClearButton: $("#subagentsAutoClearButton"),
|
|
325
364
|
subagentsClearFinishedButton: $("#subagentsClearFinishedButton"),
|
|
@@ -505,6 +544,7 @@ let tabAttachments = new Map();
|
|
|
505
544
|
let activeTextAttachmentEditor = null;
|
|
506
545
|
let activeSkillEditor = null;
|
|
507
546
|
let fileTreeState = { root: "", entriesByPath: new Map(), expanded: new Set(), loading: new Set(), selectedPath: "", requestSerial: 0, searchQuery: "", searchEntries: [], searchLoading: false, searchTruncated: false, searchTotal: 0, gitStatusRoot: "", gitStatusByPath: new Map() };
|
|
547
|
+
let fileTreeLastRenderSignature = "";
|
|
508
548
|
let activeFileViewer = null;
|
|
509
549
|
let fileViewersByTab = new Map();
|
|
510
550
|
let fileViewerOpenRequestSerial = 0;
|
|
@@ -518,6 +558,7 @@ let fileViewerSearchTimer = null;
|
|
|
518
558
|
let fileViewerSearchHighlightElement = null;
|
|
519
559
|
let fileContextMenuState = null;
|
|
520
560
|
let sidePanelContextMenuState = null;
|
|
561
|
+
let gitFooterContextMenuState = null;
|
|
521
562
|
let sidePanelSectionPointerDrag = null;
|
|
522
563
|
let sidePanelSectionLastDragOverKey = "";
|
|
523
564
|
let sidePanelSectionSuppressClickUntil = 0;
|
|
@@ -543,8 +584,6 @@ let streamThinkingRawText = "";
|
|
|
543
584
|
let streamDerivedTextCache = { rawText: null, assistantText: "", thinkingFormat: null, finalText: "" };
|
|
544
585
|
let streamBubbleVisibleSince = 0;
|
|
545
586
|
let streamBubbleHideTimer = null;
|
|
546
|
-
let streamTextRenderTimer = null;
|
|
547
|
-
let streamTextRenderFrame = null;
|
|
548
587
|
let streamToolCallSeen = false;
|
|
549
588
|
let streamToolCallBubble = null;
|
|
550
589
|
let streamToolCallText = null;
|
|
@@ -568,6 +607,97 @@ let outputModeAcknowledged = false;
|
|
|
568
607
|
let eventSourceOutputModeRequest = "auto";
|
|
569
608
|
let eventSourceOutputModeFallbackAttempted = false;
|
|
570
609
|
const compactLiveScheduler = createSustainedFlushScheduler({ flush: () => flushCompactLiveOutput() });
|
|
610
|
+
const STREAM_ISOLATION_DEBUG_LIMIT = 4096;
|
|
611
|
+
const STREAM_ISOLATION_DEBUG_ENABLED = globalThis.__PI_STREAM_ISOLATION_DEBUG__ === true
|
|
612
|
+
|| new URLSearchParams(window.location.search).get("streamIsolationDebug") === "1";
|
|
613
|
+
const streamIsolationDebugLedger = STREAM_ISOLATION_DEBUG_ENABLED ? {
|
|
614
|
+
version: 1,
|
|
615
|
+
counters: {
|
|
616
|
+
receivedEvents: 0,
|
|
617
|
+
appliedEvents: 0,
|
|
618
|
+
sinkCalls: 0,
|
|
619
|
+
batches: 0,
|
|
620
|
+
barriers: 0,
|
|
621
|
+
overflows: 0,
|
|
622
|
+
unknownEvents: 0,
|
|
623
|
+
staleEvents: 0,
|
|
624
|
+
highWaterPendingCount: 0,
|
|
625
|
+
highWaterPendingBytes: 0,
|
|
626
|
+
},
|
|
627
|
+
receivedIndexes: [],
|
|
628
|
+
appliedIndexes: [],
|
|
629
|
+
records: [],
|
|
630
|
+
unknownEvidence: [],
|
|
631
|
+
} : null;
|
|
632
|
+
const UNKNOWN_TRANSCRIPT_EVIDENCE_LIMIT = 32;
|
|
633
|
+
const UNKNOWN_TRANSCRIPT_EVIDENCE_TEXT_LIMIT = 512;
|
|
634
|
+
const unknownTranscriptEvidence = [];
|
|
635
|
+
const unknownTranscriptOwnersPendingReconcile = new Set();
|
|
636
|
+
|
|
637
|
+
function appendBoundedStreamDiagnostic(list, value, limit = STREAM_ISOLATION_DEBUG_LIMIT) {
|
|
638
|
+
list.push(value);
|
|
639
|
+
if (list.length > limit) list.splice(0, list.length - limit);
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
function recordStreamIsolationDiagnostic(record) {
|
|
643
|
+
const ledger = streamIsolationDebugLedger;
|
|
644
|
+
if (!ledger || !record) return;
|
|
645
|
+
const counters = ledger.counters;
|
|
646
|
+
if (record.type === "receipt") {
|
|
647
|
+
counters.receivedEvents += 1;
|
|
648
|
+
if (Number.isSafeInteger(record.index)) appendBoundedStreamDiagnostic(ledger.receivedIndexes, record.index);
|
|
649
|
+
} else if (record.type === "apply") {
|
|
650
|
+
if (record.applied) {
|
|
651
|
+
counters.appliedEvents += Number(record.sourceCount) || 0;
|
|
652
|
+
counters.sinkCalls += 1;
|
|
653
|
+
for (const index of record.sourceIndexes || []) {
|
|
654
|
+
if (Number.isSafeInteger(index)) appendBoundedStreamDiagnostic(ledger.appliedIndexes, index);
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
if (record.kind === "unknown-message-update") counters.unknownEvents += Number(record.sourceCount) || 1;
|
|
658
|
+
} else if (record.type === "batch") {
|
|
659
|
+
counters.batches += 1;
|
|
660
|
+
} else if (record.type === "barrier") {
|
|
661
|
+
counters.barriers += 1;
|
|
662
|
+
} else if (record.type === "overflow") {
|
|
663
|
+
counters.overflows += 1;
|
|
664
|
+
} else if (record.type === "stale") {
|
|
665
|
+
counters.staleEvents += 1;
|
|
666
|
+
}
|
|
667
|
+
if (record.type === "queued") {
|
|
668
|
+
counters.highWaterPendingCount = Math.max(counters.highWaterPendingCount, Number(record.pendingCount) || 0);
|
|
669
|
+
counters.highWaterPendingBytes = Math.max(counters.highWaterPendingBytes, Number(record.pendingBytes) || 0);
|
|
670
|
+
}
|
|
671
|
+
appendBoundedStreamDiagnostic(ledger.records, {
|
|
672
|
+
...record,
|
|
673
|
+
sourceIndexes: Array.isArray(record.sourceIndexes) ? [...record.sourceIndexes] : undefined,
|
|
674
|
+
});
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
if (streamIsolationDebugLedger) {
|
|
678
|
+
Object.defineProperty(globalThis, "__piStreamIsolationDebug", {
|
|
679
|
+
configurable: true,
|
|
680
|
+
enumerable: false,
|
|
681
|
+
value: streamIsolationDebugLedger,
|
|
682
|
+
});
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
const streamOutputController = createStreamOutputController({
|
|
686
|
+
isOwnerCurrent: (owner) => owner === transcriptStreamOwner(),
|
|
687
|
+
applyTextUpdate: (event) => handleMessageUpdate(event),
|
|
688
|
+
applyThinkingUpdate: (event) => handleMessageUpdate(event),
|
|
689
|
+
applyToolCallUpdate: (event) => handleMessageUpdate(event),
|
|
690
|
+
applyToolExecutionUpdate: (event) => {
|
|
691
|
+
if (!compactOutputActive()) applyTranscriptToolExecutionUpdate(event);
|
|
692
|
+
},
|
|
693
|
+
applyStreamError: (event) => handleMessageUpdate(event),
|
|
694
|
+
applyFollowScroll: () => {
|
|
695
|
+
if (compactOutputActive()) flushCompactLiveOutput();
|
|
696
|
+
scheduleChatFollowScroll();
|
|
697
|
+
},
|
|
698
|
+
onUnknownStreamEvent: preserveUnknownTranscriptEvidence,
|
|
699
|
+
onDiagnostic: streamIsolationDebugLedger ? recordStreamIsolationDiagnostic : undefined,
|
|
700
|
+
});
|
|
571
701
|
let assistantErrorSurfacedThisRun = false;
|
|
572
702
|
let runIndicatorBubble = null;
|
|
573
703
|
let runIndicatorText = null;
|
|
@@ -577,6 +707,29 @@ let runIndicatorRenderFrame = null;
|
|
|
577
707
|
let runIndicatorRenderScroll = false;
|
|
578
708
|
let runIndicatorGraceCheckTimer = null;
|
|
579
709
|
let runIndicatorLastStateCheckAt = 0;
|
|
710
|
+
// Lifecycle ownership is deliberately separate from the transcript-owned
|
|
711
|
+
// activity label: the transcript ticker only repaints its own elapsed-time
|
|
712
|
+
// node, while this watchdog owns the low-frequency canonical state recheck.
|
|
713
|
+
let lifecycleStateWatchdogTimer = null;
|
|
714
|
+
let lifecycleComposerSignature = null;
|
|
715
|
+
// Bounded dedupe of semantic tool-boundary records (skill tags, event log),
|
|
716
|
+
// partitioned by agent-run epoch so provider tool IDs may be reused next turn.
|
|
717
|
+
const TOOL_BOUNDARY_RECORD_LIMIT = 400;
|
|
718
|
+
const recordedToolBoundaryKeys = new Set();
|
|
719
|
+
const toolBoundaryRunEpochByTab = new Map();
|
|
720
|
+
// Dirty flags owned by the coalesced semantic reconciler. Requests remain
|
|
721
|
+
// partitioned by originating tab generation; raw stream deltas never reach it.
|
|
722
|
+
const SEMANTIC_RECONCILE_FLAGS = Object.freeze([
|
|
723
|
+
"messages",
|
|
724
|
+
"state",
|
|
725
|
+
"footer",
|
|
726
|
+
"footerData",
|
|
727
|
+
"feedback",
|
|
728
|
+
"usage",
|
|
729
|
+
"workflow",
|
|
730
|
+
]);
|
|
731
|
+
const semanticReconcilePending = new Map();
|
|
732
|
+
let semanticReconcileFrame = null;
|
|
580
733
|
let runIndicatorLocallyActive = false;
|
|
581
734
|
let runIndicatorRemovalDeferred = false;
|
|
582
735
|
let runIndicatorStartedAt = null;
|
|
@@ -624,6 +777,7 @@ let nativeCommandTabId = null;
|
|
|
624
777
|
let nativeSettingsDirty = false;
|
|
625
778
|
let sessionSummaryOverlayTabId = null;
|
|
626
779
|
let sessionSummaryOverlayFocusReturn = null;
|
|
780
|
+
let sessionSummaryOverlayFocusReturnKey = "";
|
|
627
781
|
const sessionSummaryByTab = new Map();
|
|
628
782
|
let pathPickerState = null;
|
|
629
783
|
let firstTerminalCwdPromptShown = false;
|
|
@@ -653,9 +807,23 @@ let appRunnerSearchPathDraft = "";
|
|
|
653
807
|
let appRunnerSearchPathFeedback = { type: "", message: "" };
|
|
654
808
|
let appRunnerDirectoryBrowserState = { open: false, loading: false, path: "", data: null, error: "" };
|
|
655
809
|
let optionsMenuOpen = false;
|
|
810
|
+
const OPTIONS_SUBMENU_GROUP_SELECTOR = "[data-options-submenu]";
|
|
811
|
+
const OPTIONS_SUBMENU_TRIGGER_SELECTOR = "[data-options-submenu-trigger]";
|
|
812
|
+
const OPTIONS_SUBMENU_PANEL_SELECTOR = "[data-options-submenu-panel]";
|
|
813
|
+
const OPTIONS_SUBMENU_BACK_SELECTOR = "[data-options-submenu-back]";
|
|
814
|
+
const OPTIONS_SUBMENU_LEFT_CLASS = "opens-left";
|
|
815
|
+
const OPTIONS_SUBMENU_DRILL_IN_QUERY = "(hover: none), (pointer: coarse)";
|
|
816
|
+
const OPTIONS_MENU_LABEL_SELECTOR = '.composer-options-menu-item > span:not([aria-hidden="true"]):not(.composer-options-submenu-chevron)';
|
|
817
|
+
const OPTIONS_MENU_LABEL_FONT_SIZE_PROPERTY = "--options-menu-label-font-size";
|
|
818
|
+
const OPTIONS_MENU_LABEL_MIN_FONT_SIZE_PX = 12;
|
|
819
|
+
let openOptionsSubmenuGroup = null;
|
|
820
|
+
let optionsSubmenuObserver = null;
|
|
821
|
+
let optionsSubmenuSyncing = false;
|
|
822
|
+
let optionsMenuLabelFitFrame = 0;
|
|
656
823
|
let availableCommands = [];
|
|
657
824
|
let rawAvailableCommands = [];
|
|
658
825
|
const commandCatalogsByTab = new Map();
|
|
826
|
+
const commandCatalogRefreshesByTab = new Map();
|
|
659
827
|
let commandSuggestions = [];
|
|
660
828
|
let pathSuggestions = [];
|
|
661
829
|
let bangSuggestions = [];
|
|
@@ -732,10 +900,20 @@ let subagentLaunchSlotRequestSerial = 0;
|
|
|
732
900
|
let subagentLaunchSlotReloadRequired = false;
|
|
733
901
|
const subagentLaunchSlotReloadTabs = new Set();
|
|
734
902
|
let subagentLaunchSlotFocusTarget = null;
|
|
903
|
+
let samplingParametersState = null;
|
|
904
|
+
let samplingParametersStateTabId = null;
|
|
905
|
+
const samplingParametersDrafts = new Map();
|
|
906
|
+
let samplingParametersLoading = false;
|
|
907
|
+
let samplingParametersBusy = false;
|
|
908
|
+
let samplingParametersError = "";
|
|
909
|
+
let samplingParametersNotice = "";
|
|
910
|
+
let samplingParametersFeedbackTabId = null;
|
|
911
|
+
let samplingParametersRequestSerial = 0;
|
|
735
912
|
let backendOffline = false;
|
|
736
913
|
let serverRestartInProgress = false;
|
|
737
914
|
let updateRequestInProgress = false;
|
|
738
915
|
let latestUpdateStatus = null;
|
|
916
|
+
let serverBootIdentity = "";
|
|
739
917
|
let updateStatusRefreshTimer = null;
|
|
740
918
|
let updateNotificationHideTimer = null;
|
|
741
919
|
let componentUpdatePollTimer = null;
|
|
@@ -787,9 +965,6 @@ let chatFollowFrame = null;
|
|
|
787
965
|
let chatFollowSettleTimer = null;
|
|
788
966
|
let chatFollowNeedsSettle = false;
|
|
789
967
|
let liveWidgetRenderFrame = null;
|
|
790
|
-
let liveTodoProgressSyncFrame = null;
|
|
791
|
-
let liveTodoProgressPendingText = "";
|
|
792
|
-
let liveTodoProgressPendingTabId = null;
|
|
793
968
|
let lastChatProgrammaticScrollAt = 0;
|
|
794
969
|
let chatUserScrollIntentUntil = 0;
|
|
795
970
|
let chatUserScrollAwayIntentUntil = 0;
|
|
@@ -855,6 +1030,7 @@ const TAB_STORAGE_KEY = "pi-webui-active-tab";
|
|
|
855
1030
|
const PATH_FAST_PICKS_STORAGE_KEY = "pi-webui-path-fast-picks";
|
|
856
1031
|
const AGENT_DONE_NOTIFICATIONS_STORAGE_KEY = "pi-webui-agent-done-notifications";
|
|
857
1032
|
const UPDATE_NOTIFICATION_DISMISS_STORAGE_KEY = "pi-webui-update-notification-dismissed";
|
|
1033
|
+
const OPTIONAL_FEATURE_MIGRATION_DISMISS_STORAGE_KEY = "pi-webui-optional-feature-migration-dismissed";
|
|
858
1034
|
const MOBILE_CONTINUITY_STORAGE_KEY = "pi-webui-mobile-continuity-v1";
|
|
859
1035
|
const MOBILE_INSTALL_EDUCATION_STORAGE_KEY = "pi-webui-mobile-install-education-v1";
|
|
860
1036
|
const MOBILE_CONTINUITY_MAX_SESSIONS = 24;
|
|
@@ -1020,6 +1196,9 @@ const THEME_LIGHT_DEFAULT = "catppuccin-latte";
|
|
|
1020
1196
|
const THEME_DARK_DEFAULT = "catppuccin-mocha";
|
|
1021
1197
|
const THEME_SCHEME_MODES = new Set(["light", "dark", "auto"]);
|
|
1022
1198
|
let themeSchemeMode = "light"; // "light" | "dark" | "auto"; finalized in initializeThemes
|
|
1199
|
+
let themeCatalogScopes = { global: { available: true }, project: { available: false, trusted: false } };
|
|
1200
|
+
let themeCustomizerGeneration = 0;
|
|
1201
|
+
let themeCustomizerState = null;
|
|
1023
1202
|
const TERMINAL_TABS_LAYOUTS = new Set(["top", "left"]);
|
|
1024
1203
|
const TERMINAL_TABS_LAYOUT_LABELS = { top: "Top bar", left: "Left sidebar" };
|
|
1025
1204
|
const SUBAGENT_OPEN_MODES = new Set(["overlay", "tab"]);
|
|
@@ -1054,9 +1233,7 @@ const ABORT_LONG_PRESS_TICK_MS = 100;
|
|
|
1054
1233
|
const ABORT_LONG_PRESS_RELEASE_GRACE_MS = 350;
|
|
1055
1234
|
const EMPTY_PROMPT_ESCAPE_AFTER_ABORT_GRACE_MS = 1000;
|
|
1056
1235
|
const STREAM_OUTPUT_HIDE_DELAY_MS = 300;
|
|
1057
|
-
const STREAM_OUTPUT_TOOLCALL_GUARD_MS = 220;
|
|
1058
1236
|
const STREAM_OUTPUT_MIN_VISIBLE_MS = 900;
|
|
1059
|
-
const TOOL_LIVE_UPDATE_THROTTLE_MS = 80;
|
|
1060
1237
|
const UNEXPOSED_THINKING_TEXT = "No thinking content was exposed by the provider.";
|
|
1061
1238
|
const THINKING_FORMAT_OPEN_TAG_REGEX = /^<think\b[^>]*>/i;
|
|
1062
1239
|
const THINKING_FORMAT_CLOSE_TAG_REGEX = /<\/think\s*>/i;
|
|
@@ -1611,6 +1788,7 @@ function mobileRenderMore() {
|
|
|
1611
1788
|
const page = mobileShellState.surfacePage || "root";
|
|
1612
1789
|
const topics = {
|
|
1613
1790
|
session: ["Session", ["sidePanelSectionSession"]],
|
|
1791
|
+
sampling: ["Sampling parameters", ["sidePanelSectionSampling"]],
|
|
1614
1792
|
usage: ["Usage", ["sidePanelSectionCodexUsage", "sidePanelSectionClaudeUsage"]],
|
|
1615
1793
|
extensions: ["Extensions", ["sidePanelSectionOptionalFeatures"]],
|
|
1616
1794
|
settings: ["Settings", ["sidePanelSectionControls"]],
|
|
@@ -1661,6 +1839,7 @@ function mobileRenderMore() {
|
|
|
1661
1839
|
title.textContent = topic[0];
|
|
1662
1840
|
back.hidden = false;
|
|
1663
1841
|
mobileCanonicalMountContent(host, topic[1], `more:${page}`);
|
|
1842
|
+
if (page === "sampling") ensureSamplingParametersLoaded();
|
|
1664
1843
|
if (page === "commands") mobileShellElement("commandSearchInput")?.focus({ preventScroll: true });
|
|
1665
1844
|
}
|
|
1666
1845
|
|
|
@@ -2204,8 +2383,6 @@ const appRunnerContextLineDraftByRun = new Map();
|
|
|
2204
2383
|
const scopedScrollContinuityByKey = new Map();
|
|
2205
2384
|
const liveToolRuns = new Map();
|
|
2206
2385
|
const liveToolCards = new Map();
|
|
2207
|
-
const liveToolRenderQueue = new Map();
|
|
2208
|
-
let liveToolRenderTimer = null;
|
|
2209
2386
|
// Optional feature detection intentionally checks loaded Pi capabilities (RPC-visible
|
|
2210
2387
|
// commands and live widget events), not npm package folders. This keeps local dev
|
|
2211
2388
|
// symlinks and independently installed packages working.
|
|
@@ -2218,6 +2395,7 @@ const optionalFeatureAvailability = {
|
|
|
2218
2395
|
releaseAur: false,
|
|
2219
2396
|
aurReview: false,
|
|
2220
2397
|
workflows: false,
|
|
2398
|
+
featureSystemPrompt: false,
|
|
2221
2399
|
safetyGuard: false,
|
|
2222
2400
|
statsCommand: false,
|
|
2223
2401
|
gitFooterStatus: false,
|
|
@@ -2290,6 +2468,13 @@ const OPTIONAL_FEATURES = [
|
|
|
2290
2468
|
capabilityLabel: "/workflow or workflow subprocess widget event",
|
|
2291
2469
|
description: "Modular workflow runner with live subprocess output shown in a non-blocking Web UI widget.",
|
|
2292
2470
|
},
|
|
2471
|
+
{
|
|
2472
|
+
id: "featureSystemPrompt",
|
|
2473
|
+
label: "Feature workflow routing",
|
|
2474
|
+
packageName: "@firstpick/pi-extension-feature-system-prompt",
|
|
2475
|
+
capabilityLabel: "feature-category or feature-decision-output status event",
|
|
2476
|
+
description: "Classify feature requests and show lightweight or complex routing decisions in the composer.",
|
|
2477
|
+
},
|
|
2293
2478
|
{
|
|
2294
2479
|
id: "safetyGuard",
|
|
2295
2480
|
label: "Safety guard",
|
|
@@ -2769,7 +2954,7 @@ const OPTIONAL_FEATURE_SECTIONS = [
|
|
|
2769
2954
|
id: "workflows-releases",
|
|
2770
2955
|
label: "Workflows & releases",
|
|
2771
2956
|
description: "Guided workflows, task runners, and publishing actions with visible execution state.",
|
|
2772
|
-
featureIds: ["gitWorkflow", "workflows", "releaseNpm", "releaseAur", "aurReview"],
|
|
2957
|
+
featureIds: ["gitWorkflow", "workflows", "featureSystemPrompt", "releaseNpm", "releaseAur", "aurReview"],
|
|
2773
2958
|
},
|
|
2774
2959
|
{
|
|
2775
2960
|
id: "safety-access",
|
|
@@ -2874,6 +3059,7 @@ let optionalFeatureMigrationRenderTimer = null;
|
|
|
2874
3059
|
let optionalFeatureMigrationReadyDismissTimer = null;
|
|
2875
3060
|
let optionalFeatureMigrationPendingReadyDismissKey = "";
|
|
2876
3061
|
let optionalFeatureMigrationDismissedReadyKey = "";
|
|
3062
|
+
let optionalFeatureMigrationDismissedCompletionKey = "";
|
|
2877
3063
|
let optionalFeatureMigrationDialogState = null;
|
|
2878
3064
|
let optionalFeatureMigrationLastPhase = "";
|
|
2879
3065
|
let optionalFeatureMigrationCompletionFocusKey = "";
|
|
@@ -2884,7 +3070,7 @@ const gitFooterPayloadRefreshInFlightByTab = new Set();
|
|
|
2884
3070
|
const gitFooterPayloadStateByTab = new Map();
|
|
2885
3071
|
const gitFooterPayloadSettlementTimersByTab = new Map();
|
|
2886
3072
|
const gitFooterPayloadRequestSerialByTab = new Map();
|
|
2887
|
-
const
|
|
3073
|
+
const gitFooterSyncInFlightByTab = new Set();
|
|
2888
3074
|
const gitFooterPiCalibrationInFlightByTab = new Set();
|
|
2889
3075
|
let gitFooterVisibilityApplyInFlight = false;
|
|
2890
3076
|
let gitFooterVisibilityDirty = false;
|
|
@@ -3664,6 +3850,9 @@ function setSidePanelSectionVisible(record, visible, { persist = true } = {}) {
|
|
|
3664
3850
|
ensureGitPanelRepositoriesDiscovered({ retryUnavailable: true });
|
|
3665
3851
|
});
|
|
3666
3852
|
}
|
|
3853
|
+
if (visible && record.id === "sampling" && !record.section.classList.contains("collapsed")) {
|
|
3854
|
+
queueMicrotask(() => ensureSamplingParametersLoaded());
|
|
3855
|
+
}
|
|
3667
3856
|
if (persist) persistSidePanelSectionVisibility();
|
|
3668
3857
|
}
|
|
3669
3858
|
|
|
@@ -3687,6 +3876,9 @@ function setSidePanelSectionCollapsed(record, collapsed, { persist = true } = {}
|
|
|
3687
3876
|
ensureGitPanelRepositoriesDiscovered({ retryUnavailable: true });
|
|
3688
3877
|
});
|
|
3689
3878
|
}
|
|
3879
|
+
if (!collapsed && record.id === "sampling" && !record.section.hidden) {
|
|
3880
|
+
queueMicrotask(() => ensureSamplingParametersLoaded());
|
|
3881
|
+
}
|
|
3690
3882
|
if (persist) persistSidePanelSectionState();
|
|
3691
3883
|
}
|
|
3692
3884
|
|
|
@@ -5061,7 +5253,7 @@ function bindTerminalTabDragAndDrop(element, { sourceTabId = "", target = null }
|
|
|
5061
5253
|
element.draggable = true;
|
|
5062
5254
|
element.dataset.dragTabId = sourceTabId;
|
|
5063
5255
|
element.addEventListener("dragstart", (event) => {
|
|
5064
|
-
if (event.target?.closest?.(".terminal-tab-close, .terminal-tab-group-add")) {
|
|
5256
|
+
if (event.target?.closest?.(".terminal-tab-close, .terminal-tab-actions, .terminal-tab-group-add")) {
|
|
5065
5257
|
event.preventDefault();
|
|
5066
5258
|
return;
|
|
5067
5259
|
}
|
|
@@ -5541,8 +5733,9 @@ function clearFeatureDecisionStateForTab(tabId, { render = false } = {}) {
|
|
|
5541
5733
|
function renderFeatureCategoryTag(tabId = activeTabId) {
|
|
5542
5734
|
const tag = elements.featureCategoryTag;
|
|
5543
5735
|
if (!tag) return;
|
|
5544
|
-
const
|
|
5545
|
-
const
|
|
5736
|
+
const enabled = isOptionalFeatureEnabled("featureSystemPrompt");
|
|
5737
|
+
const category = enabled ? normalizeFeatureCategory(featureCategoryByTab.get(tabId)) : "";
|
|
5738
|
+
const output = enabled ? featureDecisionOutputForTab(tabId) : "";
|
|
5546
5739
|
tag.hidden = !category;
|
|
5547
5740
|
tag.disabled = !output;
|
|
5548
5741
|
tag.textContent = category;
|
|
@@ -5554,18 +5747,22 @@ function renderFeatureCategoryTag(tabId = activeTabId) {
|
|
|
5554
5747
|
|
|
5555
5748
|
function handleFeatureDecisionOutputStatus(statusText, tabId = activeTabId) {
|
|
5556
5749
|
if (!tabId) return;
|
|
5750
|
+
optionalFeatureAvailability.featureSystemPrompt = true;
|
|
5557
5751
|
const decision = parseFeatureDecisionPayload(statusText);
|
|
5558
5752
|
if (decision) featureDecisionOutputByTab.set(tabId, decision);
|
|
5559
5753
|
else featureDecisionOutputByTab.delete(tabId);
|
|
5754
|
+
renderOptionalFeatureControls();
|
|
5560
5755
|
if (tabId === activeTabId) renderFeatureCategoryTag(tabId);
|
|
5561
5756
|
else if (featureDecisionDialogTabId === tabId) syncFeatureDecisionDialog();
|
|
5562
5757
|
}
|
|
5563
5758
|
|
|
5564
5759
|
function handleFeatureCategoryStatus(statusText, tabId = activeTabId) {
|
|
5565
5760
|
if (!tabId) return;
|
|
5761
|
+
optionalFeatureAvailability.featureSystemPrompt = true;
|
|
5566
5762
|
const category = normalizeFeatureCategory(statusText);
|
|
5567
5763
|
if (category) featureCategoryByTab.set(tabId, category);
|
|
5568
5764
|
else clearFeatureDecisionStateForTab(tabId);
|
|
5765
|
+
renderOptionalFeatureControls();
|
|
5569
5766
|
if (tabId === activeTabId) renderFeatureCategoryTag(tabId);
|
|
5570
5767
|
else if (featureDecisionDialogTabId === tabId) syncFeatureDecisionDialog();
|
|
5571
5768
|
}
|
|
@@ -5602,29 +5799,31 @@ function trackSkillsFromText(tabId, text, { kind = "used", source = "" } = {}) {
|
|
|
5602
5799
|
}
|
|
5603
5800
|
|
|
5604
5801
|
function trackSkillsFromValue(tabId, value, { keyHint = "", kind = "used", source = "", depth = 0 } = {}) {
|
|
5605
|
-
if (!tabId || value === undefined || value === null || depth > 5) return;
|
|
5802
|
+
if (!tabId || value === undefined || value === null || depth > 5) return 0;
|
|
5606
5803
|
if (Array.isArray(value)) {
|
|
5607
|
-
|
|
5608
|
-
return;
|
|
5804
|
+
return value.reduce((count, item) => count + trackSkillsFromValue(tabId, item, { keyHint, kind, source, depth: depth + 1 }), 0);
|
|
5609
5805
|
}
|
|
5610
5806
|
if (typeof value === "string") {
|
|
5611
5807
|
const skillInfo = skillInfoFromPath(value);
|
|
5612
|
-
if (skillInfo)
|
|
5613
|
-
|
|
5808
|
+
if (!skillInfo) return 0;
|
|
5809
|
+
trackSkillUsage(tabId, skillInfo.name, "read", source, { path: skillInfo.path });
|
|
5810
|
+
return 1;
|
|
5614
5811
|
}
|
|
5615
|
-
if (typeof value !== "object") return;
|
|
5812
|
+
if (typeof value !== "object") return 0;
|
|
5813
|
+
let tracked = 0;
|
|
5616
5814
|
for (const [key, nested] of Object.entries(value)) {
|
|
5617
5815
|
const hint = String(key || "").toLowerCase();
|
|
5618
|
-
trackSkillsFromValue(tabId, nested, { keyHint: hint, kind, source, depth: depth + 1 });
|
|
5816
|
+
tracked += trackSkillsFromValue(tabId, nested, { keyHint: hint, kind, source, depth: depth + 1 });
|
|
5619
5817
|
}
|
|
5818
|
+
return tracked;
|
|
5620
5819
|
}
|
|
5621
5820
|
|
|
5622
5821
|
function trackSkillsFromToolInvocation(tabId, toolName, args, { sourcePrefix = "tool" } = {}) {
|
|
5623
|
-
if (!tabId) return;
|
|
5822
|
+
if (!tabId) return false;
|
|
5624
5823
|
const name = String(toolName || "").trim();
|
|
5625
|
-
if (name.toLowerCase() !== "read") return;
|
|
5824
|
+
if (name.toLowerCase() !== "read") return false;
|
|
5626
5825
|
const source = `${sourcePrefix}:${name}`;
|
|
5627
|
-
trackSkillsFromValue(tabId, args, { kind: "read", source });
|
|
5826
|
+
return trackSkillsFromValue(tabId, args, { kind: "read", source }) > 0;
|
|
5628
5827
|
}
|
|
5629
5828
|
|
|
5630
5829
|
function trackSkillsFromMessage(tabId, message) {
|
|
@@ -5651,26 +5850,67 @@ function assistantMessageUpdateType(event) {
|
|
|
5651
5850
|
return event?.assistantMessageEvent?.type || "";
|
|
5652
5851
|
}
|
|
5653
5852
|
|
|
5853
|
+
// Skill usage is recorded only at semantic tool boundaries. Argument/output
|
|
5854
|
+
// delta cadence (`toolcall_*`, `tool_execution_update`) must never enter skill
|
|
5855
|
+
// tracking: those raw fragments are transcript-owned stream content.
|
|
5654
5856
|
function eventMayAffectSkillUsage(event) {
|
|
5655
5857
|
const type = event?.type || "";
|
|
5656
|
-
return ["tool_execution_start", "
|
|
5657
|
-
|| (type === "message_update" && assistantMessageUpdateType(event) === "toolcall_start")
|
|
5858
|
+
return ["tool_execution_start", "tool_execution_end"].includes(type)
|
|
5658
5859
|
|| (type === "response" && event.command === "new_session");
|
|
5659
5860
|
}
|
|
5660
5861
|
|
|
5862
|
+
function beginToolBoundaryRun(event) {
|
|
5863
|
+
const tabId = event?.tabId || activeTabId || "";
|
|
5864
|
+
if (!tabId || event?.replayed === true) return;
|
|
5865
|
+
toolBoundaryRunEpochByTab.set(tabId, (toolBoundaryRunEpochByTab.get(tabId) || 0) + 1);
|
|
5866
|
+
}
|
|
5867
|
+
|
|
5868
|
+
function toolBoundaryRunIdentity(event, tabId) {
|
|
5869
|
+
const explicit = String(event?.agentRunId || event?.turnId || "").trim();
|
|
5870
|
+
return explicit || `epoch-${toolBoundaryRunEpochByTab.get(tabId) || 0}`;
|
|
5871
|
+
}
|
|
5872
|
+
|
|
5873
|
+
function toolBoundaryRecordKey(event, phase) {
|
|
5874
|
+
const tabId = event?.tabId || activeTabId || "";
|
|
5875
|
+
const toolCallId = String(event?.toolCallId || event?.id || "").trim();
|
|
5876
|
+
if (!toolCallId) return "";
|
|
5877
|
+
return `${tabId}:${toolBoundaryRunIdentity(event, tabId)}:${toolCallId}:${phase}`;
|
|
5878
|
+
}
|
|
5879
|
+
|
|
5880
|
+
function rememberToolBoundaryRecordKey(key) {
|
|
5881
|
+
if (!key || recordedToolBoundaryKeys.has(key)) return false;
|
|
5882
|
+
recordedToolBoundaryKeys.add(key);
|
|
5883
|
+
while (recordedToolBoundaryKeys.size > TOOL_BOUNDARY_RECORD_LIMIT) {
|
|
5884
|
+
const oldest = recordedToolBoundaryKeys.values().next().value;
|
|
5885
|
+
if (oldest === undefined) break;
|
|
5886
|
+
recordedToolBoundaryKeys.delete(oldest);
|
|
5887
|
+
}
|
|
5888
|
+
return true;
|
|
5889
|
+
}
|
|
5890
|
+
|
|
5891
|
+
// One record per tool boundary within an agent run. Redelivered or replayed
|
|
5892
|
+
// boundaries must not duplicate skill tags or event-log lines.
|
|
5893
|
+
function claimToolBoundaryRecord(event, phase) {
|
|
5894
|
+
const key = toolBoundaryRecordKey(event, phase);
|
|
5895
|
+
return key ? rememberToolBoundaryRecordKey(key) : true;
|
|
5896
|
+
}
|
|
5897
|
+
|
|
5661
5898
|
function trackSkillsFromEvent(event) {
|
|
5662
5899
|
const tabId = event?.tabId || activeTabId;
|
|
5663
5900
|
if (!tabId || !event) return;
|
|
5664
|
-
if (["tool_execution_start", "
|
|
5665
|
-
|
|
5666
|
-
|
|
5667
|
-
|
|
5668
|
-
|
|
5669
|
-
const
|
|
5670
|
-
trackSkillsFromToolInvocation(tabId,
|
|
5901
|
+
if (["tool_execution_start", "tool_execution_end"].includes(event.type)) {
|
|
5902
|
+
// Start is preferred, but unusable start args do not consume the claim;
|
|
5903
|
+
// completion may still provide the authoritative invocation arguments.
|
|
5904
|
+
const key = toolBoundaryRecordKey(event, "skills");
|
|
5905
|
+
if (key && recordedToolBoundaryKeys.has(key)) return;
|
|
5906
|
+
const args = event.args ?? event.arguments ?? event.invocation?.args;
|
|
5907
|
+
const tracked = trackSkillsFromToolInvocation(tabId, event.toolName, args, { sourcePrefix: `event:${event.type}` });
|
|
5908
|
+
if (tracked && key) rememberToolBoundaryRecordKey(key);
|
|
5671
5909
|
return;
|
|
5672
5910
|
}
|
|
5673
5911
|
if (event.type === "response" && event.command === "new_session") {
|
|
5912
|
+
recordedToolBoundaryKeys.clear();
|
|
5913
|
+
toolBoundaryRunEpochByTab.delete(tabId);
|
|
5674
5914
|
clearSkillUsageForTab(tabId);
|
|
5675
5915
|
}
|
|
5676
5916
|
}
|
|
@@ -7082,24 +7322,25 @@ async function confirmOpenWebuiNpmPage() {
|
|
|
7082
7322
|
async function openPiReleaseNotes() {
|
|
7083
7323
|
const dialog = elements.piReleaseNotesDialog;
|
|
7084
7324
|
if (!dialog) return;
|
|
7085
|
-
const
|
|
7086
|
-
const
|
|
7325
|
+
const installedVersion = piVersion;
|
|
7326
|
+
const availableVersion = latestUpdateStatus?.pi?.updateAvailable ? latestUpdateStatus.pi.latestVersion : "";
|
|
7327
|
+
const displayedVersion = availableVersion || installedVersion;
|
|
7328
|
+
const label = formatWebuiVersion(displayedVersion);
|
|
7087
7329
|
elements.piReleaseNotesTitle.textContent = label ? `Pi ${label} release notes` : "Pi release notes";
|
|
7088
7330
|
elements.piReleaseNotesStatus.textContent = "Loading release notes from GitHub…";
|
|
7089
7331
|
elements.piReleaseNotesBody.setAttribute("aria-busy", "true");
|
|
7090
7332
|
elements.piReleaseNotesBody.replaceChildren(make("p", "muted", "Loading…"));
|
|
7091
|
-
setPiReleaseNotesLink(piReleasePageUrl(
|
|
7333
|
+
setPiReleaseNotesLink(piReleasePageUrl(displayedVersion));
|
|
7092
7334
|
renderComponentUpdateDialogs();
|
|
7093
7335
|
if (!dialog.open) dialog.showModal();
|
|
7094
7336
|
refreshUpdateStatus({ notify: false }).catch((error) => addEvent(`Pi/Web UI update check failed: ${error.message || String(error)}`, "warn"));
|
|
7095
7337
|
|
|
7096
7338
|
try {
|
|
7097
7339
|
const response = await api("/api/pi-release-notes", { scoped: false });
|
|
7098
|
-
if (
|
|
7340
|
+
if (installedVersion !== piVersion) return;
|
|
7099
7341
|
const release = response.data || {};
|
|
7100
7342
|
const releaseVersion = String(release.version || "").trim().replace(/^v/i, "");
|
|
7101
|
-
|
|
7102
|
-
const releaseLabel = formatWebuiVersion(releaseVersion || requestedVersion);
|
|
7343
|
+
const releaseLabel = formatWebuiVersion(releaseVersion || displayedVersion);
|
|
7103
7344
|
elements.piReleaseNotesTitle.textContent = releaseLabel ? `Pi ${releaseLabel} release notes` : (release.title || "Pi release notes");
|
|
7104
7345
|
renderMarkdown(elements.piReleaseNotesBody, release.body || "No release notes were provided for this release.");
|
|
7105
7346
|
const published = formatPiReleaseDate(release.publishedAt);
|
|
@@ -7115,6 +7356,7 @@ async function openPiReleaseNotes() {
|
|
|
7115
7356
|
|
|
7116
7357
|
async function refreshWebuiVersion() {
|
|
7117
7358
|
const health = await api("/api/health", { scoped: false });
|
|
7359
|
+
if (health.bootIdentity) serverBootIdentity = health.bootIdentity;
|
|
7118
7360
|
setWebuiVersion(health.webuiVersion);
|
|
7119
7361
|
setPiVersion(health.piVersion);
|
|
7120
7362
|
setWebuiDevServer(isWebuiDevMetadata(health));
|
|
@@ -7189,15 +7431,15 @@ function renderUpdateNotification(status = latestUpdateStatus, { force = false }
|
|
|
7189
7431
|
if (elements.updateNotificationMessage) {
|
|
7190
7432
|
let message = "Updates are available. Direct Web UI updates are only enabled from localhost on the host machine.";
|
|
7191
7433
|
if (canRunUpdate) {
|
|
7192
|
-
if (hasPiUpdate && hasPackageUpdate) message = "
|
|
7193
|
-
else if (hasPackageUpdate) message = "
|
|
7194
|
-
else message = "
|
|
7434
|
+
if (hasPiUpdate && hasPackageUpdate) message = "Create and confirm an exact combined update plan for eligible Pi, Web UI, and Pi-owned Optional Features; managed runtimes are staged, verified, activated, and restarted with rollback protection.";
|
|
7435
|
+
else if (hasPackageUpdate) message = "Create and confirm an exact package update plan; managed Web UI runtimes are staged, verified, activated, and restarted with rollback protection.";
|
|
7436
|
+
else message = "Create and confirm an exact Pi update plan; bundled Pi is staged with the Web UI, while an independent Pi executable is delegated to and verified.";
|
|
7195
7437
|
}
|
|
7196
7438
|
elements.updateNotificationMessage.textContent = message;
|
|
7197
7439
|
}
|
|
7198
7440
|
const details = [
|
|
7199
7441
|
items.join(" · "),
|
|
7200
|
-
latestUpdateStatus.webuiDev && latestUpdateStatus.webui?.updateAvailable ? "The current Web UI is a
|
|
7442
|
+
latestUpdateStatus.webuiDev && latestUpdateStatus.webui?.updateAvailable ? "The current Web UI is a source checkout and remains untouched; only separately verified, eligible targets can enter the exact update plan." : "",
|
|
7201
7443
|
latestUpdateStatus.packages?.note || "",
|
|
7202
7444
|
].filter(Boolean).join(" ");
|
|
7203
7445
|
if (elements.updateNotificationDetail) elements.updateNotificationDetail.textContent = details;
|
|
@@ -7221,6 +7463,7 @@ async function refreshUpdateStatus({ force = false, notify = true } = {}) {
|
|
|
7221
7463
|
const path = force ? "/api/update-status?refresh=1" : "/api/update-status";
|
|
7222
7464
|
const response = await api(path, { scoped: false });
|
|
7223
7465
|
latestUpdateStatus = response.data || null;
|
|
7466
|
+
if (latestUpdateStatus?.pi?.currentVersion) setPiVersion(latestUpdateStatus.pi.currentVersion);
|
|
7224
7467
|
if (notify) renderUpdateNotification(latestUpdateStatus);
|
|
7225
7468
|
renderComponentUpdateIndicators();
|
|
7226
7469
|
renderComponentUpdateDialogs();
|
|
@@ -7286,7 +7529,7 @@ function componentUpdateStatusText(target) {
|
|
|
7286
7529
|
if (job?.state === "succeeded") {
|
|
7287
7530
|
const activation = target === "pi"
|
|
7288
7531
|
? "New or reloaded Pi sessions use the update; already-running tabs keep their current runtime until restarted."
|
|
7289
|
-
: "
|
|
7532
|
+
: "The managed Web UI runtime was activated automatically; the browser reconnects after the verified restart.";
|
|
7290
7533
|
return { text: `${job.message || `${label} update completed.`} ${activation}`, level: "success" };
|
|
7291
7534
|
}
|
|
7292
7535
|
if (job?.state === "failed") {
|
|
@@ -7359,13 +7602,20 @@ function syncComponentUpdatePolling() {
|
|
|
7359
7602
|
}
|
|
7360
7603
|
}
|
|
7361
7604
|
|
|
7605
|
+
function separatePathPiPlanNotice(plan) {
|
|
7606
|
+
const identities = Array.isArray(plan?.identities) ? plan.identities : [];
|
|
7607
|
+
const activePi = identities.find((identity) => identity?.kind === "pi" && identity.source !== "path");
|
|
7608
|
+
const pathPi = identities.find((identity) => identity?.kind === "pi" && identity.source === "path" && identity.canonicalId !== activePi?.canonicalId);
|
|
7609
|
+
return pathPi ? `PATH Pi${pathPi.version ? ` v${pathPi.version}` : ""} is a separate installation and will remain untouched. Run pi update in a terminal to update it.` : "";
|
|
7610
|
+
}
|
|
7611
|
+
|
|
7362
7612
|
function componentUpdateConfirmationText(target) {
|
|
7363
7613
|
const pkg = latestUpdateStatus?.[target] || {};
|
|
7364
7614
|
const versionText = pkg.updateAvailable ? `\n\nDetected update: ${packageUpdateText(componentUpdateLabel(target), pkg)}.` : "";
|
|
7365
7615
|
if (target === "pi") {
|
|
7366
|
-
return `
|
|
7616
|
+
return `Create and apply an exact Pi update plan now?${versionText}\n\nBundled Pi updates are staged with the current Web UI in a side-by-side managed runtime and activated with a health-gated restart. A verified independent Pi executable delegates to that exact executable and is rejected if it cannot reach the confirmed version.`;
|
|
7367
7617
|
}
|
|
7368
|
-
return `
|
|
7618
|
+
return `Create and apply an exact Web UI update plan now?${versionText}\n\nThe confirmed Web UI and Pi versions are staged outside the live installation, probed, and activated through the stable launcher. Activation restarts the Web UI automatically and rolls back the runtime pointer if health verification fails.`;
|
|
7369
7619
|
}
|
|
7370
7620
|
|
|
7371
7621
|
async function startComponentUpdate(target) {
|
|
@@ -7378,17 +7628,28 @@ async function startComponentUpdate(target) {
|
|
|
7378
7628
|
renderComponentUpdateDialogs();
|
|
7379
7629
|
return;
|
|
7380
7630
|
}
|
|
7381
|
-
|
|
7382
|
-
|
|
7383
|
-
|
|
7631
|
+
let plan;
|
|
7632
|
+
try {
|
|
7633
|
+
plan = (await api("/api/update/plan", { method: "POST", body: { targets: [target] }, scoped: false }))?.data?.plan;
|
|
7634
|
+
} catch (error) {
|
|
7635
|
+
addEvent(error.message || String(error), "error");
|
|
7636
|
+
return;
|
|
7637
|
+
}
|
|
7638
|
+
const planNotice = separatePathPiPlanNotice(plan);
|
|
7639
|
+
const confirmed = await appConfirmText(`${componentUpdateConfirmationText(target)}${planNotice ? `\n\n${planNotice}` : ""}\n\nExact plan digest: ${plan.digest}`, {
|
|
7640
|
+
affected: target === "pi" ? "The verified active Pi installation on the Web UI host" : "A side-by-side managed Web UI runtime",
|
|
7641
|
+
confirmLabel: job?.state === "failed" ? `Retry ${label} update` : `Apply exact ${label} plan`,
|
|
7384
7642
|
danger: false,
|
|
7385
7643
|
});
|
|
7386
7644
|
if (!confirmed) return;
|
|
7387
7645
|
componentUpdateStartInProgress = true;
|
|
7388
7646
|
renderComponentUpdateDialogs();
|
|
7389
7647
|
try {
|
|
7390
|
-
const response = await api("/api/
|
|
7391
|
-
const
|
|
7648
|
+
const response = await api("/api/update/apply", { method: "POST", body: { transactionId: plan.transactionId, planDigest: plan.digest }, scoped: false });
|
|
7649
|
+
const acceptedState = ["applying", "verifying", "activating"].includes(response?.data?.state)
|
|
7650
|
+
? "running"
|
|
7651
|
+
: response?.data?.outcome === "success" ? "succeeded" : "failed";
|
|
7652
|
+
const accepted = { target, state: acceptedState, canStart: false, message: `Exact ${label} update ${response?.data?.state || response?.data?.outcome || "accepted"}.`, receipts: response?.data?.receipts || [] };
|
|
7392
7653
|
if (accepted && typeof accepted === "object") {
|
|
7393
7654
|
latestUpdateStatus = {
|
|
7394
7655
|
...(latestUpdateStatus || {}),
|
|
@@ -7427,14 +7688,16 @@ function initializeUpdateNotifications() {
|
|
|
7427
7688
|
}, UPDATE_STATUS_INITIAL_DELAY_MS);
|
|
7428
7689
|
}
|
|
7429
7690
|
|
|
7430
|
-
function piUpdateConfirmationText({ all = false } = {}) {
|
|
7691
|
+
function piUpdateConfirmationText({ all = false, plan = null } = {}) {
|
|
7431
7692
|
const items = updateNotificationItems();
|
|
7432
7693
|
const workingWarning = hasWorkingTab() ? "\n\nOne or more Pi tabs look busy or blocked. Finish or abort in-flight work before updating if you need to preserve it." : "";
|
|
7433
7694
|
const versionText = items.length ? `\n\nDetected update: ${items.join(" · ")}.` : "";
|
|
7434
|
-
const
|
|
7435
|
-
const
|
|
7436
|
-
const
|
|
7437
|
-
|
|
7695
|
+
const scope = all ? "the verified active Pi and Web UI targets" : "the verified active Pi target";
|
|
7696
|
+
const refusals = Array.isArray(plan?.refusals) && plan.refusals.length ? `\n\nRefused automatic targets: ${plan.refusals.map((item) => `${item.id}: ${item.guidance}`).join(" · ")}` : "";
|
|
7697
|
+
const separatePathPi = separatePathPiPlanNotice(plan);
|
|
7698
|
+
const pathNotice = separatePathPi ? `\n\n${separatePathPi}` : "";
|
|
7699
|
+
const digest = plan?.digest ? `\n\nExact immutable plan digest: ${plan.digest}` : "";
|
|
7700
|
+
return `Apply ${scope} now?${versionText}${refusals}${pathNotice}${digest}\n\nThe server will use only this persisted exact-target plan; it will not re-resolve latest or scan package roots. Managed Web UI activation is health-gated and automatically rolls back on failure.${workingWarning}`;
|
|
7438
7701
|
}
|
|
7439
7702
|
|
|
7440
7703
|
async function runPiUpdateAndRestart({ all = false } = {}) {
|
|
@@ -7444,16 +7707,23 @@ async function runPiUpdateAndRestart({ all = false } = {}) {
|
|
|
7444
7707
|
renderUpdateNotification(latestUpdateStatus, { force: true });
|
|
7445
7708
|
return;
|
|
7446
7709
|
}
|
|
7447
|
-
|
|
7710
|
+
let plan;
|
|
7711
|
+
try {
|
|
7712
|
+
plan = (await api("/api/update/plan", { method: "POST", body: { targets: all ? ["pi", "webui"] : ["pi"] }, scoped: false }))?.data?.plan;
|
|
7713
|
+
} catch (error) {
|
|
7714
|
+
addEvent(error.message || String(error), "error");
|
|
7715
|
+
return;
|
|
7716
|
+
}
|
|
7717
|
+
if (!(await appConfirmText(piUpdateConfirmationText({ all, plan }), { affected: "Only targets accepted by the exact server-owned plan", confirmLabel: all ? "Apply exact update plan" : "Apply exact Pi plan" }))) return;
|
|
7448
7718
|
|
|
7449
|
-
const updateLabel = all ? "Pi and
|
|
7719
|
+
const updateLabel = all ? "Pi and Web UI exact updates" : "Pi exact update";
|
|
7450
7720
|
updateRequestInProgress = true;
|
|
7451
7721
|
hideUpdateNotification();
|
|
7452
7722
|
setServerActionBusy("Updating…");
|
|
7453
7723
|
setServerActionStatus(`Running ${updateLabel}. The server will restart after the update completes…`, "warn");
|
|
7454
7724
|
setServerRestartOverlay(true, `Running ${updateLabel}. The server will restart after the update completes…`);
|
|
7455
7725
|
try {
|
|
7456
|
-
await api(
|
|
7726
|
+
await api("/api/update/apply", { method: "POST", body: { transactionId: plan.transactionId, planDigest: plan.digest }, scoped: false });
|
|
7457
7727
|
addEvent(`${updateLabel} completed; Pi Web UI server restart requested`, "warn");
|
|
7458
7728
|
} catch (error) {
|
|
7459
7729
|
if (!error?.backendOffline) {
|
|
@@ -7470,7 +7740,7 @@ async function runPiUpdateAndRestart({ all = false } = {}) {
|
|
|
7470
7740
|
}
|
|
7471
7741
|
|
|
7472
7742
|
setBackendOffline(true, new Error("update requested from side panel"));
|
|
7473
|
-
const restarted = await waitForServerRestart();
|
|
7743
|
+
const restarted = await waitForServerRestart(serverBootIdentity);
|
|
7474
7744
|
updateRequestInProgress = false;
|
|
7475
7745
|
resetServerActionControls();
|
|
7476
7746
|
if (restarted) {
|
|
@@ -8663,7 +8933,7 @@ function conversationModeCommandName() {
|
|
|
8663
8933
|
}
|
|
8664
8934
|
|
|
8665
8935
|
function conversationModeButtonLabel(mode = activeConversationMode()) {
|
|
8666
|
-
return mode.enabled ? "End Conversation" : "Start Conversation";
|
|
8936
|
+
return mode.enabled ? "End Conversation" : "Start Natural Conversation";
|
|
8667
8937
|
}
|
|
8668
8938
|
|
|
8669
8939
|
function conversationModePartialPreview(text = "") {
|
|
@@ -9270,7 +9540,6 @@ function renderOptionalFeatureDependentDisplays() {
|
|
|
9270
9540
|
renderWidgets();
|
|
9271
9541
|
renderStatus();
|
|
9272
9542
|
renderCommands();
|
|
9273
|
-
cancelStreamingAssistantTextRender();
|
|
9274
9543
|
cancelStreamBubbleHide();
|
|
9275
9544
|
streamBubble?.remove();
|
|
9276
9545
|
streamBubble = null;
|
|
@@ -9290,6 +9559,12 @@ function setOptionalFeatureDisabled(featureId, disabled) {
|
|
|
9290
9559
|
clearGitFooterWebuiPayloadCache();
|
|
9291
9560
|
for (const tabId of new Set([...gitFooterPayloadStateByTab.keys(), ...gitFooterPayloadSettlementTimersByTab.keys(), ...gitFooterPayloadRefreshInFlightByTab])) clearGitFooterPayloadState(tabId);
|
|
9292
9561
|
}
|
|
9562
|
+
if (featureId === "featureSystemPrompt") {
|
|
9563
|
+
if (disabled) {
|
|
9564
|
+
for (const tabId of new Set([...featureCategoryByTab.keys(), ...featureDecisionOutputByTab.keys()])) clearFeatureDecisionStateForTab(tabId);
|
|
9565
|
+
}
|
|
9566
|
+
renderFeatureCategoryTag();
|
|
9567
|
+
}
|
|
9293
9568
|
if (featureId === "btwCommand") {
|
|
9294
9569
|
statusEntries.delete(BTW_WEBUI_STATUS_KEY);
|
|
9295
9570
|
widgets.delete(BTW_OUTPUT_WIDGET_KEY);
|
|
@@ -9335,7 +9610,14 @@ function displayThemeName(name) {
|
|
|
9335
9610
|
}
|
|
9336
9611
|
|
|
9337
9612
|
function resolveThemeValue(theme, value, fallback, seen = new Set()) {
|
|
9338
|
-
|
|
9613
|
+
if (Number.isInteger(value)) {
|
|
9614
|
+
try {
|
|
9615
|
+
return themeColorToRgb(value, theme?.vars || {}, fallback);
|
|
9616
|
+
} catch {
|
|
9617
|
+
return fallback;
|
|
9618
|
+
}
|
|
9619
|
+
}
|
|
9620
|
+
const raw = String(value ?? "").trim();
|
|
9339
9621
|
if (!raw) return fallback;
|
|
9340
9622
|
if (/^(#|rgb\(|rgba\(|hsl\(|hsla\()/i.test(raw)) return raw;
|
|
9341
9623
|
if (seen.has(raw)) return fallback;
|
|
@@ -9646,7 +9928,10 @@ function renderThemeSearchResults(themes = []) {
|
|
|
9646
9928
|
button.title = themeSearchText(theme);
|
|
9647
9929
|
const title = make("span", "theme-search-result-title");
|
|
9648
9930
|
title.append(make("span", "model-search-result-main", themeDisplayLabel(theme)));
|
|
9649
|
-
|
|
9931
|
+
const badges = make("span", "theme-search-result-badges");
|
|
9932
|
+
badges.append(make("span", `theme-search-result-scheme ${themeIsLight(theme) ? "light" : "dark"}`, themeIsLight(theme) ? "Light" : "Dark"));
|
|
9933
|
+
if (theme.custom) badges.append(make("span", `theme-scope-badge ${theme.scope}`, themeScopeLabel(theme.scope)));
|
|
9934
|
+
title.append(badges);
|
|
9650
9935
|
button.append(title);
|
|
9651
9936
|
button.addEventListener("click", () => {
|
|
9652
9937
|
if (elements.themeSelect) elements.themeSelect.value = theme.name;
|
|
@@ -9696,6 +9981,422 @@ function toggleThemeSearchInput() {
|
|
|
9696
9981
|
else hideThemeSearchInput();
|
|
9697
9982
|
}
|
|
9698
9983
|
|
|
9984
|
+
function themeScopeLabel(scope) {
|
|
9985
|
+
if (scope === "project") return "Project";
|
|
9986
|
+
if (scope === "global") return "Global";
|
|
9987
|
+
return "Bundled";
|
|
9988
|
+
}
|
|
9989
|
+
|
|
9990
|
+
function cloneThemeDraft(theme) {
|
|
9991
|
+
return JSON.parse(JSON.stringify(theme));
|
|
9992
|
+
}
|
|
9993
|
+
|
|
9994
|
+
function themeDraftFromCatalog(theme, name = theme?.name) {
|
|
9995
|
+
return {
|
|
9996
|
+
name,
|
|
9997
|
+
...(theme?.vars && Object.keys(theme.vars).length ? { vars: cloneThemeDraft(theme.vars) } : {}),
|
|
9998
|
+
colors: cloneThemeDraft(theme?.colors || {}),
|
|
9999
|
+
...(theme?.export && Object.keys(theme.export).length ? { export: cloneThemeDraft(theme.export) } : {}),
|
|
10000
|
+
};
|
|
10001
|
+
}
|
|
10002
|
+
|
|
10003
|
+
function themeCustomizerValue(raw) {
|
|
10004
|
+
const value = String(raw ?? "").trim();
|
|
10005
|
+
if (/^(?:0|[1-9]\d{0,2})$/.test(value)) return Number(value);
|
|
10006
|
+
return value;
|
|
10007
|
+
}
|
|
10008
|
+
|
|
10009
|
+
function themeCustomizerDraftSignature(state = themeCustomizerState) {
|
|
10010
|
+
if (!state?.validTheme) return "";
|
|
10011
|
+
return JSON.stringify({
|
|
10012
|
+
scope: elements.themeCustomizerScope?.value || "",
|
|
10013
|
+
fileName: `${elements.themeCustomizerName?.value.trim() || ""}.json`,
|
|
10014
|
+
theme: state.validTheme,
|
|
10015
|
+
});
|
|
10016
|
+
}
|
|
10017
|
+
|
|
10018
|
+
function setThemeCustomizerStatus(message, kind = "muted") {
|
|
10019
|
+
if (!elements.themeCustomizerStatus) return;
|
|
10020
|
+
const urgent = kind === "error";
|
|
10021
|
+
elements.themeCustomizerStatus.textContent = message;
|
|
10022
|
+
elements.themeCustomizerStatus.className = `theme-customizer-status ${kind}`;
|
|
10023
|
+
elements.themeCustomizerStatus.setAttribute("role", urgent ? "alert" : "status");
|
|
10024
|
+
elements.themeCustomizerStatus.setAttribute("aria-live", urgent ? "assertive" : "polite");
|
|
10025
|
+
}
|
|
10026
|
+
|
|
10027
|
+
function invalidateThemeCustomizerOverwrite() {
|
|
10028
|
+
if (themeCustomizerState) themeCustomizerState.overwrite = null;
|
|
10029
|
+
if (elements.themeCustomizerOverwrite) elements.themeCustomizerOverwrite.hidden = true;
|
|
10030
|
+
}
|
|
10031
|
+
|
|
10032
|
+
function updateThemeCustomizerActions() {
|
|
10033
|
+
const state = themeCustomizerState;
|
|
10034
|
+
const name = elements.themeCustomizerName?.value.trim() || "";
|
|
10035
|
+
const validName = /^[A-Za-z0-9][A-Za-z0-9._-]{0,74}$/.test(name) && !name.includes("..");
|
|
10036
|
+
const scope = elements.themeCustomizerScope?.value;
|
|
10037
|
+
const projectUnavailable = scope === "project" && !themeCatalogScopes.project?.trusted;
|
|
10038
|
+
if (elements.themeCustomizerSaveButton) {
|
|
10039
|
+
elements.themeCustomizerSaveButton.disabled = !state?.draftValid || !validName || projectUnavailable || !!state?.saving || !!state?.overwrite;
|
|
10040
|
+
elements.themeCustomizerSaveButton.textContent = state?.saving ? "Saving…" : "Save theme";
|
|
10041
|
+
}
|
|
10042
|
+
if (elements.themeCustomizerOverwriteButton) elements.themeCustomizerOverwriteButton.disabled = !!state?.saving;
|
|
10043
|
+
if (elements.themeCustomizerCancelButton) elements.themeCustomizerCancelButton.disabled = !!state?.saving;
|
|
10044
|
+
if (elements.themeCustomizerResetButton) elements.themeCustomizerResetButton.disabled = !!state?.saving;
|
|
10045
|
+
if (!validName) setThemeCustomizerStatus("Use 1–75 letters, numbers, dots, underscores, or hyphens; consecutive dots are not allowed.", "error");
|
|
10046
|
+
else if (projectUnavailable) setThemeCustomizerStatus("This project is not saved as trusted in Pi. Choose Global themes or trust the project in Pi first.", "warn");
|
|
10047
|
+
}
|
|
10048
|
+
|
|
10049
|
+
function themeCustomizerColor(theme, token) {
|
|
10050
|
+
try {
|
|
10051
|
+
return themeColorToRgb(theme.colors[token], theme.vars || {}, "#000000");
|
|
10052
|
+
} catch {
|
|
10053
|
+
return "#000000";
|
|
10054
|
+
}
|
|
10055
|
+
}
|
|
10056
|
+
|
|
10057
|
+
function renderThemeCustomizerVisualFields(theme) {
|
|
10058
|
+
const container = elements.themeCustomizerVisualFields;
|
|
10059
|
+
if (!container || !theme) return;
|
|
10060
|
+
const groups = THEME_TOKEN_GROUPS.map((group) => {
|
|
10061
|
+
const fieldset = make("fieldset", "theme-token-group");
|
|
10062
|
+
fieldset.dataset.themeTokenGroup = group.id;
|
|
10063
|
+
fieldset.append(make("legend", undefined, group.label));
|
|
10064
|
+
const grid = make("div", "theme-token-grid");
|
|
10065
|
+
for (const { name, label } of group.tokens) {
|
|
10066
|
+
const row = make("div", "theme-token-row");
|
|
10067
|
+
row.dataset.themeToken = name;
|
|
10068
|
+
const inputId = `theme-token-${name}`;
|
|
10069
|
+
const copy = document.createElement("label");
|
|
10070
|
+
copy.className = "theme-token-label";
|
|
10071
|
+
copy.htmlFor = inputId;
|
|
10072
|
+
copy.append(document.createTextNode(label), make("code", undefined, name));
|
|
10073
|
+
const swatch = document.createElement("input");
|
|
10074
|
+
swatch.className = "theme-token-swatch";
|
|
10075
|
+
swatch.type = "color";
|
|
10076
|
+
const value = document.createElement("input");
|
|
10077
|
+
value.id = inputId;
|
|
10078
|
+
value.className = "theme-token-value";
|
|
10079
|
+
value.type = "text";
|
|
10080
|
+
value.autocomplete = "off";
|
|
10081
|
+
value.spellcheck = false;
|
|
10082
|
+
value.value = String(theme.colors[name] ?? "");
|
|
10083
|
+
value.setAttribute("aria-label", `${label} value`);
|
|
10084
|
+
const swatchNote = make("span", "theme-token-swatch-note");
|
|
10085
|
+
const syncSwatch = () => {
|
|
10086
|
+
const raw = value.value.trim();
|
|
10087
|
+
const directValue = themeCustomizerValue(raw);
|
|
10088
|
+
const direct = /^#[0-9a-f]{6}$/i.test(raw) || (typeof directValue === "number" && directValue >= 0 && directValue <= 255);
|
|
10089
|
+
swatch.disabled = !direct;
|
|
10090
|
+
swatch.value = direct ? themeColorToRgb(directValue, {}, "#000000") : themeCustomizerColor(theme, name);
|
|
10091
|
+
swatch.setAttribute("aria-label", direct
|
|
10092
|
+
? `Choose ${label} color`
|
|
10093
|
+
: `${label} uses ${raw ? `variable ${raw}` : "the terminal default"}. Edit the raw value to replace it with a color.`);
|
|
10094
|
+
swatchNote.hidden = direct;
|
|
10095
|
+
swatchNote.textContent = raw ? `Variable ${raw}; edit the value to replace it.` : "Terminal default; edit the value to replace it.";
|
|
10096
|
+
};
|
|
10097
|
+
value.addEventListener("input", () => {
|
|
10098
|
+
syncSwatch();
|
|
10099
|
+
updateThemeCustomizerFromVisual();
|
|
10100
|
+
});
|
|
10101
|
+
swatch.addEventListener("input", () => {
|
|
10102
|
+
value.value = swatch.value;
|
|
10103
|
+
syncSwatch();
|
|
10104
|
+
updateThemeCustomizerFromVisual();
|
|
10105
|
+
});
|
|
10106
|
+
syncSwatch();
|
|
10107
|
+
row.append(copy, swatch, value, swatchNote);
|
|
10108
|
+
grid.append(row);
|
|
10109
|
+
}
|
|
10110
|
+
fieldset.append(grid);
|
|
10111
|
+
return fieldset;
|
|
10112
|
+
});
|
|
10113
|
+
container.replaceChildren(...groups);
|
|
10114
|
+
}
|
|
10115
|
+
|
|
10116
|
+
function renderThemeCustomizerOptionalFields(theme) {
|
|
10117
|
+
if (!theme) return;
|
|
10118
|
+
if (elements.themeCustomizerThinkingMax) elements.themeCustomizerThinkingMax.value = String(theme.colors.thinkingMax ?? "");
|
|
10119
|
+
if (elements.themeCustomizerVars) elements.themeCustomizerVars.value = JSON.stringify(theme.vars || {}, null, 2);
|
|
10120
|
+
if (elements.themeCustomizerExportFields) {
|
|
10121
|
+
const fields = PI_THEME_EXPORT_FIELDS.map((name) => {
|
|
10122
|
+
const label = document.createElement("label");
|
|
10123
|
+
label.textContent = name;
|
|
10124
|
+
const input = document.createElement("input");
|
|
10125
|
+
input.type = "text";
|
|
10126
|
+
input.autocomplete = "off";
|
|
10127
|
+
input.spellcheck = false;
|
|
10128
|
+
input.dataset.themeExport = name;
|
|
10129
|
+
input.value = String(theme.export?.[name] ?? "");
|
|
10130
|
+
input.addEventListener("input", updateThemeCustomizerFromVisual);
|
|
10131
|
+
label.append(input);
|
|
10132
|
+
return label;
|
|
10133
|
+
});
|
|
10134
|
+
elements.themeCustomizerExportFields.replaceChildren(...fields);
|
|
10135
|
+
}
|
|
10136
|
+
}
|
|
10137
|
+
|
|
10138
|
+
function themeCustomizerCandidateFromVisual() {
|
|
10139
|
+
const state = themeCustomizerState;
|
|
10140
|
+
if (!state?.validTheme) throw new Error("No valid theme draft is available.");
|
|
10141
|
+
const candidate = cloneThemeDraft(state.validTheme);
|
|
10142
|
+
candidate.name = elements.themeCustomizerName.value.trim();
|
|
10143
|
+
candidate.colors = { ...candidate.colors };
|
|
10144
|
+
for (const input of elements.themeCustomizerVisualFields.querySelectorAll("[data-theme-token] .theme-token-value")) {
|
|
10145
|
+
candidate.colors[input.closest("[data-theme-token]").dataset.themeToken] = themeCustomizerValue(input.value);
|
|
10146
|
+
}
|
|
10147
|
+
const thinkingMax = elements.themeCustomizerThinkingMax.value.trim();
|
|
10148
|
+
if (thinkingMax) candidate.colors.thinkingMax = themeCustomizerValue(thinkingMax);
|
|
10149
|
+
else delete candidate.colors.thinkingMax;
|
|
10150
|
+
let vars;
|
|
10151
|
+
try {
|
|
10152
|
+
vars = JSON.parse(elements.themeCustomizerVars.value || "{}");
|
|
10153
|
+
} catch (error) {
|
|
10154
|
+
throw new Error(`Variables JSON is invalid: ${error.message}`);
|
|
10155
|
+
}
|
|
10156
|
+
if (!vars || typeof vars !== "object" || Array.isArray(vars)) throw new Error("Variables must be a JSON object.");
|
|
10157
|
+
if (Object.keys(vars).length) candidate.vars = vars;
|
|
10158
|
+
else delete candidate.vars;
|
|
10159
|
+
const exportColors = {};
|
|
10160
|
+
for (const input of elements.themeCustomizerExportFields.querySelectorAll("[data-theme-export]")) {
|
|
10161
|
+
if (input.value.trim()) exportColors[input.dataset.themeExport] = themeCustomizerValue(input.value);
|
|
10162
|
+
}
|
|
10163
|
+
if (Object.keys(exportColors).length) candidate.export = exportColors;
|
|
10164
|
+
else delete candidate.export;
|
|
10165
|
+
return candidate;
|
|
10166
|
+
}
|
|
10167
|
+
|
|
10168
|
+
function acceptThemeCustomizerDraft(candidate, { syncJson = true, syncControls = false } = {}) {
|
|
10169
|
+
const state = themeCustomizerState;
|
|
10170
|
+
if (!state) return false;
|
|
10171
|
+
const validation = validateTheme(candidate, { allowWebuiExport: true });
|
|
10172
|
+
if (!validation.ok) {
|
|
10173
|
+
state.draftValid = false;
|
|
10174
|
+
invalidateThemeCustomizerOverwrite();
|
|
10175
|
+
setThemeCustomizerStatus(validation.issues.map(({ path, message }) => `${path}: ${message}`).join(" · "), "error");
|
|
10176
|
+
updateThemeCustomizerActions();
|
|
10177
|
+
return false;
|
|
10178
|
+
}
|
|
10179
|
+
const canonical = canonicalizeTheme(candidate, { allowWebuiExport: true });
|
|
10180
|
+
state.validTheme = canonical;
|
|
10181
|
+
state.draftValid = true;
|
|
10182
|
+
invalidateThemeCustomizerOverwrite();
|
|
10183
|
+
if (syncJson && elements.themeCustomizerJson) elements.themeCustomizerJson.value = serializeTheme(canonical, { allowWebuiExport: true });
|
|
10184
|
+
if (syncControls) {
|
|
10185
|
+
elements.themeCustomizerName.value = canonical.name;
|
|
10186
|
+
renderThemeCustomizerVisualFields(canonical);
|
|
10187
|
+
renderThemeCustomizerOptionalFields(canonical);
|
|
10188
|
+
}
|
|
10189
|
+
applyTheme(canonical, { persist: false });
|
|
10190
|
+
setThemeCustomizerStatus("Valid draft previewed. Nothing has been written to browser storage or disk.", "success");
|
|
10191
|
+
updateThemeCustomizerActions();
|
|
10192
|
+
return true;
|
|
10193
|
+
}
|
|
10194
|
+
|
|
10195
|
+
function updateThemeCustomizerFromVisual() {
|
|
10196
|
+
if (!themeCustomizerState) return;
|
|
10197
|
+
invalidateThemeCustomizerOverwrite();
|
|
10198
|
+
try {
|
|
10199
|
+
acceptThemeCustomizerDraft(themeCustomizerCandidateFromVisual(), { syncJson: true });
|
|
10200
|
+
} catch (error) {
|
|
10201
|
+
themeCustomizerState.draftValid = false;
|
|
10202
|
+
setThemeCustomizerStatus(error.message || String(error), "error");
|
|
10203
|
+
updateThemeCustomizerActions();
|
|
10204
|
+
}
|
|
10205
|
+
}
|
|
10206
|
+
|
|
10207
|
+
function updateThemeCustomizerFromJson() {
|
|
10208
|
+
if (!themeCustomizerState) return;
|
|
10209
|
+
invalidateThemeCustomizerOverwrite();
|
|
10210
|
+
let candidate;
|
|
10211
|
+
try {
|
|
10212
|
+
candidate = JSON.parse(elements.themeCustomizerJson.value);
|
|
10213
|
+
} catch (error) {
|
|
10214
|
+
themeCustomizerState.draftValid = false;
|
|
10215
|
+
setThemeCustomizerStatus(`Advanced JSON is invalid: ${error.message}. The last valid preview remains active.`, "error");
|
|
10216
|
+
updateThemeCustomizerActions();
|
|
10217
|
+
return;
|
|
10218
|
+
}
|
|
10219
|
+
acceptThemeCustomizerDraft(candidate, { syncJson: false, syncControls: true });
|
|
10220
|
+
}
|
|
10221
|
+
|
|
10222
|
+
function restoreThemeCustomizerOpeningState(generation) {
|
|
10223
|
+
const state = themeCustomizerState;
|
|
10224
|
+
if (!state || state.generation !== generation || state.restored) return;
|
|
10225
|
+
state.restored = true;
|
|
10226
|
+
applyTheme(state.opening.theme, { persist: false });
|
|
10227
|
+
setCustomBackgroundRecord(state.opening.background);
|
|
10228
|
+
customBackgroundLoading = false;
|
|
10229
|
+
applyCustomBackgroundOverride();
|
|
10230
|
+
renderThemeSelect();
|
|
10231
|
+
}
|
|
10232
|
+
|
|
10233
|
+
function closeThemeCustomizer({ restore = true } = {}) {
|
|
10234
|
+
const state = themeCustomizerState;
|
|
10235
|
+
if (!state) {
|
|
10236
|
+
if (elements.themeCustomizerDialog?.open) elements.themeCustomizerDialog.close();
|
|
10237
|
+
return;
|
|
10238
|
+
}
|
|
10239
|
+
if (state.saving) {
|
|
10240
|
+
setThemeCustomizerStatus("Wait for the theme save to finish before closing or switching tabs.", "warn");
|
|
10241
|
+
return false;
|
|
10242
|
+
}
|
|
10243
|
+
const generation = state.generation;
|
|
10244
|
+
state.closing = true;
|
|
10245
|
+
if (restore) restoreThemeCustomizerOpeningState(generation);
|
|
10246
|
+
themeCustomizerState = null;
|
|
10247
|
+
if (elements.themeCustomizerDialog?.open) elements.themeCustomizerDialog.close();
|
|
10248
|
+
return true;
|
|
10249
|
+
}
|
|
10250
|
+
|
|
10251
|
+
function themeCustomizerNameForSource(theme) {
|
|
10252
|
+
const raw = theme?.custom ? theme.name : `${theme?.name || "custom-theme"}-custom`;
|
|
10253
|
+
return raw.replace(/[^A-Za-z0-9._-]+/g, "-").replace(/^[^A-Za-z0-9]+/, "").slice(0, 75) || "custom-theme";
|
|
10254
|
+
}
|
|
10255
|
+
|
|
10256
|
+
function installThemeCatalog(data) {
|
|
10257
|
+
availableThemes = Array.isArray(data?.themes) ? data.themes : [];
|
|
10258
|
+
themeCatalogScopes = data?.scopes && typeof data.scopes === "object" ? data.scopes : themeCatalogScopes;
|
|
10259
|
+
optionalFeatureAvailability.themeBundle = availableThemes.length > 0;
|
|
10260
|
+
renderOptionalFeatureControls();
|
|
10261
|
+
renderThemeSelect();
|
|
10262
|
+
}
|
|
10263
|
+
|
|
10264
|
+
async function refreshThemeCatalog(tabContext = activeTabContext()) {
|
|
10265
|
+
const response = await api("/api/themes", { tabId: tabContext.tabId });
|
|
10266
|
+
if (tabContext.tabId && !isCurrentTabContext(tabContext)) return response.data;
|
|
10267
|
+
installThemeCatalog(response.data || {});
|
|
10268
|
+
return response.data || {};
|
|
10269
|
+
}
|
|
10270
|
+
|
|
10271
|
+
async function openThemeCustomizer() {
|
|
10272
|
+
if (!elements.themeCustomizerDialog || !availableThemes.length) return;
|
|
10273
|
+
const generation = ++themeCustomizerGeneration;
|
|
10274
|
+
const tabContext = activeTabContext();
|
|
10275
|
+
const openingTheme = availableThemes.find((theme) => theme.name === currentThemeName) || availableThemes[0];
|
|
10276
|
+
const opening = {
|
|
10277
|
+
theme: cloneThemeDraft(openingTheme),
|
|
10278
|
+
background: customBackground ? cloneThemeDraft(customBackground) : null,
|
|
10279
|
+
};
|
|
10280
|
+
themeCustomizerState = { generation, tabContext, opening, validTheme: null, draftValid: false, initialTheme: null, overwrite: null, saving: false, restored: false };
|
|
10281
|
+
setThemeCustomizerStatus("Loading project and global theme destinations…");
|
|
10282
|
+
try {
|
|
10283
|
+
await refreshThemeCatalog(tabContext);
|
|
10284
|
+
} catch (error) {
|
|
10285
|
+
if (themeCustomizerState?.generation === generation) setThemeCustomizerStatus(`Theme catalog refresh failed: ${error.message || String(error)}`, "warn");
|
|
10286
|
+
}
|
|
10287
|
+
if (themeCustomizerState?.generation !== generation) return;
|
|
10288
|
+
const source = availableThemes.find((theme) => theme.name === openingTheme.name) || openingTheme;
|
|
10289
|
+
const draft = canonicalizeTheme(themeDraftFromCatalog(source, themeCustomizerNameForSource(source)), { allowWebuiExport: true });
|
|
10290
|
+
themeCustomizerState.source = source;
|
|
10291
|
+
themeCustomizerState.initialTheme = cloneThemeDraft(draft);
|
|
10292
|
+
const projectTrusted = themeCatalogScopes.project?.trusted === true;
|
|
10293
|
+
elements.themeCustomizerProjectOption.disabled = !projectTrusted;
|
|
10294
|
+
elements.themeCustomizerScope.value = source.custom ? source.scope : projectTrusted ? "project" : "global";
|
|
10295
|
+
elements.themeCustomizerScopeHint.textContent = projectTrusted
|
|
10296
|
+
? "Project saves use this active trusted tab’s .pi/themes directory; global saves use Pi’s agent themes directory."
|
|
10297
|
+
: "This active project is not saved as trusted in Pi, so only Global themes is available.";
|
|
10298
|
+
elements.themeCustomizerSourceBadge.textContent = `${themeScopeLabel(source.scope)} source`;
|
|
10299
|
+
elements.themeCustomizerSourceBadge.className = `theme-scope-badge ${source.scope || "bundled"}`;
|
|
10300
|
+
elements.themeCustomizerName.value = draft.name;
|
|
10301
|
+
renderThemeCustomizerVisualFields(draft);
|
|
10302
|
+
renderThemeCustomizerOptionalFields(draft);
|
|
10303
|
+
elements.themeCustomizerJson.value = serializeTheme(draft, { allowWebuiExport: true });
|
|
10304
|
+
themeCustomizerState.validTheme = draft;
|
|
10305
|
+
themeCustomizerState.draftValid = true;
|
|
10306
|
+
invalidateThemeCustomizerOverwrite();
|
|
10307
|
+
applyTheme(draft, { persist: false });
|
|
10308
|
+
setThemeCustomizerStatus("Valid draft previewed. Nothing has been written to browser storage or disk.", "success");
|
|
10309
|
+
updateThemeCustomizerActions();
|
|
10310
|
+
if (!elements.themeCustomizerDialog.open) elements.themeCustomizerDialog.showModal();
|
|
10311
|
+
queueMicrotask(() => elements.themeCustomizerName?.focus({ preventScroll: true }));
|
|
10312
|
+
}
|
|
10313
|
+
|
|
10314
|
+
function showThemeCustomizerOverwrite(details) {
|
|
10315
|
+
const state = themeCustomizerState;
|
|
10316
|
+
if (!state) return;
|
|
10317
|
+
const scope = details?.scope;
|
|
10318
|
+
const fileName = details?.fileName;
|
|
10319
|
+
if (scope !== elements.themeCustomizerScope.value || fileName !== `${elements.themeCustomizerName.value.trim()}.json` || !Number.isFinite(details?.mtimeMs)) {
|
|
10320
|
+
setThemeCustomizerStatus("The server returned conflict details for a different target. Refresh the catalog and try again.", "error");
|
|
10321
|
+
return;
|
|
10322
|
+
}
|
|
10323
|
+
state.overwrite = { signature: themeCustomizerDraftSignature(state), scope, fileName, mtimeMs: details.mtimeMs };
|
|
10324
|
+
elements.themeCustomizerOverwriteMessage.textContent = `${themeScopeLabel(scope)} themes / ${fileName} already exists. Replace only this file with the current unchanged draft?`;
|
|
10325
|
+
elements.themeCustomizerOverwrite.hidden = false;
|
|
10326
|
+
setThemeCustomizerStatus("Review the exact target, then confirm replacement. Any draft, name, or destination change cancels this confirmation.", "warn");
|
|
10327
|
+
updateThemeCustomizerActions();
|
|
10328
|
+
elements.themeCustomizerOverwriteButton.focus();
|
|
10329
|
+
}
|
|
10330
|
+
|
|
10331
|
+
async function saveThemeCustomizer({ overwrite = false } = {}) {
|
|
10332
|
+
const state = themeCustomizerState;
|
|
10333
|
+
if (!state?.draftValid || !state.validTheme || state.saving) return;
|
|
10334
|
+
if (!isCurrentTabContext(state.tabContext)) {
|
|
10335
|
+
setThemeCustomizerStatus("The active tab changed. Cancel and reopen Customize so the project destination is bound to the intended tab.", "warn");
|
|
10336
|
+
return;
|
|
10337
|
+
}
|
|
10338
|
+
const confirmation = state.overwrite;
|
|
10339
|
+
if (overwrite && (!confirmation || confirmation.signature !== themeCustomizerDraftSignature(state))) {
|
|
10340
|
+
invalidateThemeCustomizerOverwrite();
|
|
10341
|
+
setThemeCustomizerStatus("The overwrite confirmation no longer matches this target and draft. Save again to request a fresh confirmation.", "warn");
|
|
10342
|
+
updateThemeCustomizerActions();
|
|
10343
|
+
return;
|
|
10344
|
+
}
|
|
10345
|
+
const name = elements.themeCustomizerName.value.trim();
|
|
10346
|
+
const scope = elements.themeCustomizerScope.value;
|
|
10347
|
+
state.saving = true;
|
|
10348
|
+
updateThemeCustomizerActions();
|
|
10349
|
+
try {
|
|
10350
|
+
const response = await api("/api/themes/custom", {
|
|
10351
|
+
method: "POST",
|
|
10352
|
+
tabId: state.tabContext.tabId,
|
|
10353
|
+
body: {
|
|
10354
|
+
scope,
|
|
10355
|
+
fileName: `${name}.json`,
|
|
10356
|
+
theme: state.validTheme,
|
|
10357
|
+
overwrite,
|
|
10358
|
+
expectedMtimeMs: overwrite ? confirmation.mtimeMs : null,
|
|
10359
|
+
},
|
|
10360
|
+
});
|
|
10361
|
+
if (themeCustomizerState?.generation !== state.generation) return;
|
|
10362
|
+
invalidateThemeCustomizerOverwrite();
|
|
10363
|
+
await refreshThemeCatalog(state.tabContext);
|
|
10364
|
+
if (themeCustomizerState?.generation !== state.generation) return;
|
|
10365
|
+
applyTheme(state.validTheme, { persist: false });
|
|
10366
|
+
elements.themeCustomizerSourceBadge.textContent = `${themeScopeLabel(scope)} saved`;
|
|
10367
|
+
elements.themeCustomizerSourceBadge.className = `theme-scope-badge ${scope}`;
|
|
10368
|
+
setThemeCustomizerStatus(`Saved ${response.data?.fileName || `${name}.json`} to ${themeScopeLabel(scope)} themes. The WebUI catalog is refreshed. In Pi TUI, run /reload or restart, then choose it with /theme. No Pi or browser theme setting was changed.`, "success");
|
|
10369
|
+
} catch (error) {
|
|
10370
|
+
if (themeCustomizerState?.generation !== state.generation) return;
|
|
10371
|
+
const code = error.data?.code;
|
|
10372
|
+
if (code === "THEME_EXISTS") showThemeCustomizerOverwrite(error.data?.details);
|
|
10373
|
+
else if (code === "THEME_CHANGED") {
|
|
10374
|
+
invalidateThemeCustomizerOverwrite();
|
|
10375
|
+
setThemeCustomizerStatus("The target changed after confirmation and was not overwritten. Review the current file, then save again for a fresh target-bound confirmation.", "error");
|
|
10376
|
+
} else {
|
|
10377
|
+
const issues = error.data?.details?.issues;
|
|
10378
|
+
setThemeCustomizerStatus(Array.isArray(issues) && issues.length
|
|
10379
|
+
? issues.map(({ path, message }) => `${path}: ${message}`).join(" · ")
|
|
10380
|
+
: error.message || String(error), "error");
|
|
10381
|
+
}
|
|
10382
|
+
} finally {
|
|
10383
|
+
if (themeCustomizerState?.generation === state.generation) {
|
|
10384
|
+
state.saving = false;
|
|
10385
|
+
updateThemeCustomizerActions();
|
|
10386
|
+
}
|
|
10387
|
+
}
|
|
10388
|
+
}
|
|
10389
|
+
|
|
10390
|
+
function resetThemeCustomizerDraft() {
|
|
10391
|
+
const state = themeCustomizerState;
|
|
10392
|
+
if (!state?.initialTheme) return;
|
|
10393
|
+
const reset = cloneThemeDraft(state.initialTheme);
|
|
10394
|
+
elements.themeCustomizerName.value = reset.name;
|
|
10395
|
+
renderThemeCustomizerVisualFields(reset);
|
|
10396
|
+
renderThemeCustomizerOptionalFields(reset);
|
|
10397
|
+
acceptThemeCustomizerDraft(reset, { syncJson: true });
|
|
10398
|
+
}
|
|
10399
|
+
|
|
9699
10400
|
function renderThemeSelect({ unavailableLabel = "Theme bundle unavailable" } = {}) {
|
|
9700
10401
|
if (!elements.themeSelect) return;
|
|
9701
10402
|
elements.themeSelect.replaceChildren();
|
|
@@ -9704,6 +10405,7 @@ function renderThemeSelect({ unavailableLabel = "Theme bundle unavailable" } = {
|
|
|
9704
10405
|
option.value = "";
|
|
9705
10406
|
elements.themeSelect.append(option);
|
|
9706
10407
|
elements.themeSelect.disabled = true;
|
|
10408
|
+
if (elements.themeCustomizeButton) elements.themeCustomizeButton.disabled = true;
|
|
9707
10409
|
return;
|
|
9708
10410
|
}
|
|
9709
10411
|
if (!availableThemes.length) {
|
|
@@ -9711,11 +10413,14 @@ function renderThemeSelect({ unavailableLabel = "Theme bundle unavailable" } = {
|
|
|
9711
10413
|
option.value = "";
|
|
9712
10414
|
elements.themeSelect.append(option);
|
|
9713
10415
|
elements.themeSelect.disabled = true;
|
|
10416
|
+
if (elements.themeCustomizeButton) elements.themeCustomizeButton.disabled = true;
|
|
9714
10417
|
return;
|
|
9715
10418
|
}
|
|
9716
10419
|
elements.themeSelect.disabled = false;
|
|
10420
|
+
if (elements.themeCustomizeButton) elements.themeCustomizeButton.disabled = false;
|
|
9717
10421
|
for (const theme of availableThemes) {
|
|
9718
|
-
const
|
|
10422
|
+
const suffix = theme.custom ? ` · ${themeScopeLabel(theme.scope)}` : "";
|
|
10423
|
+
const option = make("option", undefined, `${theme.label || displayThemeName(theme.name) || theme.name}${suffix}`);
|
|
9719
10424
|
option.value = theme.name;
|
|
9720
10425
|
elements.themeSelect.append(option);
|
|
9721
10426
|
}
|
|
@@ -9750,6 +10455,7 @@ async function initializeThemes() {
|
|
|
9750
10455
|
throw error;
|
|
9751
10456
|
}
|
|
9752
10457
|
availableThemes = Array.isArray(response.data?.themes) ? response.data.themes : [];
|
|
10458
|
+
themeCatalogScopes = response.data?.scopes && typeof response.data.scopes === "object" ? response.data.scopes : themeCatalogScopes;
|
|
9753
10459
|
optionalFeatureAvailability.themeBundle = availableThemes.length > 0;
|
|
9754
10460
|
renderOptionalFeatureControls();
|
|
9755
10461
|
themeSchemeMode = storedThemeMode() ?? seedThemeSchemeFromStoredTheme();
|
|
@@ -9768,6 +10474,53 @@ function activeTabContext(tabId = activeTabId) {
|
|
|
9768
10474
|
return { tabId: tabId || null, generation: activeTabGeneration };
|
|
9769
10475
|
}
|
|
9770
10476
|
|
|
10477
|
+
function transcriptStreamOwner(tabId = activeTabId, generation = activeTabGeneration) {
|
|
10478
|
+
return `${tabId || ""}:${generation}`;
|
|
10479
|
+
}
|
|
10480
|
+
|
|
10481
|
+
function unknownTranscriptEvidenceText(event) {
|
|
10482
|
+
const update = event?.assistantMessageEvent || {};
|
|
10483
|
+
const value = update.delta ?? update.content ?? update.text ?? update.thinking ?? "";
|
|
10484
|
+
if (typeof value === "string") return value.slice(0, UNKNOWN_TRANSCRIPT_EVIDENCE_TEXT_LIMIT);
|
|
10485
|
+
try {
|
|
10486
|
+
return JSON.stringify(value).slice(0, UNKNOWN_TRANSCRIPT_EVIDENCE_TEXT_LIMIT);
|
|
10487
|
+
} catch {
|
|
10488
|
+
return "[unserializable transcript evidence]";
|
|
10489
|
+
}
|
|
10490
|
+
}
|
|
10491
|
+
|
|
10492
|
+
function preserveUnknownTranscriptEvidence(event, classification, owner) {
|
|
10493
|
+
const update = event?.assistantMessageEvent || {};
|
|
10494
|
+
const evidence = {
|
|
10495
|
+
owner: String(owner || ""),
|
|
10496
|
+
subtype: classification?.subtype || "(missing)",
|
|
10497
|
+
fields: Object.keys(update).slice(0, 16),
|
|
10498
|
+
text: unknownTranscriptEvidenceText(event),
|
|
10499
|
+
receivedAt: Date.now(),
|
|
10500
|
+
};
|
|
10501
|
+
appendBoundedStreamDiagnostic(unknownTranscriptEvidence, evidence, UNKNOWN_TRANSCRIPT_EVIDENCE_LIMIT);
|
|
10502
|
+
if (owner) {
|
|
10503
|
+
unknownTranscriptOwnersPendingReconcile.add(owner);
|
|
10504
|
+
while (unknownTranscriptOwnersPendingReconcile.size > UNKNOWN_TRANSCRIPT_EVIDENCE_LIMIT) {
|
|
10505
|
+
const oldest = unknownTranscriptOwnersPendingReconcile.values().next().value;
|
|
10506
|
+
if (oldest === undefined) break;
|
|
10507
|
+
unknownTranscriptOwnersPendingReconcile.delete(oldest);
|
|
10508
|
+
}
|
|
10509
|
+
}
|
|
10510
|
+
if (streamIsolationDebugLedger) {
|
|
10511
|
+
appendBoundedStreamDiagnostic(streamIsolationDebugLedger.unknownEvidence, evidence, UNKNOWN_TRANSCRIPT_EVIDENCE_LIMIT);
|
|
10512
|
+
}
|
|
10513
|
+
}
|
|
10514
|
+
|
|
10515
|
+
function reconcileUnknownTranscriptEvidenceAtBarrier(event) {
|
|
10516
|
+
const tabContext = activeTabContext(event?.tabId || activeTabId);
|
|
10517
|
+
const owner = transcriptStreamOwner(tabContext.tabId, tabContext.generation);
|
|
10518
|
+
if (!unknownTranscriptOwnersPendingReconcile.delete(owner)) return false;
|
|
10519
|
+
if (!isCurrentTabContext(tabContext)) return false;
|
|
10520
|
+
scheduleSemanticReconcile({ messages: true }, tabContext);
|
|
10521
|
+
return true;
|
|
10522
|
+
}
|
|
10523
|
+
|
|
9771
10524
|
function setActiveTabId(tabId, { remember = false } = {}) {
|
|
9772
10525
|
const nextTabId = tabId || null;
|
|
9773
10526
|
if (nextTabId !== activeTabId) {
|
|
@@ -9923,6 +10676,7 @@ function resetFileTreeState() {
|
|
|
9923
10676
|
fileTreeSearchTimer = null;
|
|
9924
10677
|
fileTreeSearchRequestSerial += 1;
|
|
9925
10678
|
fileTreeState = emptyFileTreeState(fileTreeState.requestSerial + 1);
|
|
10679
|
+
fileTreeLastRenderSignature = "";
|
|
9926
10680
|
if (elements.fileTreeSearchInput) elements.fileTreeSearchInput.value = "";
|
|
9927
10681
|
updateFileTreeSearchControls();
|
|
9928
10682
|
renderFileTree();
|
|
@@ -9943,10 +10697,47 @@ function fileTreeControlKey(node) {
|
|
|
9943
10697
|
return node?.classList?.contains("file-tree-item") && path ? `file-tree:${path}` : "";
|
|
9944
10698
|
}
|
|
9945
10699
|
|
|
10700
|
+
function fileTreeEntryRenderSignature(entry = {}) {
|
|
10701
|
+
return [
|
|
10702
|
+
normalizeFileTreePath(entry.path || ""),
|
|
10703
|
+
String(entry.name || ""),
|
|
10704
|
+
String(entry.type || ""),
|
|
10705
|
+
entry.directory === true,
|
|
10706
|
+
String(entry.extension || ""),
|
|
10707
|
+
String(entry.error || ""),
|
|
10708
|
+
];
|
|
10709
|
+
}
|
|
10710
|
+
|
|
10711
|
+
function fileTreeRenderSignature() {
|
|
10712
|
+
const entriesByPath = [...fileTreeState.entriesByPath.entries()]
|
|
10713
|
+
.map(([path, entries]) => [normalizeFileTreePath(path), (Array.isArray(entries) ? entries : []).map(fileTreeEntryRenderSignature)])
|
|
10714
|
+
.sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
|
|
10715
|
+
const gitStatusByPath = [...fileTreeState.gitStatusByPath.entries()]
|
|
10716
|
+
.map(([path, status]) => [normalizeFileTreePath(path), normalizeFileTreeGitStatus(status)])
|
|
10717
|
+
.sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
|
|
10718
|
+
return JSON.stringify({
|
|
10719
|
+
context: `${activeTabId || ""}:${activeTabGeneration}`,
|
|
10720
|
+
root: fileTreeState.root || "",
|
|
10721
|
+
displayCwd: fileTreeState.root || latestWorkspace?.displayCwd || activeTab()?.cwd || "",
|
|
10722
|
+
entriesByPath,
|
|
10723
|
+
expanded: [...fileTreeState.expanded].map(normalizeFileTreePath).sort(),
|
|
10724
|
+
loading: [...fileTreeState.loading].map(normalizeFileTreePath).sort(),
|
|
10725
|
+
selectedPath: normalizeFileTreePath(fileTreeState.selectedPath || ""),
|
|
10726
|
+
searchQuery: fileTreeState.searchQuery || fileTreeSearchQueryText(),
|
|
10727
|
+
searchEntries: fileTreeState.searchEntries.map(fileTreeEntryRenderSignature),
|
|
10728
|
+
searchLoading: fileTreeState.searchLoading,
|
|
10729
|
+
gitStatusRoot: fileTreeState.gitStatusRoot || "",
|
|
10730
|
+
gitStatusByPath,
|
|
10731
|
+
});
|
|
10732
|
+
}
|
|
10733
|
+
|
|
9946
10734
|
function renderFileTree() {
|
|
9947
10735
|
if (deferUiRenderDuringPointerActivation("file-tree", renderFileTree)) return;
|
|
9948
10736
|
const root = elements.fileTreeRoot;
|
|
9949
10737
|
if (!root) return;
|
|
10738
|
+
const renderSignature = fileTreeRenderSignature();
|
|
10739
|
+
if (renderSignature === fileTreeLastRenderSignature) return;
|
|
10740
|
+
fileTreeLastRenderSignature = renderSignature;
|
|
9950
10741
|
const continuityContextKey = `${activeTabId || ""}:${activeTabGeneration}:${fileTreeState.root || ""}`;
|
|
9951
10742
|
const focusSnapshot = captureScopedControlContinuity(root, continuityContextKey, fileTreeControlKey);
|
|
9952
10743
|
const restoreFocus = () => restoreScopedControlContinuity(root, continuityContextKey, focusSnapshot, (key) => [...root.querySelectorAll(".file-tree-item[data-path]")].find((node) => fileTreeControlKey(node) === key));
|
|
@@ -10143,7 +10934,7 @@ function appendFileTreeEntry(parent, entry, depth = 0) {
|
|
|
10143
10934
|
parent.append(item);
|
|
10144
10935
|
}
|
|
10145
10936
|
|
|
10146
|
-
async function loadFileTreeDirectory(path = FILE_TREE_ROOT_PATH, { force = false } = {}) {
|
|
10937
|
+
async function loadFileTreeDirectory(path = FILE_TREE_ROOT_PATH, { force = false, renderResult = true } = {}) {
|
|
10147
10938
|
const normalized = normalizeFileTreePath(path);
|
|
10148
10939
|
if (!force && fileTreeState.entriesByPath.has(normalized)) return fileTreeState.entriesByPath.get(normalized);
|
|
10149
10940
|
const tabContext = activeTabContext();
|
|
@@ -10151,8 +10942,10 @@ async function loadFileTreeDirectory(path = FILE_TREE_ROOT_PATH, { force = false
|
|
|
10151
10942
|
const serial = ++fileTreeState.requestSerial;
|
|
10152
10943
|
const hadCachedEntries = fileTreeState.entriesByPath.has(normalized);
|
|
10153
10944
|
fileTreeState.loading.add(normalized);
|
|
10154
|
-
if (!hadCachedEntries)
|
|
10155
|
-
|
|
10945
|
+
if (!hadCachedEntries) {
|
|
10946
|
+
setFileTreeStatus(normalized ? `Loading ${normalized}…` : "Loading workspace files…");
|
|
10947
|
+
renderFileTree();
|
|
10948
|
+
}
|
|
10156
10949
|
try {
|
|
10157
10950
|
const response = await api(fileApiPath("/api/files", normalized), { tabId: tabContext.tabId });
|
|
10158
10951
|
if (!isCurrentTabContext(tabContext) || serial < fileTreeState.requestSerial) return [];
|
|
@@ -10177,7 +10970,7 @@ async function loadFileTreeDirectory(path = FILE_TREE_ROOT_PATH, { force = false
|
|
|
10177
10970
|
return [];
|
|
10178
10971
|
} finally {
|
|
10179
10972
|
fileTreeState.loading.delete(normalized);
|
|
10180
|
-
if (isCurrentTabContext(tabContext)) renderFileTree();
|
|
10973
|
+
if (renderResult && isCurrentTabContext(tabContext)) renderFileTree();
|
|
10181
10974
|
}
|
|
10182
10975
|
}
|
|
10183
10976
|
|
|
@@ -10198,7 +10991,7 @@ function clearFileTreeSearch({ focus = false } = {}) {
|
|
|
10198
10991
|
if (focus) elements.fileTreeSearchInput?.focus();
|
|
10199
10992
|
}
|
|
10200
10993
|
|
|
10201
|
-
async function runFileTreeSearch() {
|
|
10994
|
+
async function runFileTreeSearch({ background = false } = {}) {
|
|
10202
10995
|
clearTimeout(fileTreeSearchTimer);
|
|
10203
10996
|
fileTreeSearchTimer = null;
|
|
10204
10997
|
const query = fileTreeSearchQueryText();
|
|
@@ -10211,12 +11004,14 @@ async function runFileTreeSearch() {
|
|
|
10211
11004
|
const tabContext = activeTabContext();
|
|
10212
11005
|
if (!tabContext.tabId) return [];
|
|
10213
11006
|
fileTreeState.searchQuery = query;
|
|
10214
|
-
|
|
10215
|
-
|
|
10216
|
-
|
|
10217
|
-
|
|
10218
|
-
|
|
10219
|
-
|
|
11007
|
+
if (!background) {
|
|
11008
|
+
fileTreeState.searchLoading = true;
|
|
11009
|
+
fileTreeState.searchEntries = [];
|
|
11010
|
+
fileTreeState.searchTruncated = false;
|
|
11011
|
+
fileTreeState.searchTotal = 0;
|
|
11012
|
+
setFileTreeStatus(`Searching for “${query}”…`);
|
|
11013
|
+
renderFileTree();
|
|
11014
|
+
}
|
|
10220
11015
|
try {
|
|
10221
11016
|
const response = await api(fileSearchApiPath(query), { tabId: tabContext.tabId });
|
|
10222
11017
|
if (!isCurrentTabContext(tabContext) || serial !== fileTreeSearchRequestSerial) return [];
|
|
@@ -10233,8 +11028,10 @@ async function runFileTreeSearch() {
|
|
|
10233
11028
|
return entries;
|
|
10234
11029
|
} catch (error) {
|
|
10235
11030
|
if (isCurrentTabContext(tabContext) && serial === fileTreeSearchRequestSerial) {
|
|
10236
|
-
|
|
10237
|
-
|
|
11031
|
+
if (!background) {
|
|
11032
|
+
fileTreeState.searchLoading = false;
|
|
11033
|
+
fileTreeState.searchEntries = [];
|
|
11034
|
+
}
|
|
10238
11035
|
setFileTreeStatus(error.message || String(error), "error");
|
|
10239
11036
|
addEvent(`file search failed: ${error.message || String(error)}`, "error");
|
|
10240
11037
|
}
|
|
@@ -10281,7 +11078,7 @@ async function refreshLoadedFileTreeDirectories(tabContext = activeTabContext())
|
|
|
10281
11078
|
}
|
|
10282
11079
|
};
|
|
10283
11080
|
if (fileTreeState.loading.has(FILE_TREE_ROOT_PATH)) return true;
|
|
10284
|
-
await loadFileTreeDirectory(FILE_TREE_ROOT_PATH, { force: true });
|
|
11081
|
+
await loadFileTreeDirectory(FILE_TREE_ROOT_PATH, { force: true, renderResult: false });
|
|
10285
11082
|
if (!isCurrentTabContext(tabContext)) return false;
|
|
10286
11083
|
collectDirectories(FILE_TREE_ROOT_PATH);
|
|
10287
11084
|
const cachedDirectories = [...fileTreeState.entriesByPath.keys()]
|
|
@@ -10299,7 +11096,7 @@ async function refreshLoadedFileTreeDirectories(tabContext = activeTabContext())
|
|
|
10299
11096
|
collectDirectories(path);
|
|
10300
11097
|
continue;
|
|
10301
11098
|
}
|
|
10302
|
-
await loadFileTreeDirectory(path, { force: true });
|
|
11099
|
+
await loadFileTreeDirectory(path, { force: true, renderResult: false });
|
|
10303
11100
|
if (!isCurrentTabContext(tabContext)) return false;
|
|
10304
11101
|
collectDirectories(path);
|
|
10305
11102
|
}
|
|
@@ -10323,7 +11120,7 @@ async function refreshFileTreeLive(tabContext = activeTabContext()) {
|
|
|
10323
11120
|
while (refreshContext && isCurrentTabContext(refreshContext)) {
|
|
10324
11121
|
fileTreeLiveRefreshPendingContext = null;
|
|
10325
11122
|
let skippedLoadingDirectory = false;
|
|
10326
|
-
if (fileTreeSearchQueryText()) await runFileTreeSearch();
|
|
11123
|
+
if (fileTreeSearchQueryText()) await runFileTreeSearch({ background: true });
|
|
10327
11124
|
else skippedLoadingDirectory = await refreshLoadedFileTreeDirectories(refreshContext);
|
|
10328
11125
|
if (skippedLoadingDirectory && isCurrentTabContext(refreshContext)) retryContext = refreshContext;
|
|
10329
11126
|
refreshContext = fileTreeLiveRefreshPendingContext;
|
|
@@ -10827,6 +11624,7 @@ const UI_LAYOUT_SAVE_DEBOUNCE_MS = 250;
|
|
|
10827
11624
|
const UI_LAYOUT_MAX_CONFLICT_RETRIES = 1;
|
|
10828
11625
|
const UI_LAYOUT_FIELDS = ["sidePanel", "composerActions", "footerScopedModelOrder", "terminalTabs", "fileViewerWidth"];
|
|
10829
11626
|
const UI_LAYOUT_SIDE_PANEL_FIELDS = ["sectionOrder", "collapsedSectionIds", "hiddenSectionIds", "collapsed"];
|
|
11627
|
+
const REMOVED_SIDE_PANEL_SECTION_HEIGHT_STORAGE_KEY = "pi-webui-side-panel-section-heights-v1";
|
|
10830
11628
|
const UI_LAYOUT_COMPOSER_FIELDS = ["order", "grid"];
|
|
10831
11629
|
const UI_LAYOUT_TERMINAL_FIELDS = ["layout", "customGroups"];
|
|
10832
11630
|
const UI_LAYOUT_PENDING_STORAGE_PREFIX = "pi-webui-ui-layout-pending-v3:";
|
|
@@ -11062,6 +11860,19 @@ function removeDurableUiLayoutPendingMutation(key) {
|
|
|
11062
11860
|
}
|
|
11063
11861
|
}
|
|
11064
11862
|
|
|
11863
|
+
function clearRemovedSidePanelSectionHeightState() {
|
|
11864
|
+
try {
|
|
11865
|
+
localStorage.removeItem(REMOVED_SIDE_PANEL_SECTION_HEIGHT_STORAGE_KEY);
|
|
11866
|
+
} catch {
|
|
11867
|
+
// Removed layout state may remain when browser storage is unavailable.
|
|
11868
|
+
}
|
|
11869
|
+
for (const record of durableUiLayoutPendingMutationRecords()) {
|
|
11870
|
+
if (record.field === "sidePanel" && record.subfield === "sectionHeights") {
|
|
11871
|
+
removeDurableUiLayoutPendingMutation(record.key);
|
|
11872
|
+
}
|
|
11873
|
+
}
|
|
11874
|
+
}
|
|
11875
|
+
|
|
11065
11876
|
function clearAcknowledgedDurableUiLayoutPendingMutations(snapshot) {
|
|
11066
11877
|
for (const entry of snapshot.values()) {
|
|
11067
11878
|
if (entry.subfieldMutationIds?.size) {
|
|
@@ -11285,6 +12096,8 @@ function applyDurableUiLayoutSnapshot(data, { generations = null, readEpoch = 0
|
|
|
11285
12096
|
const subfields = durableUiLayoutSubFields(field);
|
|
11286
12097
|
const dirtySubfields = dirtyEntry?.subfields;
|
|
11287
12098
|
|
|
12099
|
+
if (field === "sidePanel" && durableUiLayoutInteractionActive(field)) continue;
|
|
12100
|
+
|
|
11288
12101
|
if (subfields && field !== "composerActions") {
|
|
11289
12102
|
const applicable = {};
|
|
11290
12103
|
let hasApplicable = false;
|
|
@@ -12918,7 +13731,6 @@ function clearWidgetsForTab(tabId = activeTabId) {
|
|
|
12918
13731
|
|
|
12919
13732
|
function resetActiveTabUi() {
|
|
12920
13733
|
clearRefreshTimers();
|
|
12921
|
-
clearLiveToolRenderQueue();
|
|
12922
13734
|
eventSource?.close();
|
|
12923
13735
|
eventSource = null;
|
|
12924
13736
|
currentState = null;
|
|
@@ -12966,10 +13778,11 @@ function resetActiveTabUi() {
|
|
|
12966
13778
|
renderAppRunnerControls();
|
|
12967
13779
|
renderWidgets();
|
|
12968
13780
|
renderGitWorkflow();
|
|
12969
|
-
|
|
12970
|
-
|
|
12971
|
-
|
|
12972
|
-
|
|
13781
|
+
// renderMessages() is transcript-only, so tab-level chrome is rendered here
|
|
13782
|
+
// explicitly whether or not a cached transcript was restored.
|
|
13783
|
+
restoreCachedMessagesForActiveTab();
|
|
13784
|
+
renderFooter();
|
|
13785
|
+
renderFeedbackTray();
|
|
12973
13786
|
}
|
|
12974
13787
|
|
|
12975
13788
|
function tabGroupStatusRank(state) {
|
|
@@ -13891,7 +14704,7 @@ function renderTerminalTab(tab) {
|
|
|
13891
14704
|
applyStyledTooltip(button, terminalTabTooltip(tab), { ariaLabel: false, align: "start", description: true, variant: "workspace", targetKey: `terminal-tab:${tab.id}:switch` });
|
|
13892
14705
|
appendTerminalTabContent(button, { title: tab.title, indicator, meta: terminalTabMeta(tab, indicator), appRunnerRun, conversationModeActive, workflowModeActive, workflowCount });
|
|
13893
14706
|
button.addEventListener("click", () => switchTab(tab.id));
|
|
13894
|
-
wrapper.append(button);
|
|
14707
|
+
wrapper.append(button, createTerminalTabActions(tab));
|
|
13895
14708
|
|
|
13896
14709
|
if (tabs.length > 1) {
|
|
13897
14710
|
const close = make("button", "terminal-tab-close", "×");
|
|
@@ -13933,7 +14746,7 @@ function renderTerminalTabGroupItem(tab, group) {
|
|
|
13933
14746
|
event.stopPropagation();
|
|
13934
14747
|
switchTab(tab.id);
|
|
13935
14748
|
});
|
|
13936
|
-
item.append(button);
|
|
14749
|
+
item.append(button, createTerminalTabActions(tab));
|
|
13937
14750
|
|
|
13938
14751
|
if (tabs.length > 1) {
|
|
13939
14752
|
const close = make("button", "terminal-tab-close terminal-tab-group-item-close", "×");
|
|
@@ -14059,7 +14872,6 @@ function setNewTabMenuOpen(open) {
|
|
|
14059
14872
|
|
|
14060
14873
|
function initializeTerminalHeaderTooltips() {
|
|
14061
14874
|
applyStyledTooltip(elements.newTabButton, "Start a separate isolated Pi terminal", { ariaLabel: "Start a separate isolated Pi terminal" });
|
|
14062
|
-
applyStyledTooltip(elements.splitTabButton, "Split the active terminal to the right", { ariaLabel: "Split the active terminal to the right" });
|
|
14063
14875
|
applyStyledTooltip(elements.closeAllTabsButton, "Close all terminal tabs", { ariaLabel: "Close all terminal tabs" });
|
|
14064
14876
|
}
|
|
14065
14877
|
|
|
@@ -14104,6 +14916,8 @@ function terminalTabControlKey(node) {
|
|
|
14104
14916
|
const tabId = node?.closest?.("[data-tab-id]")?.dataset?.tabId;
|
|
14105
14917
|
if (tabId) {
|
|
14106
14918
|
if (node.classList.contains("terminal-tab-close")) return `terminal-tab:${tabId}:close`;
|
|
14919
|
+
if (node.classList.contains("terminal-tab-split-button")) return `terminal-tab:${tabId}:split`;
|
|
14920
|
+
if (node.classList.contains("terminal-tab-summary-button")) return `terminal-tab:${tabId}:summary`;
|
|
14107
14921
|
if (node.classList.contains("terminal-tab-button")) return `terminal-tab:${tabId}:switch`;
|
|
14108
14922
|
}
|
|
14109
14923
|
const groupKey = node?.closest?.("[data-group-key]")?.dataset?.groupKey;
|
|
@@ -14172,6 +14986,18 @@ function renderTabs() {
|
|
|
14172
14986
|
if (mobilePhoneExperienceInstalled && isMobileShellV2Active()) renderMobilePhoneExperience();
|
|
14173
14987
|
}
|
|
14174
14988
|
|
|
14989
|
+
function prefetchInactiveTabCommandCatalogs() {
|
|
14990
|
+
for (const tab of tabs) {
|
|
14991
|
+
if (!tab?.id || tab.id === activeTabId || commandCatalogsByTab.has(tab.id) || commandCatalogRefreshesByTab.has(tab.id)) continue;
|
|
14992
|
+
const refresh = refreshCommands(activeTabContext(tab.id))
|
|
14993
|
+
.catch(() => {})
|
|
14994
|
+
.finally(() => {
|
|
14995
|
+
if (commandCatalogRefreshesByTab.get(tab.id) === refresh) commandCatalogRefreshesByTab.delete(tab.id);
|
|
14996
|
+
});
|
|
14997
|
+
commandCatalogRefreshesByTab.set(tab.id, refresh);
|
|
14998
|
+
}
|
|
14999
|
+
}
|
|
15000
|
+
|
|
14175
15001
|
async function refreshTabs({ selectStored = false } = {}) {
|
|
14176
15002
|
const previousTabs = tabs;
|
|
14177
15003
|
const response = await api("/api/tabs", { scoped: false });
|
|
@@ -14196,6 +15022,7 @@ async function refreshTabs({ selectStored = false } = {}) {
|
|
|
14196
15022
|
}
|
|
14197
15023
|
renderSessionSkillTags(activeTabId);
|
|
14198
15024
|
renderTabs();
|
|
15025
|
+
prefetchInactiveTabCommandCatalogs();
|
|
14199
15026
|
return tabs;
|
|
14200
15027
|
}
|
|
14201
15028
|
|
|
@@ -14205,7 +15032,12 @@ async function switchTab(tabId) {
|
|
|
14205
15032
|
if (activeSubagentTerminalId) deactivateSubagentTerminalView({ focusParent: true });
|
|
14206
15033
|
return;
|
|
14207
15034
|
}
|
|
15035
|
+
if (themeCustomizerState?.saving) {
|
|
15036
|
+
setThemeCustomizerStatus("Wait for the theme save to finish before switching tabs.", "warn");
|
|
15037
|
+
return;
|
|
15038
|
+
}
|
|
14208
15039
|
if (activeSubagentTerminalId) deactivateSubagentTerminalView({ render: false });
|
|
15040
|
+
if (themeCustomizerState) closeThemeCustomizer({ restore: true });
|
|
14209
15041
|
clearOpenTerminalTabGroup(null, { force: true });
|
|
14210
15042
|
setFollowUpQueueOpen(false);
|
|
14211
15043
|
setFollowUpQueueStatus("");
|
|
@@ -14228,11 +15060,13 @@ async function switchTab(tabId) {
|
|
|
14228
15060
|
connectEvents(tabContext);
|
|
14229
15061
|
await refreshAll(tabContext);
|
|
14230
15062
|
if (isCurrentTabContext(tabContext)) markTabOutputSeen();
|
|
15063
|
+
await refreshThemeCatalog(tabContext).catch((error) => addEvent(`Custom theme catalog refresh failed: ${error.message || String(error)}`, "warn"));
|
|
14231
15064
|
if (!subagentLaunchSlotDraftIsDirty()) {
|
|
14232
15065
|
loadSubagentLaunchSlotConfig({ tabId }).catch(() => {});
|
|
14233
15066
|
} else {
|
|
14234
15067
|
renderSubagentLaunchSlots();
|
|
14235
15068
|
}
|
|
15069
|
+
refreshSamplingParametersForTabContext(tabContext);
|
|
14236
15070
|
}
|
|
14237
15071
|
|
|
14238
15072
|
function currentDirectoryForNewTab() {
|
|
@@ -14250,19 +15084,28 @@ function terminalSplitFrameUrl(tabId) {
|
|
|
14250
15084
|
return `${url.pathname}${url.search}`;
|
|
14251
15085
|
}
|
|
14252
15086
|
|
|
15087
|
+
function updateTerminalSplitControls(canShowSplit, splitTab = terminalSplitTab()) {
|
|
15088
|
+
elements.tabBar?.querySelectorAll(".terminal-tab-split-button").forEach((button) => {
|
|
15089
|
+
const tabId = button.closest("[data-tab-id]")?.dataset?.tabId || "";
|
|
15090
|
+
const tab = tabs.find((candidate) => candidate.id === tabId);
|
|
15091
|
+
const isOpenSplit = canShowSplit && tabId === splitTab?.id;
|
|
15092
|
+
button.disabled = embeddedSplitMode || isSidePanelOverlayView() || !tab;
|
|
15093
|
+
button.setAttribute("aria-pressed", isOpenSplit ? "true" : "false");
|
|
15094
|
+
button.dataset.splitState = isOpenSplit ? "unsplit" : "split";
|
|
15095
|
+
const label = isOpenSplit
|
|
15096
|
+
? `Close split view for ${tab?.title || "Pi terminal"}`
|
|
15097
|
+
: `Split ${tab?.title || "Pi terminal"} to the right`;
|
|
15098
|
+
applyStyledTooltip(button, label, { ariaLabel: label, targetKey: tabId ? `terminal-tab:${tabId}:split` : "" });
|
|
15099
|
+
});
|
|
15100
|
+
}
|
|
15101
|
+
|
|
14253
15102
|
function updateTerminalSplitUi() {
|
|
14254
15103
|
const tab = terminalSplitTab();
|
|
14255
15104
|
const canShowSplit = !!tab && !embeddedSplitMode && !isSidePanelOverlayView();
|
|
14256
15105
|
document.body.classList.toggle("terminal-split-open", canShowSplit);
|
|
14257
15106
|
if (elements.terminalSplitShell) elements.terminalSplitShell.hidden = !canShowSplit;
|
|
14258
15107
|
requestAnimationFrame(syncResizablePanelWidthsForViewport);
|
|
14259
|
-
|
|
14260
|
-
elements.splitTabButton.disabled = embeddedSplitMode || isSidePanelOverlayView() || !activeTab();
|
|
14261
|
-
elements.splitTabButton.setAttribute("aria-pressed", canShowSplit ? "true" : "false");
|
|
14262
|
-
elements.splitTabButton.dataset.splitState = canShowSplit ? "unsplit" : "split";
|
|
14263
|
-
const label = canShowSplit ? `Close split view for ${tab.title}` : "Split the active terminal to the right";
|
|
14264
|
-
applyStyledTooltip(elements.splitTabButton, label, { ariaLabel: label });
|
|
14265
|
-
}
|
|
15108
|
+
updateTerminalSplitControls(canShowSplit, tab);
|
|
14266
15109
|
if (!canShowSplit) return;
|
|
14267
15110
|
if (elements.terminalSplitTitle) elements.terminalSplitTitle.textContent = tab.title || "Split terminal";
|
|
14268
15111
|
if (elements.terminalSplitMeta) elements.terminalSplitMeta.textContent = [tab.running ? `pid ${tab.pid || "starting"}` : "stopped", normalizeDisplayPath(tab.cwd || "")].filter(Boolean).join(" · ");
|
|
@@ -14295,22 +15138,23 @@ function reconcileTerminalSplitState() {
|
|
|
14295
15138
|
updateTerminalSplitUi();
|
|
14296
15139
|
}
|
|
14297
15140
|
|
|
14298
|
-
async function
|
|
15141
|
+
async function splitTerminalTab(tabId, { triggerButton = null } = {}) {
|
|
14299
15142
|
if (embeddedSplitMode) return;
|
|
14300
|
-
if (splitTabId) {
|
|
15143
|
+
if (splitTabId === tabId) {
|
|
14301
15144
|
closeTerminalSplitView();
|
|
14302
15145
|
return;
|
|
14303
15146
|
}
|
|
14304
|
-
const sourceTab =
|
|
14305
|
-
|
|
15147
|
+
const sourceTab = tabs.find((tab) => tab.id === tabId);
|
|
15148
|
+
if (!sourceTab) return;
|
|
15149
|
+
if (splitTabId) closeTerminalSplitView();
|
|
15150
|
+
let resolvedCwd = sourceTab.cwd || latestWorkspace?.cwd || currentDirectoryForNewTab();
|
|
14306
15151
|
setMobileTabsExpanded(false);
|
|
14307
15152
|
setNewTabMenuOpen(false);
|
|
14308
15153
|
if (!resolvedCwd) {
|
|
14309
|
-
resolvedCwd = await pickCwd(sourceTab
|
|
15154
|
+
resolvedCwd = await pickCwd(sourceTab, "", { title: "Choose CWD for split terminal" });
|
|
14310
15155
|
if (!resolvedCwd) return;
|
|
14311
15156
|
}
|
|
14312
|
-
|
|
14313
|
-
for (const button of disabledButtons) button.disabled = true;
|
|
15157
|
+
if (triggerButton) triggerButton.disabled = true;
|
|
14314
15158
|
try {
|
|
14315
15159
|
const response = await api("/api/tabs", { method: "POST", body: { cwd: resolvedCwd }, scoped: false });
|
|
14316
15160
|
tabs = response.data?.tabs || tabs;
|
|
@@ -14319,12 +15163,12 @@ async function splitActiveTerminalTab({ triggerButton = elements.splitTabButton
|
|
|
14319
15163
|
if (tab?.id) {
|
|
14320
15164
|
setTerminalSplitTab(tab.id);
|
|
14321
15165
|
renderTabs();
|
|
14322
|
-
addEvent(`split ${sourceTab
|
|
15166
|
+
addEvent(`split ${sourceTab.title || "terminal"} into independent ${tab.title}`, "info");
|
|
14323
15167
|
}
|
|
14324
15168
|
} catch (error) {
|
|
14325
15169
|
addEvent(error.message, "error");
|
|
14326
15170
|
} finally {
|
|
14327
|
-
|
|
15171
|
+
if (triggerButton) triggerButton.disabled = false;
|
|
14328
15172
|
updateTerminalSplitUi();
|
|
14329
15173
|
}
|
|
14330
15174
|
}
|
|
@@ -14508,6 +15352,7 @@ async function initializeTabs() {
|
|
|
14508
15352
|
return [];
|
|
14509
15353
|
});
|
|
14510
15354
|
if (!saved.length) await createFirstTerminalTabFromChosenDirectory();
|
|
15355
|
+
await refreshThemeCatalog(activeTabContext()).catch((error) => addEvent(`Custom theme catalog refresh failed: ${error.message || String(error)}`, "warn"));
|
|
14511
15356
|
return;
|
|
14512
15357
|
}
|
|
14513
15358
|
focusPromptInput({ defer: true });
|
|
@@ -14519,6 +15364,8 @@ async function initializeTabs() {
|
|
|
14519
15364
|
if (!subagentLaunchSlotDraftIsDirty() || subagentLaunchSlotConfigTabId !== activeTabId) {
|
|
14520
15365
|
loadSubagentLaunchSlotConfig().catch(() => {});
|
|
14521
15366
|
}
|
|
15367
|
+
refreshSamplingParametersForTabContext(tabContext);
|
|
15368
|
+
await refreshThemeCatalog(tabContext).catch((error) => addEvent(`Custom theme catalog refresh failed: ${error.message || String(error)}`, "warn"));
|
|
14522
15369
|
}
|
|
14523
15370
|
}
|
|
14524
15371
|
|
|
@@ -15633,7 +16480,7 @@ const GIT_FOOTER_TOOLTIP_COPY = {
|
|
|
15633
16480
|
cwd: "Active working directory for this Web UI tab.",
|
|
15634
16481
|
git: "Current Git branch. detached means HEAD is not on a branch; no repo means the cwd is outside a Git work tree.",
|
|
15635
16482
|
"git-state": "Active Git operation or detached state. Finish or abort rebase/merge/cherry-pick/revert/bisect before normal commits.",
|
|
15636
|
-
sync: "Remote tracking divergence. ↑ means local commits
|
|
16483
|
+
sync: "Remote tracking divergence. ↑ means local commits to push; ↓ means remote commits to pull. Incoming-only Sync pulls from origin; outgoing Sync uses the confirmed push flow, including the guarded force-with-lease fallback when needed.",
|
|
15637
16484
|
changes: "Working tree and fetched remote summary. 🟢 staged, ✏️ modified unstaged, ➕ untracked, ⚠️ conflicted; ⬇️ means fetched remote commits to pull; 🔄/✓/⚠️ fetch shows the tab git fetch state; ✅ means no changes.",
|
|
15638
16485
|
"git-extra": "Extra Git signals. 📦 stash, 🧩 dirty submodules, 🌳 worktrees, 🏷️ tag at HEAD, 🕒 last commit age, 🔓 signing mismatch.",
|
|
15639
16486
|
worktree: "Git worktree checkout for this tab. Use branch worktrees to work on branches in parallel without switching this checkout.",
|
|
@@ -15710,7 +16557,7 @@ const GIT_FOOTER_VISIBILITY_LABELS = Object.freeze({
|
|
|
15710
16557
|
"webui-context-auto-compaction": "Auto-compaction action",
|
|
15711
16558
|
"webui-branch-picker": "Branch/worktree picker",
|
|
15712
16559
|
"webui-git-init": "Git init affordance",
|
|
15713
|
-
"webui-sync-push": "Sync push action",
|
|
16560
|
+
"webui-sync-push": "Sync pull/push action",
|
|
15714
16561
|
"webui-changes-modal": "Changes modal",
|
|
15715
16562
|
"webui-git-tools-modal": "Git tools modal",
|
|
15716
16563
|
"webui-model-picker": "Model picker",
|
|
@@ -15747,7 +16594,7 @@ const GIT_FOOTER_VISIBILITY_HINTS = Object.freeze({
|
|
|
15747
16594
|
"webui-context-auto-compaction": "Click action on context chips for auto-compaction.",
|
|
15748
16595
|
"webui-branch-picker": "Click action on the git branch/worktree chips.",
|
|
15749
16596
|
"webui-git-init": "Git initialization affordance when a tab has no repository.",
|
|
15750
|
-
"webui-sync-push": "
|
|
16597
|
+
"webui-sync-push": "Compatibility visibility key for incoming pull and outgoing push actions on Sync chips.",
|
|
15751
16598
|
"webui-changes-modal": "Click action opening the changes/conflicts modal.",
|
|
15752
16599
|
"webui-git-tools-modal": "Click action opening extra git tools.",
|
|
15753
16600
|
"webui-model-picker": "Click action opening the footer model picker.",
|
|
@@ -15919,6 +16766,7 @@ function setGitFooterVisibilitySelection(checked) {
|
|
|
15919
16766
|
function openGitFooterVisibilityDialog() {
|
|
15920
16767
|
if (!elements.gitFooterVisibilityDialog) return;
|
|
15921
16768
|
setOptionsMenuOpen(false);
|
|
16769
|
+
closeGitFooterContextMenu({ returnFocus: false });
|
|
15922
16770
|
hideFooterTooltip();
|
|
15923
16771
|
gitFooterVisibilityDirty = false;
|
|
15924
16772
|
renderGitFooterVisibilityDialog();
|
|
@@ -15932,6 +16780,65 @@ function closeGitFooterVisibilityDialog() {
|
|
|
15932
16780
|
if (elements.gitFooterVisibilityDialog?.open) elements.gitFooterVisibilityDialog.close();
|
|
15933
16781
|
}
|
|
15934
16782
|
|
|
16783
|
+
function closeGitFooterContextMenu({ returnFocus = true } = {}) {
|
|
16784
|
+
const trigger = gitFooterContextMenuState?.trigger;
|
|
16785
|
+
gitFooterContextMenuState = null;
|
|
16786
|
+
if (elements.gitFooterContextMenu) elements.gitFooterContextMenu.hidden = true;
|
|
16787
|
+
if (returnFocus && trigger?.isConnected) queueMicrotask(() => trigger.focus?.({ preventScroll: true }));
|
|
16788
|
+
}
|
|
16789
|
+
|
|
16790
|
+
function showGitFooterContextMenu(event, chip, trigger) {
|
|
16791
|
+
const menu = elements.gitFooterContextMenu;
|
|
16792
|
+
const key = cleanStatusText(chip?.key);
|
|
16793
|
+
if (!menu || !key) return;
|
|
16794
|
+
event.preventDefault();
|
|
16795
|
+
event.stopPropagation();
|
|
16796
|
+
closeFileContextMenu({ returnFocus: false });
|
|
16797
|
+
closeGitPanelContextMenu({ returnFocus: false });
|
|
16798
|
+
closeSidePanelContextMenu({ returnFocus: false });
|
|
16799
|
+
closeGitFooterContextMenu({ returnFocus: false });
|
|
16800
|
+
hideFooterTooltip();
|
|
16801
|
+
|
|
16802
|
+
const label = cleanStatusText(chip?.label) || gitFooterVisibilityLabel(key);
|
|
16803
|
+
gitFooterContextMenuState = { key, label, trigger };
|
|
16804
|
+
const disableButton = menu.querySelector('[data-git-footer-menu-action="disable"]');
|
|
16805
|
+
if (disableButton) disableButton.textContent = `Disable ${label} box`;
|
|
16806
|
+
menu.hidden = false;
|
|
16807
|
+
const rect = menu.getBoundingClientRect();
|
|
16808
|
+
const left = Math.min(event.clientX, Math.max(8, window.innerWidth - rect.width - 8));
|
|
16809
|
+
const top = Math.min(event.clientY, Math.max(8, window.innerHeight - rect.height - 8));
|
|
16810
|
+
menu.style.left = `${Math.max(8, left)}px`;
|
|
16811
|
+
menu.style.top = `${Math.max(8, top)}px`;
|
|
16812
|
+
menu.querySelector('[role="menuitem"]')?.focus({ preventScroll: true });
|
|
16813
|
+
}
|
|
16814
|
+
|
|
16815
|
+
function bindGitFooterContextMenu(node, chip) {
|
|
16816
|
+
if (!node || !chip?.key) return node;
|
|
16817
|
+
node.setAttribute("aria-keyshortcuts", "ContextMenu Shift+F10");
|
|
16818
|
+
node.addEventListener("contextmenu", (event) => showGitFooterContextMenu(event, chip, node));
|
|
16819
|
+
node.addEventListener("keydown", (event) => {
|
|
16820
|
+
if (event.key !== "ContextMenu" && !(event.shiftKey && event.key === "F10")) return;
|
|
16821
|
+
const rect = node.getBoundingClientRect();
|
|
16822
|
+
showGitFooterContextMenu({
|
|
16823
|
+
preventDefault: () => event.preventDefault(),
|
|
16824
|
+
stopPropagation: () => event.stopPropagation(),
|
|
16825
|
+
clientX: rect.left + Math.min(rect.width, 24),
|
|
16826
|
+
clientY: rect.bottom,
|
|
16827
|
+
}, chip, node);
|
|
16828
|
+
});
|
|
16829
|
+
return node;
|
|
16830
|
+
}
|
|
16831
|
+
|
|
16832
|
+
async function disableGitFooterContextChip(key, label) {
|
|
16833
|
+
try {
|
|
16834
|
+
await runGitFooterVisibilityCommand("hide", [key]);
|
|
16835
|
+
addEvent(`Disabled the ${label || key} Git footer box.`, "success");
|
|
16836
|
+
requestGitFooterWebuiPayload(activeTabContext(), { force: true, allowDuringRun: true });
|
|
16837
|
+
} catch (error) {
|
|
16838
|
+
addEvent(error.message || String(error), "error");
|
|
16839
|
+
}
|
|
16840
|
+
}
|
|
16841
|
+
|
|
15935
16842
|
function cleanFooterPayloadText(value, fallback = "", maxLength = 240) {
|
|
15936
16843
|
const text = cleanStatusText(value).slice(0, maxLength);
|
|
15937
16844
|
return text || fallback;
|
|
@@ -16319,16 +17226,25 @@ function renderGitFooterPayloadMetric(chip, payload) {
|
|
|
16319
17226
|
const node = footerMetric(chip.icon || "•", chip.label, chip.value, chip.tone ? `tone-${chip.tone}` : "", options);
|
|
16320
17227
|
if (chip.contextUsage) applyFooterContextUsage(node, chip.contextUsage);
|
|
16321
17228
|
if (chip.usageWindows) applyFooterUsageWindows(node, chip.usageWindows);
|
|
16322
|
-
return node;
|
|
17229
|
+
return bindGitFooterContextMenu(node, chip);
|
|
16323
17230
|
}
|
|
16324
17231
|
|
|
16325
|
-
function
|
|
16326
|
-
const
|
|
16327
|
-
|
|
17232
|
+
function gitFooterSyncCounts(value) {
|
|
17233
|
+
const text = String(value || "");
|
|
17234
|
+
const aheadMatch = text.match(/[↑⇡]\s*(\d+)/u);
|
|
17235
|
+
const behindMatch = text.match(/[↓⇣]\s*(\d+)/u);
|
|
17236
|
+
return {
|
|
17237
|
+
ahead: aheadMatch ? Number.parseInt(aheadMatch[1] || "0", 10) || 0 : 0,
|
|
17238
|
+
behind: behindMatch ? Number.parseInt(behindMatch[1] || "0", 10) || 0 : 0,
|
|
17239
|
+
};
|
|
16328
17240
|
}
|
|
16329
17241
|
|
|
16330
|
-
function
|
|
16331
|
-
|
|
17242
|
+
function gitFooterSyncAction(chip) {
|
|
17243
|
+
if (chip?.key !== "sync") return "";
|
|
17244
|
+
const { ahead, behind } = gitFooterSyncCounts(chip.value);
|
|
17245
|
+
if (behind > 0 && ahead === 0) return "pull";
|
|
17246
|
+
if (ahead > 0) return "push";
|
|
17247
|
+
return "";
|
|
16332
17248
|
}
|
|
16333
17249
|
|
|
16334
17250
|
function gitFooterCurrentBranch() {
|
|
@@ -16337,9 +17253,31 @@ function gitFooterCurrentBranch() {
|
|
|
16337
17253
|
return value && value !== "no repo" ? cleanFooterPayloadText(gitChip.value, "") : "";
|
|
16338
17254
|
}
|
|
16339
17255
|
|
|
17256
|
+
async function pullGitFooterSync(tabId = activeTabId) {
|
|
17257
|
+
if (!tabId || gitFooterSyncInFlightByTab.has(tabId)) return;
|
|
17258
|
+
const tabContext = activeTabContext(tabId);
|
|
17259
|
+
hideFooterTooltip();
|
|
17260
|
+
gitFooterSyncInFlightByTab.add(tabId);
|
|
17261
|
+
if (isCurrentTabContext(tabContext)) renderFooter();
|
|
17262
|
+
try {
|
|
17263
|
+
const response = await api("/api/git-changes/pull", { method: "POST", body: { remote: "origin" }, tabId });
|
|
17264
|
+
if (!response.ok) {
|
|
17265
|
+
const detail = [response.error, response.hint, formatGitCommandResult(response.data)].filter(Boolean).join("\n\n").trim();
|
|
17266
|
+
throw new Error(detail || "git pull from origin failed");
|
|
17267
|
+
}
|
|
17268
|
+
addEvent("Pulled Git changes from origin.", "success");
|
|
17269
|
+
requestGitFooterWebuiPayload(tabContext, { force: true });
|
|
17270
|
+
} catch (error) {
|
|
17271
|
+
addEvent(error.message || String(error), "error");
|
|
17272
|
+
} finally {
|
|
17273
|
+
gitFooterSyncInFlightByTab.delete(tabId);
|
|
17274
|
+
if (isCurrentTabContext(tabContext)) renderFooter();
|
|
17275
|
+
}
|
|
17276
|
+
}
|
|
17277
|
+
|
|
16340
17278
|
async function pushGitFooterSync(tabId = activeTabId, syncValue = "") {
|
|
16341
|
-
if (!tabId ||
|
|
16342
|
-
const outgoing =
|
|
17279
|
+
if (!tabId || gitFooterSyncInFlightByTab.has(tabId)) return;
|
|
17280
|
+
const outgoing = gitFooterSyncCounts(syncValue).ahead;
|
|
16343
17281
|
if (outgoing <= 0) return;
|
|
16344
17282
|
const tabContext = activeTabContext(tabId);
|
|
16345
17283
|
const tab = tabs.find((item) => item.id === tabId);
|
|
@@ -16351,7 +17289,7 @@ async function pushGitFooterSync(tabId = activeTabId, syncValue = "") {
|
|
|
16351
17289
|
: "";
|
|
16352
17290
|
if (!(await appConfirmText(`Run git push for ${outgoing} outgoing commit${outgoing === 1 ? "" : "s"} in ${target}?${protectedWarning}`, { affected: `Remote Git branch ${branch || "current branch"}`, confirmLabel: "Push commits" }))) return;
|
|
16353
17291
|
|
|
16354
|
-
|
|
17292
|
+
gitFooterSyncInFlightByTab.add(tabId);
|
|
16355
17293
|
if (isCurrentTabContext(tabContext)) renderFooter();
|
|
16356
17294
|
try {
|
|
16357
17295
|
const response = await api("/api/git-workflow/push", { method: "POST", body: {}, tabId });
|
|
@@ -16393,7 +17331,7 @@ async function pushGitFooterSync(tabId = activeTabId, syncValue = "") {
|
|
|
16393
17331
|
} catch (error) {
|
|
16394
17332
|
addEvent(error.message || String(error), "error");
|
|
16395
17333
|
} finally {
|
|
16396
|
-
|
|
17334
|
+
gitFooterSyncInFlightByTab.delete(tabId);
|
|
16397
17335
|
if (isCurrentTabContext(tabContext)) renderFooter();
|
|
16398
17336
|
}
|
|
16399
17337
|
}
|
|
@@ -16414,13 +17352,19 @@ function renderGitFooterPayloadMeta(chip, tab, payload) {
|
|
|
16414
17352
|
} else if (chip.key === "worktree" && visible("webui-branch-picker")) {
|
|
16415
17353
|
options.onClick = () => setFooterBranchPickerOpen(!footerBranchPickerOpen);
|
|
16416
17354
|
action = "Click to manage branch worktrees for this repository.";
|
|
16417
|
-
} else if (chip.key === "sync" && visible("webui-sync-push")
|
|
17355
|
+
} else if (chip.key === "sync" && visible("webui-sync-push")) {
|
|
16418
17356
|
const tabId = tab?.id || activeTabId;
|
|
16419
|
-
const
|
|
16420
|
-
|
|
17357
|
+
const syncAction = gitFooterSyncAction(chip);
|
|
17358
|
+
const inFlight = tabId ? gitFooterSyncInFlightByTab.has(tabId) : false;
|
|
17359
|
+
if (syncAction === "pull") {
|
|
17360
|
+
options.onClick = () => pullGitFooterSync(tabId);
|
|
17361
|
+
action = inFlight ? "Pulling from origin." : "Click to pull from origin with fast-forward only.";
|
|
17362
|
+
} else if (syncAction === "push") {
|
|
17363
|
+
options.onClick = () => pushGitFooterSync(tabId, chip.value);
|
|
17364
|
+
action = inFlight ? "Pushing local commits to the configured remote." : "Click to push local commits to the configured remote.";
|
|
17365
|
+
}
|
|
16421
17366
|
options.ariaBusy = inFlight;
|
|
16422
17367
|
options.disabled = inFlight;
|
|
16423
|
-
action = inFlight ? "Pushing local commits to the configured remote." : "Click to push local commits to the configured remote.";
|
|
16424
17368
|
} else if (chip.key === "changes" && visible("webui-changes-modal")) {
|
|
16425
17369
|
options.onClick = () => openGitChangesDialog(tab?.id || activeTabId);
|
|
16426
17370
|
action = "Click to view the current git diff.";
|
|
@@ -16450,7 +17394,7 @@ function renderGitFooterPayloadMeta(chip, tab, payload) {
|
|
|
16450
17394
|
}
|
|
16451
17395
|
if (chip.contextUsage) applyFooterContextUsage(node, chip.contextUsage);
|
|
16452
17396
|
if (chip.usageWindows) applyFooterUsageWindows(node, chip.usageWindows);
|
|
16453
|
-
return node;
|
|
17397
|
+
return bindGitFooterContextMenu(node, chip);
|
|
16454
17398
|
}
|
|
16455
17399
|
|
|
16456
17400
|
// Shape key for a footer chip with the frequently-changing fields removed, so
|
|
@@ -16486,10 +17430,10 @@ function footerBranchPickerRenderKey() {
|
|
|
16486
17430
|
function gitFooterPickerStateKey(payload) {
|
|
16487
17431
|
const tabContext = activeTabContext();
|
|
16488
17432
|
const refreshInFlight = tabContext.tabId ? gitFooterPayloadRefreshInFlightByTab.has(tabContext.tabId) : false;
|
|
16489
|
-
const
|
|
17433
|
+
const syncInFlight = tabContext.tabId ? gitFooterSyncInFlightByTab.has(tabContext.tabId) : false;
|
|
16490
17434
|
const piCalibrationInFlight = tabContext.tabId ? gitFooterPiCalibrationInFlightByTab.has(tabContext.tabId) : false;
|
|
16491
17435
|
const refreshAvailable = hasLoadedRpcCommand("git-footer-refresh");
|
|
16492
|
-
return `${footerModelPickerOpen ? 1 : 0}|${footerThinkingPickerOpen ? 1 : 0}|${footerBranchPickerOpen ? 1 : 0}|${footerBranchPickerRenderKey()}|${mobileFooterExpanded ? 1 : 0}|${refreshInFlight ? 1 : 0}|${
|
|
17436
|
+
return `${footerModelPickerOpen ? 1 : 0}|${footerThinkingPickerOpen ? 1 : 0}|${footerBranchPickerOpen ? 1 : 0}|${footerBranchPickerRenderKey()}|${mobileFooterExpanded ? 1 : 0}|${refreshInFlight ? 1 : 0}|${syncInFlight ? 1 : 0}|${piCalibrationInFlight ? 1 : 0}|${refreshAvailable ? 1 : 0}|${gitFooterPayloadVisibilityKey(payload)}`;
|
|
16493
17437
|
}
|
|
16494
17438
|
|
|
16495
17439
|
function updateGitFooterChipNodeValue(node, chip, valueSelector) {
|
|
@@ -16594,6 +17538,7 @@ function renderGitFooterPayload(payload) {
|
|
|
16594
17538
|
return;
|
|
16595
17539
|
}
|
|
16596
17540
|
|
|
17541
|
+
closeGitFooterContextMenu({ returnFocus: false });
|
|
16597
17542
|
elements.statusBar.replaceChildren();
|
|
16598
17543
|
elements.statusBar.classList.remove("statusbar-tui-footer");
|
|
16599
17544
|
elements.statusBar.classList.add("statusbar-git-footer");
|
|
@@ -20323,6 +21268,84 @@ function scheduleRefreshFooter(delay = 300, tabContext = activeTabContext()) {
|
|
|
20323
21268
|
}, delay);
|
|
20324
21269
|
}
|
|
20325
21270
|
|
|
21271
|
+
function semanticReconcileContextKey(tabContext = {}) {
|
|
21272
|
+
return `${tabContext.tabId || ""}:${Number(tabContext.generation) || 0}`;
|
|
21273
|
+
}
|
|
21274
|
+
|
|
21275
|
+
function mergeSemanticReconcileRequest(pendingByContext, dirty = {}, tabContext = {}) {
|
|
21276
|
+
const key = semanticReconcileContextKey(tabContext);
|
|
21277
|
+
let request = pendingByContext.get(key);
|
|
21278
|
+
if (!request) {
|
|
21279
|
+
request = { tabContext: { tabId: tabContext.tabId || null, generation: Number(tabContext.generation) || 0 }, dirty: {} };
|
|
21280
|
+
}
|
|
21281
|
+
let requested = false;
|
|
21282
|
+
for (const flag of SEMANTIC_RECONCILE_FLAGS) {
|
|
21283
|
+
if (!dirty[flag]) continue;
|
|
21284
|
+
request.dirty[flag] = true;
|
|
21285
|
+
requested = true;
|
|
21286
|
+
}
|
|
21287
|
+
if (requested) pendingByContext.set(key, request);
|
|
21288
|
+
return requested;
|
|
21289
|
+
}
|
|
21290
|
+
|
|
21291
|
+
function takeSemanticReconcileRequests(pendingByContext) {
|
|
21292
|
+
const requests = Array.from(pendingByContext.values());
|
|
21293
|
+
pendingByContext.clear();
|
|
21294
|
+
return requests;
|
|
21295
|
+
}
|
|
21296
|
+
|
|
21297
|
+
// Coalesced semantic reconciliation. Lifecycle boundaries declare which
|
|
21298
|
+
// non-transcript surfaces became dirty; each tab generation retains its own
|
|
21299
|
+
// request until the frame flush. Raw stream deltas never reach here.
|
|
21300
|
+
function scheduleSemanticReconcile(dirty = {}, tabContext = activeTabContext()) {
|
|
21301
|
+
if (!mergeSemanticReconcileRequest(semanticReconcilePending, dirty, tabContext)) return;
|
|
21302
|
+
if (semanticReconcileFrame !== null) return;
|
|
21303
|
+
const flush = () => {
|
|
21304
|
+
semanticReconcileFrame = null;
|
|
21305
|
+
flushSemanticReconcile();
|
|
21306
|
+
};
|
|
21307
|
+
if (typeof requestAnimationFrame === "function") semanticReconcileFrame = requestAnimationFrame(flush);
|
|
21308
|
+
else semanticReconcileFrame = setTimeout(flush, 0);
|
|
21309
|
+
}
|
|
21310
|
+
|
|
21311
|
+
function flushSemanticReconcile() {
|
|
21312
|
+
for (const { dirty, tabContext } of takeSemanticReconcileRequests(semanticReconcilePending)) {
|
|
21313
|
+
// Originating-tab settlement work is never reassigned. Workflow continuation
|
|
21314
|
+
// is tab-scoped and may run after the user has switched away.
|
|
21315
|
+
if (dirty.workflow) reconcileGitWorkflowContinuation(tabContext.tabId);
|
|
21316
|
+
if (dirty.usage) {
|
|
21317
|
+
scheduleRefreshCodexUsage(2200);
|
|
21318
|
+
scheduleRefreshClaudeUsage(2200);
|
|
21319
|
+
}
|
|
21320
|
+
|
|
21321
|
+
// DOM and active-session fetches are valid only for the still-current tab
|
|
21322
|
+
// generation; resetActiveTabUi/refreshAll owns the newly active tab.
|
|
21323
|
+
if (!isCurrentTabContext(tabContext)) continue;
|
|
21324
|
+
if (dirty.messages) scheduleRefreshMessages(120, tabContext);
|
|
21325
|
+
if (dirty.state) scheduleRefreshState(120, tabContext);
|
|
21326
|
+
if (dirty.footerData) scheduleRefreshFooter(300, tabContext);
|
|
21327
|
+
if (dirty.footer) renderFooter();
|
|
21328
|
+
if (dirty.feedback) renderFeedbackTray();
|
|
21329
|
+
if (dirty.usage) {
|
|
21330
|
+
refreshCodexFastMode(tabContext).catch((error) => addEvent(`Codex Fast mode refresh failed: ${error.message || String(error)}`, "warn"));
|
|
21331
|
+
}
|
|
21332
|
+
}
|
|
21333
|
+
}
|
|
21334
|
+
|
|
21335
|
+
// Continue a guided git workflow that was waiting on the agent turn. This is a
|
|
21336
|
+
// settlement-boundary concern, not a streaming concern.
|
|
21337
|
+
function reconcileGitWorkflowContinuation(workflowTabId = activeTabId) {
|
|
21338
|
+
const workflow = gitWorkflowForTab(workflowTabId, { create: false });
|
|
21339
|
+
if (!workflow?.active) return;
|
|
21340
|
+
if (workflow.step === "generating") {
|
|
21341
|
+
loadGitWorkflowMessage({ requireFresh: true, generationId: workflow.messageGenerationId, runId: workflow.runId, tabId: workflowTabId });
|
|
21342
|
+
} else if (workflow.step === "branchNaming") {
|
|
21343
|
+
loadGitWorkflowBranchName({ requireFresh: true, retries: 3, runId: workflow.runId, tabId: workflowTabId });
|
|
21344
|
+
} else if (workflow.step === "prGenerating") {
|
|
21345
|
+
loadGitWorkflowPr({ requireFresh: true, retries: 3, runId: workflow.runId, tabId: workflowTabId });
|
|
21346
|
+
}
|
|
21347
|
+
}
|
|
21348
|
+
|
|
20326
21349
|
function formatCodexPlanType(value) {
|
|
20327
21350
|
const text = String(value || "").trim();
|
|
20328
21351
|
if (!text) return "unknown plan";
|
|
@@ -22616,6 +23639,499 @@ function initializeSubagentLaunchSlots() {
|
|
|
22616
23639
|
if (activeTabId) loadSubagentLaunchSlotConfig().catch(() => {});
|
|
22617
23640
|
}
|
|
22618
23641
|
|
|
23642
|
+
function samplingParametersPath(tabId) {
|
|
23643
|
+
return `/api/tabs/${encodeURIComponent(tabId)}/sampling-parameters`;
|
|
23644
|
+
}
|
|
23645
|
+
|
|
23646
|
+
const samplingParameterControlElements = new Map();
|
|
23647
|
+
let samplingParameterTooltipDismissalInstalled = false;
|
|
23648
|
+
|
|
23649
|
+
function samplingParameterTooltipBoundary(row) {
|
|
23650
|
+
const viewportHeight = globalThis.innerHeight || document.documentElement?.clientHeight || 0;
|
|
23651
|
+
const clippingRects = [row?.closest?.(".side-panel-section-content"), row?.closest?.(".side-panel-body")]
|
|
23652
|
+
.map((node) => node?.getBoundingClientRect?.())
|
|
23653
|
+
.filter(Boolean);
|
|
23654
|
+
return {
|
|
23655
|
+
top: Math.max(8, ...clippingRects.map((rect) => rect.top)),
|
|
23656
|
+
bottom: Math.min(viewportHeight - 8, ...clippingRects.map((rect) => rect.bottom)),
|
|
23657
|
+
};
|
|
23658
|
+
}
|
|
23659
|
+
|
|
23660
|
+
function updateSamplingParameterTooltipPlacement(row, tooltip) {
|
|
23661
|
+
if (!row?.classList.contains("unsupported") || tooltip?.hidden || !row.getBoundingClientRect || !tooltip.getBoundingClientRect) return;
|
|
23662
|
+
tooltip.classList.remove("sampling-tooltip-below");
|
|
23663
|
+
tooltip.style?.removeProperty("--sampling-tooltip-max-height");
|
|
23664
|
+
const rowRect = row.getBoundingClientRect();
|
|
23665
|
+
const naturalHeight = Math.max(tooltip.scrollHeight || 0, tooltip.getBoundingClientRect().height || 0);
|
|
23666
|
+
const boundary = samplingParameterTooltipBoundary(row);
|
|
23667
|
+
const spaceAbove = Math.max(0, rowRect.top - boundary.top - 6);
|
|
23668
|
+
const spaceBelow = Math.max(0, boundary.bottom - rowRect.bottom - 6);
|
|
23669
|
+
const placeBelow = spaceAbove < naturalHeight && spaceBelow > spaceAbove;
|
|
23670
|
+
const availableHeight = placeBelow ? spaceBelow : spaceAbove;
|
|
23671
|
+
tooltip.classList.toggle("sampling-tooltip-below", placeBelow);
|
|
23672
|
+
tooltip.style?.setProperty("--sampling-tooltip-max-height", `${Math.floor(availableHeight)}px`);
|
|
23673
|
+
}
|
|
23674
|
+
|
|
23675
|
+
function resetSamplingParameterTooltip(row, tooltip) {
|
|
23676
|
+
row?.classList.remove("sampling-tooltip-dismissed");
|
|
23677
|
+
updateSamplingParameterTooltipPlacement(row, tooltip);
|
|
23678
|
+
}
|
|
23679
|
+
|
|
23680
|
+
function dismissSamplingParameterTooltip(row, event) {
|
|
23681
|
+
if (!row?.classList.contains("unsupported") || row.classList.contains("sampling-tooltip-dismissed")) return false;
|
|
23682
|
+
row.classList.add("sampling-tooltip-dismissed");
|
|
23683
|
+
event?.preventDefault?.();
|
|
23684
|
+
event?.stopPropagation?.();
|
|
23685
|
+
return true;
|
|
23686
|
+
}
|
|
23687
|
+
|
|
23688
|
+
function initializeSamplingParameterTooltipDismissal() {
|
|
23689
|
+
if (samplingParameterTooltipDismissalInstalled || typeof document.addEventListener !== "function") return;
|
|
23690
|
+
samplingParameterTooltipDismissalInstalled = true;
|
|
23691
|
+
document.addEventListener("keydown", (event) => {
|
|
23692
|
+
if (event.key !== "Escape" || event.target?.closest?.(".sampling-parameter-control.unsupported")) return;
|
|
23693
|
+
const hovered = document.querySelector?.(".sampling-parameter-control.unsupported:hover:not(.sampling-tooltip-dismissed)");
|
|
23694
|
+
if (hovered) dismissSamplingParameterTooltip(hovered, event);
|
|
23695
|
+
});
|
|
23696
|
+
}
|
|
23697
|
+
|
|
23698
|
+
function cloneSamplingControlDraft(draft) {
|
|
23699
|
+
return draft ? JSON.parse(JSON.stringify(draft)) : null;
|
|
23700
|
+
}
|
|
23701
|
+
|
|
23702
|
+
function samplingParametersBaseDraft(tabId = activeTabId) {
|
|
23703
|
+
if (!tabId || samplingParametersStateTabId !== tabId || !samplingParametersState) return null;
|
|
23704
|
+
return createSamplingControlDraft(samplingParametersState.session || {}, {
|
|
23705
|
+
defaults: samplingParametersState.defaults || {},
|
|
23706
|
+
});
|
|
23707
|
+
}
|
|
23708
|
+
|
|
23709
|
+
function samplingParametersDraft(tabId = activeTabId) {
|
|
23710
|
+
return tabId ? samplingParametersDrafts.get(tabId) ?? null : null;
|
|
23711
|
+
}
|
|
23712
|
+
|
|
23713
|
+
function setSamplingParametersDraft(draft, tabId = activeTabId) {
|
|
23714
|
+
if (!tabId) return;
|
|
23715
|
+
if (draft === null) samplingParametersDrafts.delete(tabId);
|
|
23716
|
+
else samplingParametersDrafts.set(tabId, cloneSamplingControlDraft(draft));
|
|
23717
|
+
}
|
|
23718
|
+
|
|
23719
|
+
function samplingParametersEditableDraft(tabId = activeTabId) {
|
|
23720
|
+
return samplingParametersDraft(tabId) || samplingParametersBaseDraft(tabId);
|
|
23721
|
+
}
|
|
23722
|
+
|
|
23723
|
+
// Drafts are keyed by Pi tab so background refreshes and tab switches cannot
|
|
23724
|
+
// overwrite or expose another session's unsaved controls.
|
|
23725
|
+
function samplingParametersDraftIsDirty(tabId = activeTabId) {
|
|
23726
|
+
const draft = samplingParametersDraft(tabId);
|
|
23727
|
+
if (!draft) return false;
|
|
23728
|
+
const baseline = samplingParametersBaseDraft(tabId);
|
|
23729
|
+
return !baseline || !samplingControlDraftEquals(draft, baseline);
|
|
23730
|
+
}
|
|
23731
|
+
|
|
23732
|
+
function samplingParametersSectionRecord() {
|
|
23733
|
+
return sidePanelSectionRecords().find(({ id }) => id === "sampling") || null;
|
|
23734
|
+
}
|
|
23735
|
+
|
|
23736
|
+
function samplingParametersSectionActive() {
|
|
23737
|
+
const record = samplingParametersSectionRecord();
|
|
23738
|
+
return !!record && !record.section.hidden && !record.section.classList.contains("collapsed");
|
|
23739
|
+
}
|
|
23740
|
+
|
|
23741
|
+
function samplingParametersSupportText() {
|
|
23742
|
+
const state = samplingParametersStateTabId === activeTabId ? samplingParametersState : null;
|
|
23743
|
+
const support = state?.support;
|
|
23744
|
+
if (!support) return samplingParametersLoading ? "Loading sampling support…" : "Select a running Pi tab to load sampling parameters.";
|
|
23745
|
+
const modelLabel = support.model?.provider && support.model?.id ? `(${support.model.provider}) ${support.model.id}` : "unknown model";
|
|
23746
|
+
const apiLabel = support.api || "unknown API";
|
|
23747
|
+
if (support.supported) return `${modelLabel} · ${apiLabel} · ${support.message || "Sampling parameters apply to subsequent provider requests."}`;
|
|
23748
|
+
const compatible = Array.isArray(support.compatibleApis) && support.compatibleApis.length
|
|
23749
|
+
? ` Sampling-capable APIs: ${support.compatibleApis.join(", ")}.`
|
|
23750
|
+
: "";
|
|
23751
|
+
return `${modelLabel} · ${apiLabel} · ${support.message || "Sampling parameters are stored but not applied."}${compatible}`;
|
|
23752
|
+
}
|
|
23753
|
+
|
|
23754
|
+
// Success and error text describes one tab's last action, so it is suppressed as soon
|
|
23755
|
+
// as another tab becomes active instead of leaking into the new tab's status line.
|
|
23756
|
+
function samplingParametersFeedbackIsCurrent() {
|
|
23757
|
+
return samplingParametersFeedbackTabId === activeTabId;
|
|
23758
|
+
}
|
|
23759
|
+
|
|
23760
|
+
function setSamplingParametersFeedback({ error = "", notice = "" } = {}) {
|
|
23761
|
+
samplingParametersError = error;
|
|
23762
|
+
samplingParametersNotice = notice;
|
|
23763
|
+
samplingParametersFeedbackTabId = error || notice ? activeTabId : null;
|
|
23764
|
+
}
|
|
23765
|
+
|
|
23766
|
+
function samplingParametersStatusText({ dirty, unsupported, validation, loadedForActiveTab }) {
|
|
23767
|
+
const feedbackCurrent = samplingParametersFeedbackIsCurrent();
|
|
23768
|
+
if (samplingParametersError && feedbackCurrent) return samplingParametersError;
|
|
23769
|
+
if (samplingParametersBusy) return "Applying sampling parameters…";
|
|
23770
|
+
if (samplingParametersLoading) return "Loading session sampling parameters…";
|
|
23771
|
+
if (!activeTabId) return "Select a running Pi tab to edit sampling parameters.";
|
|
23772
|
+
if (samplingParametersNotice && feedbackCurrent) return samplingParametersNotice;
|
|
23773
|
+
if (!loadedForActiveTab) return "Sampling parameters are not loaded for this tab.";
|
|
23774
|
+
if (!validation.valid) return Object.values(validation.errors)[0] || "Correct invalid sampling values before applying.";
|
|
23775
|
+
if (unsupported) return "This model has no verified sampling parameters, so applying them is disabled.";
|
|
23776
|
+
if (dirty) return "Unsaved controls · Apply stores enabled values for this session only.";
|
|
23777
|
+
return "Saved for this Pi session · unchecked parameters inherit model defaults.";
|
|
23778
|
+
}
|
|
23779
|
+
|
|
23780
|
+
function samplingParameterCapabilities(state) {
|
|
23781
|
+
return Object.fromEntries(SAMPLING_PARAMETER_CATALOG.map(({ key }) => [
|
|
23782
|
+
key,
|
|
23783
|
+
samplingParameterCapability(state?.support?.parameters, key),
|
|
23784
|
+
]));
|
|
23785
|
+
}
|
|
23786
|
+
|
|
23787
|
+
function samplingParameterDomId(key, suffix) {
|
|
23788
|
+
return `samplingParameter${key.split("_").map((part) => part[0].toUpperCase() + part.slice(1)).join("")}${suffix}`;
|
|
23789
|
+
}
|
|
23790
|
+
|
|
23791
|
+
function samplingParameterDisplayValue(parameters, key) {
|
|
23792
|
+
if (!parameters || typeof parameters !== "object" || !Object.hasOwn(parameters, key)) return "Inherited";
|
|
23793
|
+
const value = parameters[key];
|
|
23794
|
+
return typeof value === "number" && Number.isFinite(value) ? String(value) : "Invalid or unsupported value";
|
|
23795
|
+
}
|
|
23796
|
+
|
|
23797
|
+
function updateSamplingParameterControl(key, mutate) {
|
|
23798
|
+
const baseline = samplingParametersEditableDraft();
|
|
23799
|
+
if (!baseline || samplingParametersStateTabId !== activeTabId) return;
|
|
23800
|
+
const next = cloneSamplingControlDraft(baseline);
|
|
23801
|
+
mutate(next.controls[key]);
|
|
23802
|
+
setSamplingParametersDraft(next);
|
|
23803
|
+
setSamplingParametersFeedback();
|
|
23804
|
+
renderSamplingParameters();
|
|
23805
|
+
}
|
|
23806
|
+
|
|
23807
|
+
function initializeSamplingParameterControls() {
|
|
23808
|
+
if (!elements.samplingParametersControls || samplingParameterControlElements.size) return;
|
|
23809
|
+
initializeSamplingParameterTooltipDismissal();
|
|
23810
|
+
const groups = new Map();
|
|
23811
|
+
for (const [name, label] of [["core", "OpenAI-compatible controls"], ["server-extension", "Server extensions"]]) {
|
|
23812
|
+
const section = document.createElement("section");
|
|
23813
|
+
section.className = "sampling-parameter-group";
|
|
23814
|
+
section.dataset.samplingParameterGroup = name;
|
|
23815
|
+
const heading = document.createElement("h3");
|
|
23816
|
+
heading.textContent = label;
|
|
23817
|
+
section.append(heading);
|
|
23818
|
+
elements.samplingParametersControls.append(section);
|
|
23819
|
+
groups.set(name, section);
|
|
23820
|
+
}
|
|
23821
|
+
|
|
23822
|
+
for (const definition of SAMPLING_PARAMETER_CATALOG) {
|
|
23823
|
+
const row = document.createElement("div");
|
|
23824
|
+
row.className = "sampling-parameter-control";
|
|
23825
|
+
row.dataset.samplingParameter = definition.key;
|
|
23826
|
+
row.setAttribute("role", "group");
|
|
23827
|
+
|
|
23828
|
+
const enableId = samplingParameterDomId(definition.key, "Enabled");
|
|
23829
|
+
const valueId = samplingParameterDomId(definition.key, "Value");
|
|
23830
|
+
const rangeId = samplingParameterDomId(definition.key, "Range");
|
|
23831
|
+
const descriptionId = samplingParameterDomId(definition.key, "Description");
|
|
23832
|
+
const errorId = samplingParameterDomId(definition.key, "Error");
|
|
23833
|
+
const tooltipId = samplingParameterDomId(definition.key, "UnsupportedReason");
|
|
23834
|
+
row.setAttribute("aria-labelledby", `${enableId}Label`);
|
|
23835
|
+
|
|
23836
|
+
const header = document.createElement("div");
|
|
23837
|
+
header.className = "sampling-parameter-control-header";
|
|
23838
|
+
const enable = document.createElement("input");
|
|
23839
|
+
enable.id = enableId;
|
|
23840
|
+
enable.type = "checkbox";
|
|
23841
|
+
const label = document.createElement("label");
|
|
23842
|
+
label.id = `${enableId}Label`;
|
|
23843
|
+
label.htmlFor = enableId;
|
|
23844
|
+
label.textContent = definition.label;
|
|
23845
|
+
const scope = document.createElement("span");
|
|
23846
|
+
scope.className = "sampling-parameter-scope";
|
|
23847
|
+
scope.textContent = definition.scopeLabel;
|
|
23848
|
+
header.append(enable, label, scope);
|
|
23849
|
+
|
|
23850
|
+
const description = document.createElement("p");
|
|
23851
|
+
description.id = descriptionId;
|
|
23852
|
+
description.className = "sampling-parameter-description";
|
|
23853
|
+
description.textContent = definition.description;
|
|
23854
|
+
|
|
23855
|
+
const editor = document.createElement("div");
|
|
23856
|
+
editor.className = "sampling-parameter-editor";
|
|
23857
|
+
const number = document.createElement("input");
|
|
23858
|
+
number.id = valueId;
|
|
23859
|
+
number.className = "sampling-parameter-number";
|
|
23860
|
+
number.type = "number";
|
|
23861
|
+
number.inputMode = definition.kind === "integer" ? "numeric" : "decimal";
|
|
23862
|
+
number.step = String(definition.step);
|
|
23863
|
+
if (definition.min !== undefined && !definition.minExclusive) number.min = String(definition.min);
|
|
23864
|
+
if (definition.max !== undefined) number.max = String(definition.max);
|
|
23865
|
+
number.setAttribute("aria-label", `${definition.label} exact value`);
|
|
23866
|
+
number.setAttribute("aria-describedby", `${descriptionId} ${errorId}`);
|
|
23867
|
+
const range = document.createElement("input");
|
|
23868
|
+
range.id = rangeId;
|
|
23869
|
+
range.className = "sampling-parameter-range";
|
|
23870
|
+
range.type = "range";
|
|
23871
|
+
range.min = String(definition.slider.min);
|
|
23872
|
+
range.max = String(definition.slider.max);
|
|
23873
|
+
range.step = String(definition.slider.step);
|
|
23874
|
+
range.setAttribute("aria-label", `${definition.label} common-range slider`);
|
|
23875
|
+
range.setAttribute("aria-describedby", descriptionId);
|
|
23876
|
+
editor.append(number, range);
|
|
23877
|
+
|
|
23878
|
+
const context = document.createElement("dl");
|
|
23879
|
+
context.className = "sampling-parameter-context";
|
|
23880
|
+
const defaultTerm = document.createElement("dt");
|
|
23881
|
+
defaultTerm.textContent = "Model default";
|
|
23882
|
+
const defaultValue = document.createElement("dd");
|
|
23883
|
+
const effectiveTerm = document.createElement("dt");
|
|
23884
|
+
effectiveTerm.textContent = "Effective";
|
|
23885
|
+
const effectiveValue = document.createElement("dd");
|
|
23886
|
+
context.append(defaultTerm, defaultValue, effectiveTerm, effectiveValue);
|
|
23887
|
+
|
|
23888
|
+
const error = document.createElement("p");
|
|
23889
|
+
error.id = errorId;
|
|
23890
|
+
error.className = "sampling-parameter-error";
|
|
23891
|
+
error.setAttribute("aria-live", "polite");
|
|
23892
|
+
|
|
23893
|
+
const tooltip = document.createElement("p");
|
|
23894
|
+
tooltip.id = tooltipId;
|
|
23895
|
+
tooltip.className = "sampling-parameter-unsupported-tooltip";
|
|
23896
|
+
tooltip.setAttribute("role", "tooltip");
|
|
23897
|
+
|
|
23898
|
+
enable.addEventListener("change", () => updateSamplingParameterControl(definition.key, (control) => {
|
|
23899
|
+
control.enabled = enable.checked;
|
|
23900
|
+
}));
|
|
23901
|
+
number.addEventListener("input", () => updateSamplingParameterControl(definition.key, (control) => {
|
|
23902
|
+
control.value = number.value;
|
|
23903
|
+
}));
|
|
23904
|
+
range.addEventListener("input", () => updateSamplingParameterControl(definition.key, (control) => {
|
|
23905
|
+
control.value = range.value;
|
|
23906
|
+
}));
|
|
23907
|
+
row.addEventListener("keydown", (event) => {
|
|
23908
|
+
if (event.key === "Escape") dismissSamplingParameterTooltip(row, event);
|
|
23909
|
+
});
|
|
23910
|
+
row.addEventListener("pointerenter", () => resetSamplingParameterTooltip(row, tooltip));
|
|
23911
|
+
row.addEventListener("focusin", () => resetSamplingParameterTooltip(row, tooltip));
|
|
23912
|
+
row.addEventListener("focusout", (event) => {
|
|
23913
|
+
if (!row.contains?.(event.relatedTarget) && !row.matches?.(":hover")) row.classList.remove("sampling-tooltip-dismissed");
|
|
23914
|
+
});
|
|
23915
|
+
|
|
23916
|
+
row.append(header, description, editor, context, error, tooltip);
|
|
23917
|
+
groups.get(definition.group)?.append(row);
|
|
23918
|
+
samplingParameterControlElements.set(definition.key, { row, enable, number, range, defaultValue, effectiveValue, error, tooltip });
|
|
23919
|
+
}
|
|
23920
|
+
}
|
|
23921
|
+
|
|
23922
|
+
function renderSamplingParameters() {
|
|
23923
|
+
initializeSamplingParameterControls();
|
|
23924
|
+
const loadedForActiveTab = !!samplingParametersState && samplingParametersStateTabId === activeTabId;
|
|
23925
|
+
const activeState = loadedForActiveTab ? samplingParametersState : null;
|
|
23926
|
+
const editableDraft = samplingParametersEditableDraft()
|
|
23927
|
+
|| createSamplingControlDraft({}, { defaults: activeState?.defaults || {} });
|
|
23928
|
+
const validation = validateSamplingControlDraft(editableDraft);
|
|
23929
|
+
const dirty = samplingParametersDraftIsDirty();
|
|
23930
|
+
const capabilities = samplingParameterCapabilities(activeState);
|
|
23931
|
+
const unsupported = !Object.values(capabilities).some(({ supported }) => supported);
|
|
23932
|
+
const feedbackError = !!samplingParametersError && samplingParametersFeedbackIsCurrent();
|
|
23933
|
+
const showError = feedbackError || !validation.valid;
|
|
23934
|
+
const defaults = splitSamplingParameters(activeState?.defaults || {}).known;
|
|
23935
|
+
const effective = splitSamplingParameters(activeState?.effective || {}).known;
|
|
23936
|
+
const controlsDisabled = samplingParametersBusy || samplingParametersLoading || !activeTabId || !loadedForActiveTab;
|
|
23937
|
+
|
|
23938
|
+
for (const definition of SAMPLING_PARAMETER_CATALOG) {
|
|
23939
|
+
const refs = samplingParameterControlElements.get(definition.key);
|
|
23940
|
+
if (!refs) continue;
|
|
23941
|
+
const control = editableDraft.controls[definition.key];
|
|
23942
|
+
const capability = capabilities[definition.key];
|
|
23943
|
+
const parameterUnsupported = !capability.supported;
|
|
23944
|
+
const error = validation.errors[definition.key] || "";
|
|
23945
|
+
const valueText = typeof control.value === "number" || typeof control.value === "string" ? String(control.value) : "";
|
|
23946
|
+
const tooltipId = samplingParameterDomId(definition.key, "UnsupportedReason");
|
|
23947
|
+
refs.enable.checked = control.enabled;
|
|
23948
|
+
refs.enable.disabled = controlsDisabled || parameterUnsupported;
|
|
23949
|
+
refs.number.disabled = controlsDisabled || parameterUnsupported || !control.enabled;
|
|
23950
|
+
refs.range.disabled = controlsDisabled || parameterUnsupported || !control.enabled;
|
|
23951
|
+
if (refs.number.value !== valueText) refs.number.value = valueText;
|
|
23952
|
+
refs.range.value = String(samplingParameterSliderValue(definition.key, control.value));
|
|
23953
|
+
refs.number.setAttribute("aria-invalid", error ? "true" : "false");
|
|
23954
|
+
refs.row.classList.toggle("enabled", control.enabled);
|
|
23955
|
+
refs.row.classList.toggle("invalid", !!error);
|
|
23956
|
+
refs.row.classList.toggle("unsupported", parameterUnsupported);
|
|
23957
|
+
refs.row.tabIndex = parameterUnsupported ? 0 : -1;
|
|
23958
|
+
if (parameterUnsupported) {
|
|
23959
|
+
refs.row.setAttribute("aria-disabled", "true");
|
|
23960
|
+
refs.row.setAttribute("aria-describedby", tooltipId);
|
|
23961
|
+
refs.enable.setAttribute("aria-describedby", tooltipId);
|
|
23962
|
+
} else {
|
|
23963
|
+
refs.row.removeAttribute("aria-disabled");
|
|
23964
|
+
refs.row.removeAttribute("aria-describedby");
|
|
23965
|
+
refs.enable.removeAttribute("aria-describedby");
|
|
23966
|
+
refs.row.classList.remove("sampling-tooltip-dismissed");
|
|
23967
|
+
}
|
|
23968
|
+
refs.defaultValue.textContent = samplingParameterDisplayValue(defaults, definition.key);
|
|
23969
|
+
refs.effectiveValue.textContent = samplingParameterDisplayValue(effective, definition.key);
|
|
23970
|
+
refs.error.textContent = error;
|
|
23971
|
+
refs.error.hidden = !error;
|
|
23972
|
+
refs.tooltip.hidden = !parameterUnsupported;
|
|
23973
|
+
refs.tooltip.textContent = parameterUnsupported ? capability.reason : "";
|
|
23974
|
+
}
|
|
23975
|
+
|
|
23976
|
+
if (elements.samplingParametersSupport) {
|
|
23977
|
+
elements.samplingParametersSupport.textContent = samplingParametersSupportText();
|
|
23978
|
+
elements.samplingParametersSupport.classList.toggle("warning", unsupported);
|
|
23979
|
+
}
|
|
23980
|
+
if (elements.samplingParametersPreserved) {
|
|
23981
|
+
elements.samplingParametersPreserved.textContent = loadedForActiveTab
|
|
23982
|
+
? summarizePreservedSamplingParameters(editableDraft.preservedUnknown).text
|
|
23983
|
+
: samplingParametersLoading ? "Loading additional parameter state…" : "Additional parameter state is not loaded for this tab.";
|
|
23984
|
+
}
|
|
23985
|
+
if (elements.applySamplingParametersButton) {
|
|
23986
|
+
elements.applySamplingParametersButton.disabled = samplingParametersBusy
|
|
23987
|
+
|| samplingParametersLoading
|
|
23988
|
+
|| !activeTabId
|
|
23989
|
+
|| !loadedForActiveTab
|
|
23990
|
+
|| unsupported
|
|
23991
|
+
|| !validation.valid;
|
|
23992
|
+
elements.applySamplingParametersButton.textContent = samplingParametersBusy ? "Applying…" : "Apply";
|
|
23993
|
+
}
|
|
23994
|
+
if (elements.resetSamplingParametersButton) {
|
|
23995
|
+
elements.resetSamplingParametersButton.disabled = samplingParametersBusy
|
|
23996
|
+
|| samplingParametersLoading
|
|
23997
|
+
|| !activeTabId
|
|
23998
|
+
|| !loadedForActiveTab;
|
|
23999
|
+
}
|
|
24000
|
+
if (elements.reloadSamplingParametersButton) {
|
|
24001
|
+
elements.reloadSamplingParametersButton.disabled = samplingParametersBusy || samplingParametersLoading || !activeTabId;
|
|
24002
|
+
}
|
|
24003
|
+
if (elements.samplingParametersStatus) {
|
|
24004
|
+
elements.samplingParametersStatus.textContent = samplingParametersStatusText({ dirty, unsupported, validation, loadedForActiveTab });
|
|
24005
|
+
elements.samplingParametersStatus.classList.toggle("error", showError);
|
|
24006
|
+
elements.samplingParametersStatus.classList.toggle("warning", !showError && unsupported);
|
|
24007
|
+
}
|
|
24008
|
+
}
|
|
24009
|
+
|
|
24010
|
+
function applySamplingParametersResponse(data, tabId) {
|
|
24011
|
+
const existingDraft = samplingParametersDraft(tabId);
|
|
24012
|
+
samplingParametersState = data || null;
|
|
24013
|
+
samplingParametersStateTabId = tabId;
|
|
24014
|
+
if (existingDraft) {
|
|
24015
|
+
const loadedDraft = samplingParametersBaseDraft(tabId);
|
|
24016
|
+
existingDraft.preservedUnknown = cloneSamplingControlDraft(loadedDraft)?.preservedUnknown || {};
|
|
24017
|
+
setSamplingParametersDraft(existingDraft, tabId);
|
|
24018
|
+
}
|
|
24019
|
+
if (!samplingParametersDraftIsDirty(tabId)) setSamplingParametersDraft(null, tabId);
|
|
24020
|
+
}
|
|
24021
|
+
|
|
24022
|
+
async function loadSamplingParameters({ tabId = activeTabId, force = false } = {}) {
|
|
24023
|
+
if (!tabId) {
|
|
24024
|
+
samplingParametersState = null;
|
|
24025
|
+
samplingParametersStateTabId = null;
|
|
24026
|
+
renderSamplingParameters();
|
|
24027
|
+
return;
|
|
24028
|
+
}
|
|
24029
|
+
// Structured drafts are stored separately from loaded state, so a background
|
|
24030
|
+
// refresh can update support/default/hidden-key context without discarding edits.
|
|
24031
|
+
if (force) setSamplingParametersDraft(null, tabId);
|
|
24032
|
+
const requestSerial = ++samplingParametersRequestSerial;
|
|
24033
|
+
samplingParametersLoading = true;
|
|
24034
|
+
setSamplingParametersFeedback();
|
|
24035
|
+
renderSamplingParameters();
|
|
24036
|
+
try {
|
|
24037
|
+
const response = await api(samplingParametersPath(tabId), { scoped: false });
|
|
24038
|
+
if (requestSerial !== samplingParametersRequestSerial || tabId !== activeTabId) return;
|
|
24039
|
+
applySamplingParametersResponse(response.data, tabId);
|
|
24040
|
+
} catch (error) {
|
|
24041
|
+
if (requestSerial !== samplingParametersRequestSerial || tabId !== activeTabId) return;
|
|
24042
|
+
setSamplingParametersFeedback({ error: `Could not load sampling parameters: ${error.message || String(error)}` });
|
|
24043
|
+
} finally {
|
|
24044
|
+
if (requestSerial === samplingParametersRequestSerial) {
|
|
24045
|
+
samplingParametersLoading = false;
|
|
24046
|
+
renderSamplingParameters();
|
|
24047
|
+
}
|
|
24048
|
+
}
|
|
24049
|
+
}
|
|
24050
|
+
|
|
24051
|
+
// Background refresh for tab and model changes. It stays quiet until the section has
|
|
24052
|
+
// been opened once, so collapsed panels never pay for helper round-trips.
|
|
24053
|
+
function refreshSamplingParametersForTabContext(tabContext = activeTabContext()) {
|
|
24054
|
+
if (!tabContext.tabId) return;
|
|
24055
|
+
if (!samplingParametersState && !samplingParametersSectionActive()) return;
|
|
24056
|
+
return loadSamplingParameters({ tabId: tabContext.tabId }).catch(() => {});
|
|
24057
|
+
}
|
|
24058
|
+
|
|
24059
|
+
async function writeSamplingParameters(samplingParams, { successNotice }) {
|
|
24060
|
+
const tabId = activeTabId;
|
|
24061
|
+
if (!tabId) return;
|
|
24062
|
+
const requestSerial = ++samplingParametersRequestSerial;
|
|
24063
|
+
samplingParametersBusy = true;
|
|
24064
|
+
setSamplingParametersFeedback();
|
|
24065
|
+
renderSamplingParameters();
|
|
24066
|
+
try {
|
|
24067
|
+
const response = await api(samplingParametersPath(tabId), { method: "PUT", body: samplingParams, scoped: false });
|
|
24068
|
+
setSamplingParametersDraft(null, tabId);
|
|
24069
|
+
if (requestSerial !== samplingParametersRequestSerial || tabId !== activeTabId) return;
|
|
24070
|
+
applySamplingParametersResponse(response.data, tabId);
|
|
24071
|
+
setSamplingParametersFeedback({ notice: successNotice });
|
|
24072
|
+
} catch (error) {
|
|
24073
|
+
if (requestSerial !== samplingParametersRequestSerial || tabId !== activeTabId) return;
|
|
24074
|
+
setSamplingParametersFeedback({ error: `Could not save sampling parameters: ${error.message || String(error)}` });
|
|
24075
|
+
} finally {
|
|
24076
|
+
// Writes are serialized by the busy guard. A tab/model refresh may supersede
|
|
24077
|
+
// the response serial, but it must never strand the section in a busy state.
|
|
24078
|
+
samplingParametersBusy = false;
|
|
24079
|
+
renderSamplingParameters();
|
|
24080
|
+
}
|
|
24081
|
+
}
|
|
24082
|
+
|
|
24083
|
+
async function applySamplingParameters() {
|
|
24084
|
+
if (!activeTabId || samplingParametersBusy) return;
|
|
24085
|
+
if (!samplingParametersState || samplingParametersStateTabId !== activeTabId) {
|
|
24086
|
+
setSamplingParametersFeedback({ error: "Wait for this tab's sampling parameters to load before applying changes." });
|
|
24087
|
+
renderSamplingParameters();
|
|
24088
|
+
return;
|
|
24089
|
+
}
|
|
24090
|
+
const capabilities = samplingParameterCapabilities(samplingParametersState);
|
|
24091
|
+
if (!Object.values(capabilities).some(({ supported }) => supported)) {
|
|
24092
|
+
setSamplingParametersFeedback({ error: "This model has no verified sampling parameters, so nothing was sent." });
|
|
24093
|
+
renderSamplingParameters();
|
|
24094
|
+
return;
|
|
24095
|
+
}
|
|
24096
|
+
const draft = samplingParametersEditableDraft();
|
|
24097
|
+
const validation = validateSamplingControlDraft(draft);
|
|
24098
|
+
if (!validation.valid) {
|
|
24099
|
+
setSamplingParametersFeedback({ error: Object.values(validation.errors)[0] || "Correct invalid sampling values before applying." });
|
|
24100
|
+
renderSamplingParameters();
|
|
24101
|
+
return;
|
|
24102
|
+
}
|
|
24103
|
+
const samplingParams = buildSamplingParametersFromDraft(draft);
|
|
24104
|
+
await writeSamplingParameters(samplingParams, {
|
|
24105
|
+
successNotice: Object.keys(samplingParams).length
|
|
24106
|
+
? "Applied to this Pi session · affects subsequent provider requests."
|
|
24107
|
+
: "Session override cleared · model defaults apply.",
|
|
24108
|
+
});
|
|
24109
|
+
}
|
|
24110
|
+
|
|
24111
|
+
async function resetSamplingParameters() {
|
|
24112
|
+
if (!activeTabId || samplingParametersBusy) return;
|
|
24113
|
+
if (!samplingParametersState || samplingParametersStateTabId !== activeTabId) {
|
|
24114
|
+
setSamplingParametersFeedback({ error: "Wait for this tab's sampling parameters to load before resetting them." });
|
|
24115
|
+
renderSamplingParameters();
|
|
24116
|
+
return;
|
|
24117
|
+
}
|
|
24118
|
+
await writeSamplingParameters({}, { successNotice: "Session override cleared · model defaults apply." });
|
|
24119
|
+
}
|
|
24120
|
+
|
|
24121
|
+
// Lazy loader for surfaces that reveal the section (side-panel expand/visibility,
|
|
24122
|
+
// mobile canonical mount) after the initial page load.
|
|
24123
|
+
function ensureSamplingParametersLoaded() {
|
|
24124
|
+
if (!activeTabId || samplingParametersLoading || samplingParametersBusy) return;
|
|
24125
|
+
if (samplingParametersState && samplingParametersStateTabId === activeTabId) return;
|
|
24126
|
+
loadSamplingParameters().catch(() => {});
|
|
24127
|
+
}
|
|
24128
|
+
|
|
24129
|
+
function initializeSamplingParameters() {
|
|
24130
|
+
initializeSamplingParameterControls();
|
|
24131
|
+
renderSamplingParameters();
|
|
24132
|
+
if (samplingParametersSectionActive()) ensureSamplingParametersLoaded();
|
|
24133
|
+
}
|
|
24134
|
+
|
|
22619
24135
|
function sessionCopyButton(label, value) {
|
|
22620
24136
|
const button = make("button", "session-copy-button", "Copy");
|
|
22621
24137
|
button.type = "button";
|
|
@@ -23072,10 +24588,10 @@ function liveTodoProgressWidgetLinesFromText(text, tabId = activeTabId) {
|
|
|
23072
24588
|
return lines;
|
|
23073
24589
|
}
|
|
23074
24590
|
|
|
23075
|
-
// Coalesce
|
|
23076
|
-
//
|
|
23077
|
-
//
|
|
23078
|
-
//
|
|
24591
|
+
// Coalesce widget rebuilds to one per animation frame. Todo-progress records
|
|
24592
|
+
// are now derived only at authoritative message reconciliation, but several
|
|
24593
|
+
// semantic boundaries can land in the same frame, so the widget area must
|
|
24594
|
+
// still never be torn down/rebuilt more than once per frame.
|
|
23079
24595
|
function scheduleLiveWidgetRender() {
|
|
23080
24596
|
if (liveWidgetRenderFrame !== null) return;
|
|
23081
24597
|
const flush = () => {
|
|
@@ -23086,20 +24602,25 @@ function scheduleLiveWidgetRender() {
|
|
|
23086
24602
|
else liveWidgetRenderFrame = setTimeout(flush, 0);
|
|
23087
24603
|
}
|
|
23088
24604
|
|
|
23089
|
-
|
|
23090
|
-
|
|
23091
|
-
|
|
23092
|
-
|
|
23093
|
-
|
|
23094
|
-
|
|
23095
|
-
const
|
|
23096
|
-
|
|
23097
|
-
|
|
23098
|
-
|
|
23099
|
-
|
|
23100
|
-
|
|
23101
|
-
|
|
23102
|
-
|
|
24605
|
+
// Authoritative source for the todo-progress record: the settled assistant
|
|
24606
|
+
// text that message reconciliation just fetched. Raw stream tokens never
|
|
24607
|
+
// reach this path, so widget records change at most once per reconciliation
|
|
24608
|
+
// and only when the parsed checklist value actually differs.
|
|
24609
|
+
function authoritativeTodoProgressSourceText(messages = latestMessages) {
|
|
24610
|
+
for (let index = (messages?.length || 0) - 1; index >= 0; index -= 1) {
|
|
24611
|
+
const message = messages[index];
|
|
24612
|
+
if (message?.role !== "assistant") continue;
|
|
24613
|
+
const text = textFromContent(message.content);
|
|
24614
|
+
if (String(text || "").trim()) return text;
|
|
24615
|
+
}
|
|
24616
|
+
return "";
|
|
24617
|
+
}
|
|
24618
|
+
|
|
24619
|
+
function reconcileTodoProgressFromMessages(messages = latestMessages, tabId = activeTabId) {
|
|
24620
|
+
if (!tabId) return false;
|
|
24621
|
+
const text = authoritativeTodoProgressSourceText(messages);
|
|
24622
|
+
if (!text) return false;
|
|
24623
|
+
return syncLiveTodoProgressWidgetFromText(text, tabId);
|
|
23103
24624
|
}
|
|
23104
24625
|
|
|
23105
24626
|
function syncLiveTodoProgressWidgetFromText(text, tabId = activeTabId) {
|
|
@@ -23109,7 +24630,7 @@ function syncLiveTodoProgressWidgetFromText(text, tabId = activeTabId) {
|
|
|
23109
24630
|
if (tabId && todoProgressSignatureByTab.get(tabId) === signature) return false;
|
|
23110
24631
|
// liveTodoProgressWidgetLinesFromText already short-circuits unless the
|
|
23111
24632
|
// feature is enabled, so detection is settled here. Do NOT run
|
|
23112
|
-
// updateOptionalFeatureAvailability()
|
|
24633
|
+
// updateOptionalFeatureAvailability() from this path: it triggers git-footer
|
|
23113
24634
|
// payload reconciliation and a full optional-feature control rebuild.
|
|
23114
24635
|
// Availability is reconciled on command/state refreshes and RPC widget
|
|
23115
24636
|
// updates instead, keeping streaming output decoupled from chrome UI.
|
|
@@ -23480,6 +25001,7 @@ function renderAurReviewWidget() {
|
|
|
23480
25001
|
if (!isOptionalFeatureEnabled("aurReview")) return null;
|
|
23481
25002
|
const payload = parseAurReviewPayload(getWidgetLines(AUR_REVIEW_RPC_WIDGET_KEY));
|
|
23482
25003
|
if (!payload || payload.decision.state === "closed") return null;
|
|
25004
|
+
if (payload.origin === "guided-git" && payload.scope === "staged" && payload.decision.state === "approved") return null;
|
|
23483
25005
|
|
|
23484
25006
|
const node = make("section", "widget aur-review-widget");
|
|
23485
25007
|
node.setAttribute("aria-label", "Manual repository review");
|
|
@@ -27556,10 +29078,11 @@ function renderGitWorkflow() {
|
|
|
27556
29078
|
elements.gitWorkflowSteps.replaceChildren();
|
|
27557
29079
|
elements.gitWorkflowActions.replaceChildren();
|
|
27558
29080
|
|
|
27559
|
-
|
|
27560
|
-
//
|
|
27561
|
-
//
|
|
27562
|
-
const reviewStepAvailable =
|
|
29081
|
+
const preferences = gitWorkflow.preferences || gitWorkflowPreferences || {};
|
|
29082
|
+
// The saved option controls new workflows, while an already-required review
|
|
29083
|
+
// remains visible and fail-closed if setup or extension availability changes.
|
|
29084
|
+
const reviewStepAvailable = (preferences.reviewProcessEnabled !== false && guidedGitReviewAvailable(activeTabId))
|
|
29085
|
+
|| gitWorkflow.guidedReviewRequired === true;
|
|
27563
29086
|
const standardProcesses = reviewStepAvailable ? GIT_WORKFLOW_PROCESSES : GIT_WORKFLOW_PROCESSES.filter((process) => process.value !== "review");
|
|
27564
29087
|
const processes = gitWorkflow.mode === "initRepo" ? GIT_INIT_WORKFLOW_PROCESSES : standardProcesses;
|
|
27565
29088
|
const activeIndexMap = gitWorkflow.mode === "initRepo" ? GIT_INIT_WORKFLOW_ACTIVE_INDEX : GIT_WORKFLOW_ACTIVE_INDEX;
|
|
@@ -27586,7 +29109,6 @@ function renderGitWorkflow() {
|
|
|
27586
29109
|
return;
|
|
27587
29110
|
}
|
|
27588
29111
|
|
|
27589
|
-
const preferences = gitWorkflow.preferences || gitWorkflowPreferences || {};
|
|
27590
29112
|
if (gitWorkflow.step === "add") {
|
|
27591
29113
|
if (preferences.stagingPolicy === "all") {
|
|
27592
29114
|
addGitWorkflowAction("Run git add .", () => runGitAdd(), "primary", false);
|
|
@@ -27968,10 +29490,9 @@ async function startGitWorkflow(tabId = activeTabId, { skipSetup = false } = {})
|
|
|
27968
29490
|
pr: null,
|
|
27969
29491
|
prRequestedAt: 0,
|
|
27970
29492
|
...resetGuidedGitReviewPatch({ retainDeclinedStagedContentHash: false }),
|
|
27971
|
-
//
|
|
27972
|
-
//
|
|
27973
|
-
|
|
27974
|
-
guidedReviewRequired: guidedGitReviewAvailable(tabId),
|
|
29493
|
+
// The saved option and current capability decide whether a new flow requires
|
|
29494
|
+
// review; once required, later setup or extension changes cannot bypass it.
|
|
29495
|
+
guidedReviewRequired: preferences.reviewProcessEnabled !== false && guidedGitReviewAvailable(tabId),
|
|
27975
29496
|
preferences,
|
|
27976
29497
|
verificationConfirmed: false,
|
|
27977
29498
|
}, { tabId });
|
|
@@ -28303,7 +29824,7 @@ async function runGitAdd(tabId = gitWorkflowActionTabId()) {
|
|
|
28303
29824
|
const result = await gitWorkflowRequest("/api/git-workflow/add", { runId, tabId });
|
|
28304
29825
|
if (!result) return;
|
|
28305
29826
|
const output = `${formatGitCommandResult(result)}\n\nStaged.`;
|
|
28306
|
-
if (guidedGitReviewAvailable(tabId) || workflow.guidedReviewRequired === true) {
|
|
29827
|
+
if ((workflow.preferences?.reviewProcessEnabled !== false && guidedGitReviewAvailable(tabId)) || workflow.guidedReviewRequired === true) {
|
|
28307
29828
|
// A required gate never falls through to the legacy message flow just
|
|
28308
29829
|
// because its extension was disabled or disappeared after staging.
|
|
28309
29830
|
await requestGuidedGitReview(tabId, { output });
|
|
@@ -28327,7 +29848,7 @@ async function acceptCurrentGitStaging(tabId = gitWorkflowActionTabId()) {
|
|
|
28327
29848
|
const staged = Number(response.data?.summary?.staged || 0);
|
|
28328
29849
|
if (staged <= 0) throw new Error("No staged files are available. Use Review/select changes to stage the intended files first.");
|
|
28329
29850
|
const output = `Using the current staged set (${staged} file${staged === 1 ? "" : "s"}).`;
|
|
28330
|
-
if (guidedGitReviewAvailable(tabId) || workflow.guidedReviewRequired === true) {
|
|
29851
|
+
if ((workflow.preferences?.reviewProcessEnabled !== false && guidedGitReviewAvailable(tabId)) || workflow.guidedReviewRequired === true) {
|
|
28331
29852
|
await requestGuidedGitReview(tabId, { output });
|
|
28332
29853
|
} else {
|
|
28333
29854
|
setGitWorkflow({
|
|
@@ -32299,43 +33820,9 @@ function updateLiveToolCard(bubble, message) {
|
|
|
32299
33820
|
return true;
|
|
32300
33821
|
}
|
|
32301
33822
|
|
|
32302
|
-
function cancelQueuedLiveToolRunRender(toolCallId = "") {
|
|
32303
|
-
if (toolCallId) liveToolRenderQueue.delete(String(toolCallId));
|
|
32304
|
-
else liveToolRenderQueue.clear();
|
|
32305
|
-
if (liveToolRenderQueue.size === 0) {
|
|
32306
|
-
clearTimeout(liveToolRenderTimer);
|
|
32307
|
-
liveToolRenderTimer = null;
|
|
32308
|
-
}
|
|
32309
|
-
}
|
|
32310
|
-
|
|
32311
|
-
function clearLiveToolRenderQueue() {
|
|
32312
|
-
cancelQueuedLiveToolRunRender();
|
|
32313
|
-
}
|
|
32314
|
-
|
|
32315
|
-
function flushLiveToolRunRenderQueue() {
|
|
32316
|
-
const entries = Array.from(liveToolRenderQueue.values());
|
|
32317
|
-
clearLiveToolRenderQueue();
|
|
32318
|
-
for (const entry of entries) renderLiveToolRun(entry.run, { scroll: entry.scroll });
|
|
32319
|
-
}
|
|
32320
|
-
|
|
32321
|
-
function scheduleLiveToolRunRender(run, { scroll = false } = {}) {
|
|
32322
|
-
if (!run?.toolCallId) return;
|
|
32323
|
-
const id = String(run.toolCallId);
|
|
32324
|
-
const existing = liveToolRenderQueue.get(id);
|
|
32325
|
-
liveToolRenderQueue.set(id, { run, scroll: !!(existing?.scroll || scroll) });
|
|
32326
|
-
if (liveToolRenderTimer) return;
|
|
32327
|
-
liveToolRenderTimer = setTimeout(() => {
|
|
32328
|
-
liveToolRenderTimer = null;
|
|
32329
|
-
const flush = () => flushLiveToolRunRenderQueue();
|
|
32330
|
-
if (typeof requestAnimationFrame === "function") requestAnimationFrame(flush);
|
|
32331
|
-
else flush();
|
|
32332
|
-
}, TOOL_LIVE_UPDATE_THROTTLE_MS);
|
|
32333
|
-
}
|
|
32334
|
-
|
|
32335
33823
|
function renderLiveToolRun(run, { scroll = true } = {}) {
|
|
32336
33824
|
if (!run?.toolCallId) return;
|
|
32337
33825
|
const id = String(run.toolCallId);
|
|
32338
|
-
cancelQueuedLiveToolRunRender(id);
|
|
32339
33826
|
const existing = liveToolCards.get(id);
|
|
32340
33827
|
const existingConnected = !!(existing?.isConnected && existing.parentElement === elements.chat);
|
|
32341
33828
|
const shouldFollow = scroll && (autoFollowChat || isChatNearBottom());
|
|
@@ -32385,10 +33872,10 @@ function handleToolExecutionStart(event) {
|
|
|
32385
33872
|
if (run) renderLiveToolRun(run);
|
|
32386
33873
|
}
|
|
32387
33874
|
|
|
32388
|
-
function
|
|
33875
|
+
function applyTranscriptToolExecutionUpdate(event) {
|
|
32389
33876
|
const result = { ...(event.partialResult || {}), isError: false };
|
|
32390
33877
|
const run = upsertLiveToolRun(event, { result, isPartial: true, isError: false });
|
|
32391
|
-
if (run)
|
|
33878
|
+
if (run) renderLiveToolRun(run, { scroll: false });
|
|
32392
33879
|
}
|
|
32393
33880
|
|
|
32394
33881
|
function handleToolExecutionEnd(event) {
|
|
@@ -32729,7 +34216,11 @@ function runIndicatorDetail() {
|
|
|
32729
34216
|
return "Waiting for output or action…";
|
|
32730
34217
|
}
|
|
32731
34218
|
|
|
34219
|
+
// Transcript-owned ticker: it may only repaint the run-indicator bubble's own
|
|
34220
|
+
// stable text nodes. Canonical state reconciliation belongs to the separate
|
|
34221
|
+
// lifecycle watchdog below, so transcript rendering never issues network work.
|
|
32732
34222
|
function startRunIndicatorTicker() {
|
|
34223
|
+
startLifecycleStateWatchdog();
|
|
32733
34224
|
if (runIndicatorTimer) return;
|
|
32734
34225
|
runIndicatorTimer = setInterval(() => {
|
|
32735
34226
|
if (!runIndicatorIsActive()) {
|
|
@@ -32737,17 +34228,39 @@ function startRunIndicatorTicker() {
|
|
|
32737
34228
|
return;
|
|
32738
34229
|
}
|
|
32739
34230
|
updateRunIndicatorBubble();
|
|
32740
|
-
maybeRefreshRunIndicatorState();
|
|
32741
34231
|
}, RUN_INDICATOR_TICK_MS);
|
|
32742
34232
|
}
|
|
32743
34233
|
|
|
32744
34234
|
function stopRunIndicatorTicker() {
|
|
32745
34235
|
clearInterval(runIndicatorTimer);
|
|
32746
34236
|
runIndicatorTimer = null;
|
|
34237
|
+
stopLifecycleStateWatchdog();
|
|
34238
|
+
}
|
|
34239
|
+
|
|
34240
|
+
// Lifecycle-owned watchdog. It runs while a run is active and performs the
|
|
34241
|
+
// bounded canonical state recheck that keeps Stop/idle honest when a terminal
|
|
34242
|
+
// lifecycle event is dropped. It is time-driven, never output/token-driven.
|
|
34243
|
+
function startLifecycleStateWatchdog() {
|
|
34244
|
+
if (lifecycleStateWatchdogTimer) return;
|
|
34245
|
+
lifecycleStateWatchdogTimer = setInterval(() => {
|
|
34246
|
+
if (!runIndicatorIsActive()) {
|
|
34247
|
+
stopLifecycleStateWatchdog();
|
|
34248
|
+
return;
|
|
34249
|
+
}
|
|
34250
|
+
maybeRefreshRunIndicatorState();
|
|
34251
|
+
}, RUN_INDICATOR_STATE_RECHECK_MS);
|
|
34252
|
+
}
|
|
34253
|
+
|
|
34254
|
+
function stopLifecycleStateWatchdog() {
|
|
34255
|
+
clearInterval(lifecycleStateWatchdogTimer);
|
|
34256
|
+
lifecycleStateWatchdogTimer = null;
|
|
32747
34257
|
}
|
|
32748
34258
|
|
|
32749
34259
|
function createRunIndicatorBubble() {
|
|
32750
34260
|
runIndicatorBubble = make("article", "message runIndicator run-indicator-message streaming");
|
|
34261
|
+
// Stable transcript-owned activity root: streaming activity updates rewrite
|
|
34262
|
+
// only this bubble's own text nodes, never composer or chrome surfaces.
|
|
34263
|
+
runIndicatorBubble.dataset.streamOwned = "run-indicator";
|
|
32751
34264
|
runIndicatorBubble.setAttribute("aria-live", "polite");
|
|
32752
34265
|
runIndicatorBubble.setAttribute("aria-label", "Agent is running:");
|
|
32753
34266
|
|
|
@@ -32824,10 +34337,31 @@ function setRunIndicatorActivity(activity, { active = true, scroll = true } = {}
|
|
|
32824
34337
|
const needsRender = scroll || !hadRunIndicatorBubble || wasLocallyActive !== runIndicatorLocallyActive || previousActivity !== runIndicatorActivity;
|
|
32825
34338
|
if (needsRender) scheduleRunIndicatorRender({ scroll });
|
|
32826
34339
|
else if (runIndicatorIsActive()) startRunIndicatorTicker();
|
|
32827
|
-
|
|
34340
|
+
// Activity wording is transcript-owned. Composer/Stop chrome is reconciled
|
|
34341
|
+
// only when the lifecycle enum itself changes, so wording updates can never
|
|
34342
|
+
// reparent Steer/Follow-up controls or rewrite the run-active body class.
|
|
34343
|
+
syncLifecycleComposerState();
|
|
32828
34344
|
if (active) scheduleRunIndicatorGraceCheck();
|
|
32829
34345
|
}
|
|
32830
34346
|
|
|
34347
|
+
function currentLifecycleComposerSignature() {
|
|
34348
|
+
return [
|
|
34349
|
+
activeTabGeneration,
|
|
34350
|
+
isRunActive() ? "run" : "idle",
|
|
34351
|
+
isAbortAvailable() ? "abort" : "no-abort",
|
|
34352
|
+
abortRequestInFlight ? "aborting" : "ready",
|
|
34353
|
+
busyPromptBehavior,
|
|
34354
|
+
].join("|");
|
|
34355
|
+
}
|
|
34356
|
+
|
|
34357
|
+
function syncLifecycleComposerState({ force = false } = {}) {
|
|
34358
|
+
const signature = currentLifecycleComposerSignature();
|
|
34359
|
+
if (!force && signature === lifecycleComposerSignature) return false;
|
|
34360
|
+
lifecycleComposerSignature = signature;
|
|
34361
|
+
scheduleComposerModeButtonsUpdate();
|
|
34362
|
+
return true;
|
|
34363
|
+
}
|
|
34364
|
+
|
|
32831
34365
|
function clearRunIndicatorActivity({ render = true, deferRemoval = false } = {}) {
|
|
32832
34366
|
clearRunIndicatorGraceCheck();
|
|
32833
34367
|
runIndicatorLastStateCheckAt = 0;
|
|
@@ -32837,6 +34371,8 @@ function clearRunIndicatorActivity({ render = true, deferRemoval = false } = {})
|
|
|
32837
34371
|
runIndicatorRemovalDeferred = deferRemoval && runIndicatorBubble?.parentElement === elements.chat;
|
|
32838
34372
|
if (runIndicatorRemovalDeferred) stopRunIndicatorTicker();
|
|
32839
34373
|
else if (render) renderRunIndicator();
|
|
34374
|
+
stopLifecycleStateWatchdog();
|
|
34375
|
+
lifecycleComposerSignature = currentLifecycleComposerSignature();
|
|
32840
34376
|
updateComposerModeButtons();
|
|
32841
34377
|
}
|
|
32842
34378
|
|
|
@@ -32862,6 +34398,7 @@ function syncRunIndicatorFromState(state = currentState) {
|
|
|
32862
34398
|
} else {
|
|
32863
34399
|
renderRunIndicator();
|
|
32864
34400
|
}
|
|
34401
|
+
lifecycleComposerSignature = currentLifecycleComposerSignature();
|
|
32865
34402
|
updateComposerModeButtons();
|
|
32866
34403
|
}
|
|
32867
34404
|
|
|
@@ -33618,6 +35155,7 @@ function clearChatTouchIntent() {
|
|
|
33618
35155
|
|
|
33619
35156
|
function isChatScrollAwayIntent(event) {
|
|
33620
35157
|
if (event?.type === "wheel") return event.deltaY < 0;
|
|
35158
|
+
if (event?.type === "middle-drag") return event.deltaY > 0;
|
|
33621
35159
|
if (event?.type === "touchmove") {
|
|
33622
35160
|
const clientY = Number(event?.touches?.[0]?.clientY);
|
|
33623
35161
|
const scrollAway = !Number.isFinite(clientY) || chatLastTouchClientY === null || clientY > chatLastTouchClientY;
|
|
@@ -33814,10 +35352,285 @@ function setOptionsMenuOpen(open) {
|
|
|
33814
35352
|
elements.optionsMenuButton.setAttribute("aria-expanded", optionsMenuOpen ? "true" : "false");
|
|
33815
35353
|
elements.optionsMenuButton.classList.toggle("menu-open", optionsMenuOpen);
|
|
33816
35354
|
elements.optionsMenuButton.parentElement?.classList.toggle("open", optionsMenuOpen);
|
|
35355
|
+
if (optionsMenuOpen) syncOptionsSubmenuAvailability();
|
|
35356
|
+
else closeOptionsSubmenus();
|
|
35357
|
+
if (optionsMenuOpen) scheduleOptionsMenuLabelFit();
|
|
33817
35358
|
scheduleMobileDropdownScrollBoundsUpdate();
|
|
33818
35359
|
if (!optionsMenuOpen) scheduleDeferredUiFlushAfterDropdownClose();
|
|
33819
35360
|
}
|
|
33820
35361
|
|
|
35362
|
+
function optionsSubmenuGroups() {
|
|
35363
|
+
if (!elements.optionsMenu) return [];
|
|
35364
|
+
return Array.from(elements.optionsMenu.querySelectorAll(OPTIONS_SUBMENU_GROUP_SELECTOR));
|
|
35365
|
+
}
|
|
35366
|
+
|
|
35367
|
+
function optionsSubmenuTrigger(group) {
|
|
35368
|
+
if (!group?.querySelector) return null;
|
|
35369
|
+
return group.querySelector(OPTIONS_SUBMENU_TRIGGER_SELECTOR) || group.querySelector('button[aria-haspopup="menu"]');
|
|
35370
|
+
}
|
|
35371
|
+
|
|
35372
|
+
function optionsSubmenuPanel(group) {
|
|
35373
|
+
if (!group?.querySelector) return null;
|
|
35374
|
+
const controlledId = optionsSubmenuTrigger(group)?.getAttribute("aria-controls");
|
|
35375
|
+
const controlled = controlledId ? document.getElementById(controlledId) : null;
|
|
35376
|
+
if (controlled) return controlled;
|
|
35377
|
+
return group.querySelector(OPTIONS_SUBMENU_PANEL_SELECTOR) || group.querySelector('[role="menu"]');
|
|
35378
|
+
}
|
|
35379
|
+
|
|
35380
|
+
function optionsSubmenuBackButton(group) {
|
|
35381
|
+
return optionsSubmenuPanel(group)?.querySelector(OPTIONS_SUBMENU_BACK_SELECTOR) || null;
|
|
35382
|
+
}
|
|
35383
|
+
|
|
35384
|
+
function isOptionsSubmenuPanelItem(item) {
|
|
35385
|
+
const panel = item?.closest?.(OPTIONS_SUBMENU_PANEL_SELECTOR);
|
|
35386
|
+
return !!panel && !!elements.optionsMenu?.contains(panel);
|
|
35387
|
+
}
|
|
35388
|
+
|
|
35389
|
+
function isVisibleOptionsMenuItem(item) {
|
|
35390
|
+
if (!item || item.hidden || item.disabled) return false;
|
|
35391
|
+
if (item.getAttribute?.("aria-hidden") === "true") return false;
|
|
35392
|
+
return !item.closest?.("[hidden]");
|
|
35393
|
+
}
|
|
35394
|
+
|
|
35395
|
+
function optionsSubmenuActionItems(group) {
|
|
35396
|
+
const panel = optionsSubmenuPanel(group);
|
|
35397
|
+
if (!panel) return [];
|
|
35398
|
+
const back = optionsSubmenuBackButton(group);
|
|
35399
|
+
return Array.from(panel.querySelectorAll('[role="menuitem"]')).filter((item) => item !== back);
|
|
35400
|
+
}
|
|
35401
|
+
|
|
35402
|
+
function optionsSubmenuHasVisibleActions(group) {
|
|
35403
|
+
return optionsSubmenuActionItems(group).some((item) => !item.hidden && !item.disabled && item.getAttribute("aria-hidden") !== "true");
|
|
35404
|
+
}
|
|
35405
|
+
|
|
35406
|
+
function optionsSubmenuItems(group) {
|
|
35407
|
+
const panel = optionsSubmenuPanel(group);
|
|
35408
|
+
if (!panel) return [];
|
|
35409
|
+
const back = optionsSubmenuBackButton(group);
|
|
35410
|
+
return Array.from(panel.querySelectorAll('[role="menuitem"]')).filter((item) => item !== back && !item.hidden && !item.disabled && item.getAttribute("aria-hidden") !== "true");
|
|
35411
|
+
}
|
|
35412
|
+
|
|
35413
|
+
function optionsMenuRootItems() {
|
|
35414
|
+
if (!elements.optionsMenu) return [];
|
|
35415
|
+
return Array.from(elements.optionsMenu.querySelectorAll('[role="menuitem"]'))
|
|
35416
|
+
.filter((item) => !isOptionsSubmenuPanelItem(item) && isVisibleOptionsMenuItem(item));
|
|
35417
|
+
}
|
|
35418
|
+
|
|
35419
|
+
function focusOptionsMenuItem(item) {
|
|
35420
|
+
item?.focus?.({ preventScroll: true });
|
|
35421
|
+
}
|
|
35422
|
+
|
|
35423
|
+
function optionsSubmenuUsesDrillIn() {
|
|
35424
|
+
if (isMobileView()) return true;
|
|
35425
|
+
return window.matchMedia?.(OPTIONS_SUBMENU_DRILL_IN_QUERY)?.matches === true;
|
|
35426
|
+
}
|
|
35427
|
+
|
|
35428
|
+
function syncOptionsSubmenuAvailability() {
|
|
35429
|
+
if (optionsSubmenuSyncing) return;
|
|
35430
|
+
optionsSubmenuSyncing = true;
|
|
35431
|
+
try {
|
|
35432
|
+
for (const group of optionsSubmenuGroups()) {
|
|
35433
|
+
const available = optionsSubmenuHasVisibleActions(group);
|
|
35434
|
+
const unavailable = !available;
|
|
35435
|
+
const trigger = optionsSubmenuTrigger(group);
|
|
35436
|
+
if (group.hidden !== unavailable) group.hidden = unavailable;
|
|
35437
|
+
if (trigger) {
|
|
35438
|
+
if (trigger.hidden !== unavailable) trigger.hidden = unavailable;
|
|
35439
|
+
if (trigger.disabled !== unavailable) trigger.disabled = unavailable;
|
|
35440
|
+
}
|
|
35441
|
+
if (!available && openOptionsSubmenuGroup === group) setOptionsSubmenuOpen(group, false);
|
|
35442
|
+
}
|
|
35443
|
+
} finally {
|
|
35444
|
+
optionsSubmenuSyncing = false;
|
|
35445
|
+
}
|
|
35446
|
+
}
|
|
35447
|
+
|
|
35448
|
+
function fitOptionsMenuLabels() {
|
|
35449
|
+
if (!elements.optionsMenu) return;
|
|
35450
|
+
const labels = elements.optionsMenu.querySelectorAll(OPTIONS_MENU_LABEL_SELECTOR);
|
|
35451
|
+
for (const label of labels) {
|
|
35452
|
+
label.style.removeProperty(OPTIONS_MENU_LABEL_FONT_SIZE_PROPERTY);
|
|
35453
|
+
label.removeAttribute("data-options-menu-label-fitted");
|
|
35454
|
+
const availableWidth = label.clientWidth;
|
|
35455
|
+
const requiredWidth = label.scrollWidth;
|
|
35456
|
+
if (availableWidth <= 0 || requiredWidth <= availableWidth + 0.5) continue;
|
|
35457
|
+
const baseFontSize = Number.parseFloat(window.getComputedStyle(label).fontSize);
|
|
35458
|
+
if (!Number.isFinite(baseFontSize) || baseFontSize <= 0) continue;
|
|
35459
|
+
const fittedFontSize = Math.max(
|
|
35460
|
+
OPTIONS_MENU_LABEL_MIN_FONT_SIZE_PX,
|
|
35461
|
+
Math.floor(baseFontSize * (availableWidth / requiredWidth) * 98) / 100,
|
|
35462
|
+
);
|
|
35463
|
+
if (fittedFontSize >= baseFontSize) continue;
|
|
35464
|
+
label.style.setProperty(OPTIONS_MENU_LABEL_FONT_SIZE_PROPERTY, `${fittedFontSize}px`);
|
|
35465
|
+
label.setAttribute("data-options-menu-label-fitted", "");
|
|
35466
|
+
}
|
|
35467
|
+
}
|
|
35468
|
+
|
|
35469
|
+
function scheduleOptionsMenuLabelFit() {
|
|
35470
|
+
if (!elements.optionsMenu) return;
|
|
35471
|
+
if (optionsMenuLabelFitFrame) window.cancelAnimationFrame(optionsMenuLabelFitFrame);
|
|
35472
|
+
optionsMenuLabelFitFrame = window.requestAnimationFrame(() => {
|
|
35473
|
+
optionsMenuLabelFitFrame = 0;
|
|
35474
|
+
fitOptionsMenuLabels();
|
|
35475
|
+
});
|
|
35476
|
+
}
|
|
35477
|
+
|
|
35478
|
+
function updateOptionsSubmenuPlacement(group) {
|
|
35479
|
+
const panel = optionsSubmenuPanel(group);
|
|
35480
|
+
if (!group || !panel) return;
|
|
35481
|
+
if (optionsSubmenuUsesDrillIn()) {
|
|
35482
|
+
group.classList.remove(OPTIONS_SUBMENU_LEFT_CLASS);
|
|
35483
|
+
panel.classList.remove(OPTIONS_SUBMENU_LEFT_CLASS);
|
|
35484
|
+
return;
|
|
35485
|
+
}
|
|
35486
|
+
const anchorRect = (optionsSubmenuTrigger(group) || group).getBoundingClientRect?.();
|
|
35487
|
+
if (!anchorRect) return;
|
|
35488
|
+
const viewportWidth = window.innerWidth || document.documentElement.clientWidth || 0;
|
|
35489
|
+
const panelWidth = panel.offsetWidth || panel.getBoundingClientRect?.().width || 0;
|
|
35490
|
+
const spaceRight = viewportWidth - anchorRect.right;
|
|
35491
|
+
const flipLeft = panelWidth > 0 && spaceRight < panelWidth && anchorRect.left > spaceRight;
|
|
35492
|
+
group.classList.toggle(OPTIONS_SUBMENU_LEFT_CLASS, flipLeft);
|
|
35493
|
+
panel.classList.toggle(OPTIONS_SUBMENU_LEFT_CLASS, flipLeft);
|
|
35494
|
+
}
|
|
35495
|
+
|
|
35496
|
+
function setOptionsSubmenuOpen(group, open, { focusFirstItem = false, restoreFocus = false } = {}) {
|
|
35497
|
+
if (!group) return;
|
|
35498
|
+
const trigger = optionsSubmenuTrigger(group);
|
|
35499
|
+
const panel = optionsSubmenuPanel(group);
|
|
35500
|
+
const shouldOpen = !!open && !trigger?.disabled && !trigger?.hidden && !group.hidden;
|
|
35501
|
+
if (shouldOpen) {
|
|
35502
|
+
for (const sibling of optionsSubmenuGroups()) {
|
|
35503
|
+
if (sibling !== group) setOptionsSubmenuOpen(sibling, false);
|
|
35504
|
+
}
|
|
35505
|
+
}
|
|
35506
|
+
if (shouldOpen) openOptionsSubmenuGroup = group;
|
|
35507
|
+
else if (openOptionsSubmenuGroup === group) openOptionsSubmenuGroup = null;
|
|
35508
|
+
group.classList.toggle("open", shouldOpen);
|
|
35509
|
+
trigger?.setAttribute("aria-expanded", shouldOpen ? "true" : "false");
|
|
35510
|
+
trigger?.classList.toggle("menu-open", shouldOpen);
|
|
35511
|
+
if (panel) panel.hidden = !shouldOpen;
|
|
35512
|
+
if (elements.optionsMenu) {
|
|
35513
|
+
elements.optionsMenu.classList.toggle("submenu-open", !!openOptionsSubmenuGroup);
|
|
35514
|
+
const openGroupId = openOptionsSubmenuGroup?.dataset?.optionsSubmenu || "";
|
|
35515
|
+
if (openGroupId) elements.optionsMenu.dataset.openGroup = openGroupId;
|
|
35516
|
+
else delete elements.optionsMenu.dataset.openGroup;
|
|
35517
|
+
}
|
|
35518
|
+
if (shouldOpen) updateOptionsSubmenuPlacement(group);
|
|
35519
|
+
else {
|
|
35520
|
+
group.classList.remove(OPTIONS_SUBMENU_LEFT_CLASS);
|
|
35521
|
+
panel?.classList.remove(OPTIONS_SUBMENU_LEFT_CLASS);
|
|
35522
|
+
}
|
|
35523
|
+
if (shouldOpen && focusFirstItem) focusOptionsMenuItem(optionsSubmenuItems(group)[0]);
|
|
35524
|
+
if (!shouldOpen && restoreFocus) focusOptionsMenuItem(trigger);
|
|
35525
|
+
if (shouldOpen) scheduleOptionsMenuLabelFit();
|
|
35526
|
+
scheduleMobileDropdownScrollBoundsUpdate();
|
|
35527
|
+
}
|
|
35528
|
+
|
|
35529
|
+
function closeOptionsSubmenus({ restoreFocus = false } = {}) {
|
|
35530
|
+
const previous = openOptionsSubmenuGroup;
|
|
35531
|
+
for (const group of optionsSubmenuGroups()) setOptionsSubmenuOpen(group, false);
|
|
35532
|
+
openOptionsSubmenuGroup = null;
|
|
35533
|
+
if (restoreFocus && previous) focusOptionsMenuItem(optionsSubmenuTrigger(previous));
|
|
35534
|
+
}
|
|
35535
|
+
|
|
35536
|
+
function moveOptionsMenuFocus(items, currentIndex, offset) {
|
|
35537
|
+
if (!items.length) return;
|
|
35538
|
+
const nextIndex = currentIndex < 0
|
|
35539
|
+
? (offset > 0 ? 0 : items.length - 1)
|
|
35540
|
+
: (currentIndex + offset + items.length) % items.length;
|
|
35541
|
+
focusOptionsMenuItem(items[nextIndex]);
|
|
35542
|
+
}
|
|
35543
|
+
|
|
35544
|
+
function handleOptionsMenuKeydown(event) {
|
|
35545
|
+
const target = event.target;
|
|
35546
|
+
if (!target?.closest || !elements.optionsMenu?.contains(target)) return;
|
|
35547
|
+
const panelGroup = isOptionsSubmenuPanelItem(target) ? target.closest(OPTIONS_SUBMENU_GROUP_SELECTOR) : null;
|
|
35548
|
+
const items = panelGroup ? optionsSubmenuItems(panelGroup) : optionsMenuRootItems();
|
|
35549
|
+
const index = items.indexOf(target);
|
|
35550
|
+
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
|
|
35551
|
+
event.preventDefault();
|
|
35552
|
+
moveOptionsMenuFocus(items, index, event.key === "ArrowDown" ? 1 : -1);
|
|
35553
|
+
return;
|
|
35554
|
+
}
|
|
35555
|
+
if (event.key === "Home" || event.key === "End") {
|
|
35556
|
+
event.preventDefault();
|
|
35557
|
+
focusOptionsMenuItem(event.key === "Home" ? items[0] : items[items.length - 1]);
|
|
35558
|
+
return;
|
|
35559
|
+
}
|
|
35560
|
+
if (event.key === "ArrowRight") {
|
|
35561
|
+
const group = panelGroup ? null : target.closest(OPTIONS_SUBMENU_GROUP_SELECTOR);
|
|
35562
|
+
if (group && optionsSubmenuTrigger(group) === target) {
|
|
35563
|
+
event.preventDefault();
|
|
35564
|
+
setOptionsSubmenuOpen(group, true, { focusFirstItem: true });
|
|
35565
|
+
}
|
|
35566
|
+
return;
|
|
35567
|
+
}
|
|
35568
|
+
if (event.key === "ArrowLeft") {
|
|
35569
|
+
if (!panelGroup) return;
|
|
35570
|
+
event.preventDefault();
|
|
35571
|
+
setOptionsSubmenuOpen(panelGroup, false, { restoreFocus: true });
|
|
35572
|
+
return;
|
|
35573
|
+
}
|
|
35574
|
+
if (event.key !== "Escape") return;
|
|
35575
|
+
if (panelGroup || openOptionsSubmenuGroup) {
|
|
35576
|
+
// Escape closes only the deepest open level; the root menu stays open.
|
|
35577
|
+
event.preventDefault();
|
|
35578
|
+
event.stopPropagation();
|
|
35579
|
+
if (panelGroup) setOptionsSubmenuOpen(panelGroup, false, { restoreFocus: true });
|
|
35580
|
+
else closeOptionsSubmenus({ restoreFocus: true });
|
|
35581
|
+
return;
|
|
35582
|
+
}
|
|
35583
|
+
closeOptionsSubmenus();
|
|
35584
|
+
focusOptionsMenuItem(elements.optionsMenuButton);
|
|
35585
|
+
}
|
|
35586
|
+
|
|
35587
|
+
function handleOptionsSubmenuClick(event) {
|
|
35588
|
+
const back = event.target?.closest?.(OPTIONS_SUBMENU_BACK_SELECTOR);
|
|
35589
|
+
if (back && elements.optionsMenu?.contains(back)) {
|
|
35590
|
+
event.preventDefault();
|
|
35591
|
+
event.stopPropagation();
|
|
35592
|
+
setOptionsSubmenuOpen(back.closest(OPTIONS_SUBMENU_GROUP_SELECTOR), false, { restoreFocus: true });
|
|
35593
|
+
return;
|
|
35594
|
+
}
|
|
35595
|
+
const trigger = event.target?.closest?.(OPTIONS_SUBMENU_TRIGGER_SELECTOR);
|
|
35596
|
+
if (!trigger || !elements.optionsMenu?.contains(trigger)) return;
|
|
35597
|
+
event.preventDefault();
|
|
35598
|
+
event.stopPropagation();
|
|
35599
|
+
const group = trigger.closest(OPTIONS_SUBMENU_GROUP_SELECTOR);
|
|
35600
|
+
const shouldOpen = openOptionsSubmenuGroup !== group;
|
|
35601
|
+
setOptionsSubmenuOpen(group, shouldOpen, { focusFirstItem: shouldOpen });
|
|
35602
|
+
}
|
|
35603
|
+
|
|
35604
|
+
function initializeOptionsSubmenus() {
|
|
35605
|
+
const groups = optionsSubmenuGroups();
|
|
35606
|
+
if (!elements.optionsMenu || !groups.length) return;
|
|
35607
|
+
for (const group of groups) {
|
|
35608
|
+
group.addEventListener("pointerenter", (event) => {
|
|
35609
|
+
if (event.pointerType === "touch" || optionsSubmenuUsesDrillIn()) return;
|
|
35610
|
+
setOptionsSubmenuOpen(group, true);
|
|
35611
|
+
});
|
|
35612
|
+
group.addEventListener("pointerleave", (event) => {
|
|
35613
|
+
if (event.pointerType === "touch" || optionsSubmenuUsesDrillIn()) return;
|
|
35614
|
+
if (group.contains(document.activeElement)) return;
|
|
35615
|
+
setOptionsSubmenuOpen(group, false);
|
|
35616
|
+
});
|
|
35617
|
+
}
|
|
35618
|
+
const rootMenuContainer = elements.optionsMenu.parentElement;
|
|
35619
|
+
rootMenuContainer?.addEventListener("pointerenter", scheduleOptionsMenuLabelFit);
|
|
35620
|
+
rootMenuContainer?.addEventListener("focusin", scheduleOptionsMenuLabelFit);
|
|
35621
|
+
elements.optionsMenu.addEventListener("click", handleOptionsSubmenuClick);
|
|
35622
|
+
elements.optionsMenu.addEventListener("keydown", handleOptionsMenuKeydown);
|
|
35623
|
+
optionsSubmenuObserver?.disconnect();
|
|
35624
|
+
optionsSubmenuObserver = new MutationObserver(() => syncOptionsSubmenuAvailability());
|
|
35625
|
+
optionsSubmenuObserver.observe(elements.optionsMenu, { subtree: true, attributes: true, attributeFilter: ["hidden", "disabled", "aria-hidden"] });
|
|
35626
|
+
window.addEventListener("resize", () => {
|
|
35627
|
+
if (openOptionsSubmenuGroup) updateOptionsSubmenuPlacement(openOptionsSubmenuGroup);
|
|
35628
|
+
scheduleOptionsMenuLabelFit();
|
|
35629
|
+
});
|
|
35630
|
+
closeOptionsSubmenus();
|
|
35631
|
+
syncOptionsSubmenuAvailability();
|
|
35632
|
+
}
|
|
35633
|
+
|
|
33821
35634
|
function optionalFeatureIdForCommand(name) {
|
|
33822
35635
|
const baseName = commandBaseName(name);
|
|
33823
35636
|
if (OPTIONAL_COMMAND_FEATURES.has(baseName)) return OPTIONAL_COMMAND_FEATURES.get(baseName);
|
|
@@ -34162,8 +35975,10 @@ function applyOptionalFeatureProgressStates(snapshot) {
|
|
|
34162
35975
|
}
|
|
34163
35976
|
if (progress.restartDeferred === true) {
|
|
34164
35977
|
optionalFeatureRestartNotice = { autoRestarted: false, restartDeferred: true, tabId: activeTabId };
|
|
34165
|
-
} else if (progress.autoRestarted === true) {
|
|
35978
|
+
} else if (progress.autoRestarted === true && !optionalFeatureMigrationCompletionIsDismissed(snapshot)) {
|
|
34166
35979
|
optionalFeatureRestartNotice = { autoRestarted: true, restartDeferred: false, tabId: activeTabId };
|
|
35980
|
+
} else if (optionalFeatureMigrationCompletionIsDismissed(snapshot)) {
|
|
35981
|
+
optionalFeatureRestartNotice = null;
|
|
34167
35982
|
}
|
|
34168
35983
|
optionalFeatureBatchState = {
|
|
34169
35984
|
phase: progress.phase === "migrating" ? "running" : progress.phase === "partial" ? "failed" : "done",
|
|
@@ -34210,6 +36025,41 @@ function optionalFeatureReadyDismissKey(snapshot = optionalFeatureMigrationSnaps
|
|
|
34210
36025
|
return snapshot.phase === "ready" ? String(snapshot.revision || "pending") : "";
|
|
34211
36026
|
}
|
|
34212
36027
|
|
|
36028
|
+
function optionalFeatureMigrationCompletionKey(snapshot = optionalFeatureMigrationSnapshot) {
|
|
36029
|
+
if (snapshot.phase !== "complete") return "";
|
|
36030
|
+
const completedAt = String(snapshot.progress?.completedAt || snapshot.completedAt || "");
|
|
36031
|
+
return completedAt ? `${snapshot.revision || "pending"}:${completedAt}` : "";
|
|
36032
|
+
}
|
|
36033
|
+
|
|
36034
|
+
function storedDismissedOptionalFeatureMigrationKey() {
|
|
36035
|
+
try {
|
|
36036
|
+
return localStorage.getItem(OPTIONAL_FEATURE_MIGRATION_DISMISS_STORAGE_KEY) || "";
|
|
36037
|
+
} catch {
|
|
36038
|
+
return "";
|
|
36039
|
+
}
|
|
36040
|
+
}
|
|
36041
|
+
|
|
36042
|
+
function optionalFeatureMigrationCompletionIsDismissed(snapshot = optionalFeatureMigrationSnapshot) {
|
|
36043
|
+
const key = optionalFeatureMigrationCompletionKey(snapshot);
|
|
36044
|
+
return Boolean(key && (optionalFeatureMigrationDismissedCompletionKey === key || storedDismissedOptionalFeatureMigrationKey() === key));
|
|
36045
|
+
}
|
|
36046
|
+
|
|
36047
|
+
function rememberDismissedOptionalFeatureMigration(key) {
|
|
36048
|
+
if (!key) return;
|
|
36049
|
+
optionalFeatureMigrationDismissedCompletionKey = key;
|
|
36050
|
+
try {
|
|
36051
|
+
localStorage.setItem(OPTIONAL_FEATURE_MIGRATION_DISMISS_STORAGE_KEY, key);
|
|
36052
|
+
} catch {
|
|
36053
|
+
// Keep the dismissal page-local when browser storage is unavailable.
|
|
36054
|
+
}
|
|
36055
|
+
}
|
|
36056
|
+
|
|
36057
|
+
function dismissOptionalFeatureMigrationCompletion() {
|
|
36058
|
+
rememberDismissedOptionalFeatureMigration(optionalFeatureMigrationCompletionKey());
|
|
36059
|
+
optionalFeatureRestartNotice = null;
|
|
36060
|
+
renderOptionalFeatureMigrationSurface();
|
|
36061
|
+
}
|
|
36062
|
+
|
|
34213
36063
|
function scheduleOptionalFeatureReadyDismiss(key) {
|
|
34214
36064
|
if (!key) {
|
|
34215
36065
|
clearOptionalFeatureReadyDismissTimer();
|
|
@@ -34286,6 +36136,14 @@ function renderOptionalFeatureMigrationSurface() {
|
|
|
34286
36136
|
const progress = snapshot.progress;
|
|
34287
36137
|
const readyDismissKey = optionalFeatureReadyDismissKey(snapshot);
|
|
34288
36138
|
const readyCanAutoDismiss = Boolean(readyDismissKey && !optionalFeatureRestartNotice);
|
|
36139
|
+
if (optionalFeatureMigrationCompletionIsDismissed(snapshot)) {
|
|
36140
|
+
clearOptionalFeatureReadyDismissTimer();
|
|
36141
|
+
optionalFeatureRestartNotice = null;
|
|
36142
|
+
surface.replaceChildren();
|
|
36143
|
+
surface.hidden = true;
|
|
36144
|
+
ensureOptionalFeatureMigrationRenderTimer();
|
|
36145
|
+
return;
|
|
36146
|
+
}
|
|
34289
36147
|
if (readyCanAutoDismiss && optionalFeatureMigrationDismissedReadyKey === readyDismissKey) {
|
|
34290
36148
|
surface.replaceChildren();
|
|
34291
36149
|
surface.hidden = true;
|
|
@@ -34318,6 +36176,7 @@ function renderOptionalFeatureMigrationSurface() {
|
|
|
34318
36176
|
} else if (snapshot.phase === "complete") {
|
|
34319
36177
|
title.textContent = "Optional feature migration complete";
|
|
34320
36178
|
detail.textContent = optionalFeatureMigrationProgressText(progress) || `${summary.ready || 0} optional features ready`;
|
|
36179
|
+
if (!optionalFeatureRestartNotice) actions.append(optionalFeatureMigrationAction("Dismiss", dismissOptionalFeatureMigrationCompletion));
|
|
34321
36180
|
} else if (snapshot.phase === "action-required") {
|
|
34322
36181
|
title.textContent = conflicts.length ? "Optional feature conflicts were safely excluded" : "Previous optional features need migration";
|
|
34323
36182
|
detail.textContent = conflicts.length
|
|
@@ -34362,10 +36221,7 @@ function renderOptionalFeatureMigrationSurface() {
|
|
|
34362
36221
|
if (optionalFeatureRestartNotice.restartDeferred) {
|
|
34363
36222
|
notice.append(optionalFeatureMigrationAction("Restart tab", () => restartOptionalFeatureTab(), "primary"));
|
|
34364
36223
|
} else {
|
|
34365
|
-
notice.append(optionalFeatureMigrationAction("Dismiss",
|
|
34366
|
-
optionalFeatureRestartNotice = null;
|
|
34367
|
-
renderOptionalFeatureMigrationSurface();
|
|
34368
|
-
}));
|
|
36224
|
+
notice.append(optionalFeatureMigrationAction("Dismiss", dismissOptionalFeatureMigrationCompletion));
|
|
34369
36225
|
}
|
|
34370
36226
|
card.append(notice);
|
|
34371
36227
|
}
|
|
@@ -35495,19 +37351,108 @@ function sessionSummaryStateForTab(tabId = activeTabId) {
|
|
|
35495
37351
|
return normalized;
|
|
35496
37352
|
}
|
|
35497
37353
|
|
|
37354
|
+
function sessionSummaryControlStatus(tabId) {
|
|
37355
|
+
const state = sessionSummaryStateForTab(tabId);
|
|
37356
|
+
if (state?.status === "generating") return "Generating session summary…";
|
|
37357
|
+
if (state?.status === "failure") return `Session summary failed: ${state.message || "unknown error"}`;
|
|
37358
|
+
if (state?.summaryMarkdown) return "Open the latest session summary";
|
|
37359
|
+
return "Open or create a session summary";
|
|
37360
|
+
}
|
|
37361
|
+
|
|
37362
|
+
function createTerminalTabSplitButton(tab) {
|
|
37363
|
+
const button = make("button", "terminal-tab-split-button");
|
|
37364
|
+
button.type = "button";
|
|
37365
|
+
button.draggable = false;
|
|
37366
|
+
const isOpenSplit = splitTabId === tab.id && !embeddedSplitMode && !isSidePanelOverlayView();
|
|
37367
|
+
button.disabled = embeddedSplitMode || isSidePanelOverlayView();
|
|
37368
|
+
button.setAttribute("aria-pressed", isOpenSplit ? "true" : "false");
|
|
37369
|
+
button.dataset.splitState = isOpenSplit ? "unsplit" : "split";
|
|
37370
|
+
const label = isOpenSplit ? `Close split view for ${tab.title || "Pi terminal"}` : `Split ${tab.title || "Pi terminal"} to the right`;
|
|
37371
|
+
applyStyledTooltip(button, label, { ariaLabel: label, targetKey: `terminal-tab:${tab.id}:split` });
|
|
37372
|
+
const ns = "http://www.w3.org/2000/svg";
|
|
37373
|
+
const icon = document.createElementNS(ns, "svg");
|
|
37374
|
+
icon.setAttribute("class", "terminal-tab-action-icon terminal-tab-split-icon");
|
|
37375
|
+
icon.setAttribute("viewBox", "0 0 24 24");
|
|
37376
|
+
icon.setAttribute("aria-hidden", "true");
|
|
37377
|
+
icon.setAttribute("focusable", "false");
|
|
37378
|
+
const frame = document.createElementNS(ns, "rect");
|
|
37379
|
+
frame.setAttribute("x", "4");
|
|
37380
|
+
frame.setAttribute("y", "5");
|
|
37381
|
+
frame.setAttribute("width", "16");
|
|
37382
|
+
frame.setAttribute("height", "14");
|
|
37383
|
+
frame.setAttribute("rx", "2");
|
|
37384
|
+
frame.setAttribute("fill", "none");
|
|
37385
|
+
frame.setAttribute("stroke", "currentColor");
|
|
37386
|
+
frame.setAttribute("stroke-width", "2");
|
|
37387
|
+
const divider = document.createElementNS(ns, "path");
|
|
37388
|
+
divider.setAttribute("d", "M12 5v14M15 12h4m0 0-2-2m2 2-2 2");
|
|
37389
|
+
divider.setAttribute("fill", "none");
|
|
37390
|
+
divider.setAttribute("stroke", "currentColor");
|
|
37391
|
+
divider.setAttribute("stroke-width", "2");
|
|
37392
|
+
divider.setAttribute("stroke-linecap", "round");
|
|
37393
|
+
divider.setAttribute("stroke-linejoin", "round");
|
|
37394
|
+
icon.append(frame, divider);
|
|
37395
|
+
button.append(icon);
|
|
37396
|
+
button.addEventListener("click", (event) => {
|
|
37397
|
+
event.stopPropagation();
|
|
37398
|
+
void splitTerminalTab(tab.id, { triggerButton: button });
|
|
37399
|
+
});
|
|
37400
|
+
return button;
|
|
37401
|
+
}
|
|
37402
|
+
|
|
37403
|
+
function createTerminalTabActions(tab) {
|
|
37404
|
+
const actions = make("div", "terminal-tab-actions");
|
|
37405
|
+
actions.setAttribute("role", "group");
|
|
37406
|
+
actions.setAttribute("aria-label", `Actions for ${tab.title || "Pi terminal"}`);
|
|
37407
|
+
actions.append(createTerminalTabSplitButton(tab));
|
|
37408
|
+
const summary = createTerminalTabSessionSummaryButton(tab);
|
|
37409
|
+
if (summary) actions.append(summary);
|
|
37410
|
+
return actions;
|
|
37411
|
+
}
|
|
37412
|
+
|
|
37413
|
+
function createTerminalTabSessionSummaryButton(tab) {
|
|
37414
|
+
if (!tab?.id || !hasAvailableCommand("summary", { tabId: tab.id })) return null;
|
|
37415
|
+
const state = sessionSummaryStateForTab(tab.id);
|
|
37416
|
+
const status = sessionSummaryControlStatus(tab.id);
|
|
37417
|
+
const button = make("button", "terminal-tab-summary-button");
|
|
37418
|
+
button.type = "button";
|
|
37419
|
+
button.draggable = false;
|
|
37420
|
+
button.disabled = state?.status === "generating";
|
|
37421
|
+
button.setAttribute("aria-busy", state?.status === "generating" ? "true" : "false");
|
|
37422
|
+
button.setAttribute("aria-controls", "sessionSummaryOverlay");
|
|
37423
|
+
const label = `${status} for ${tab.title || "Pi terminal"}`;
|
|
37424
|
+
applyStyledTooltip(button, status, { ariaLabel: label, targetKey: `terminal-tab:${tab.id}:summary` });
|
|
37425
|
+
const ns = "http://www.w3.org/2000/svg";
|
|
37426
|
+
const icon = document.createElementNS(ns, "svg");
|
|
37427
|
+
icon.setAttribute("class", "composer-icon");
|
|
37428
|
+
icon.setAttribute("viewBox", "0 0 24 24");
|
|
37429
|
+
icon.setAttribute("aria-hidden", "true");
|
|
37430
|
+
icon.setAttribute("focusable", "false");
|
|
37431
|
+
const page = document.createElementNS(ns, "path");
|
|
37432
|
+
page.setAttribute("d", "M5 4h14v16H5z");
|
|
37433
|
+
page.setAttribute("fill", "none");
|
|
37434
|
+
page.setAttribute("stroke", "currentColor");
|
|
37435
|
+
page.setAttribute("stroke-width", "2");
|
|
37436
|
+
page.setAttribute("stroke-linejoin", "round");
|
|
37437
|
+
const lines = document.createElementNS(ns, "path");
|
|
37438
|
+
lines.setAttribute("d", "M8 8h8M8 12h8M8 16h5");
|
|
37439
|
+
lines.setAttribute("fill", "none");
|
|
37440
|
+
lines.setAttribute("stroke", "currentColor");
|
|
37441
|
+
lines.setAttribute("stroke-width", "2");
|
|
37442
|
+
lines.setAttribute("stroke-linecap", "round");
|
|
37443
|
+
icon.append(page, lines);
|
|
37444
|
+
button.append(icon);
|
|
37445
|
+
button.addEventListener("click", (event) => {
|
|
37446
|
+
event.stopPropagation();
|
|
37447
|
+
void openSessionSummaryForTab(tab.id, { focusReturnKey: `terminal-tab:${tab.id}:summary` }).catch((error) => addEvent(error.message || String(error), "error"));
|
|
37448
|
+
});
|
|
37449
|
+
return button;
|
|
37450
|
+
}
|
|
37451
|
+
|
|
35498
37452
|
function renderSessionSummaryControls() {
|
|
35499
|
-
const available = !!activeTabId && hasAvailableCommand("summary", { tabId: activeTabId });
|
|
35500
37453
|
const setupAvailable = !!activeTabId && hasAvailableCommand("summary-setup", { tabId: activeTabId });
|
|
35501
|
-
const state = sessionSummaryStateForTab(activeTabId);
|
|
35502
|
-
const status = state?.status === "generating" ? "Generating session summary…" : state?.status === "failure" ? `Session summary failed: ${state.message || "unknown error"}` : state?.summaryMarkdown ? "Open the latest session summary" : "Open or create a session summary";
|
|
35503
|
-
for (const button of [elements.summaryHeaderButton, elements.summaryActionButton]) {
|
|
35504
|
-
if (!button) continue;
|
|
35505
|
-
button.hidden = !available;
|
|
35506
|
-
button.disabled = !available || state?.status === "generating";
|
|
35507
|
-
button.setAttribute("aria-busy", state?.status === "generating" ? "true" : "false");
|
|
35508
|
-
applyStyledTooltip(button, status, { ariaLabel: status, align: "end" });
|
|
35509
|
-
}
|
|
35510
37454
|
if (elements.optionsSummarySetupButton) elements.optionsSummarySetupButton.hidden = !setupAvailable;
|
|
37455
|
+
scheduleTabsRender();
|
|
35511
37456
|
}
|
|
35512
37457
|
|
|
35513
37458
|
function closeSessionSummaryOverlay({ restoreFocus = true } = {}) {
|
|
@@ -35515,9 +37460,19 @@ function closeSessionSummaryOverlay({ restoreFocus = true } = {}) {
|
|
|
35515
37460
|
if (!overlay || overlay.hidden) return;
|
|
35516
37461
|
overlay.hidden = true;
|
|
35517
37462
|
const focusReturn = sessionSummaryOverlayFocusReturn;
|
|
37463
|
+
const focusReturnKey = sessionSummaryOverlayFocusReturnKey;
|
|
37464
|
+
const keyedFocusReturn = focusReturnKey
|
|
37465
|
+
? [...elements.tabBar.querySelectorAll("button")].find((node) => terminalTabControlKey(node) === focusReturnKey)
|
|
37466
|
+
: null;
|
|
37467
|
+
const connectedFocusReturn = keyedFocusReturn || (focusReturn?.isConnected ? focusReturn : null);
|
|
35518
37468
|
sessionSummaryOverlayTabId = null;
|
|
35519
37469
|
sessionSummaryOverlayFocusReturn = null;
|
|
35520
|
-
|
|
37470
|
+
sessionSummaryOverlayFocusReturnKey = "";
|
|
37471
|
+
if (restoreFocus && connectedFocusReturn) {
|
|
37472
|
+
const groupKey = connectedFocusReturn.closest?.("[data-group-key]")?.dataset?.groupKey;
|
|
37473
|
+
if (groupKey) setOpenTerminalTabGroup(groupKey);
|
|
37474
|
+
queueMicrotask(() => connectedFocusReturn.focus({ preventScroll: true }));
|
|
37475
|
+
}
|
|
35521
37476
|
}
|
|
35522
37477
|
|
|
35523
37478
|
function renderSessionSummaryOverlay() {
|
|
@@ -35545,9 +37500,10 @@ function renderSessionSummaryOverlay() {
|
|
|
35545
37500
|
elements.sessionSummaryOverlayRefreshButton.textContent = generating ? "Generating…" : "Refresh";
|
|
35546
37501
|
}
|
|
35547
37502
|
|
|
35548
|
-
function openSessionSummaryOverlay(tabId, { loading = false } = {}) {
|
|
37503
|
+
function openSessionSummaryOverlay(tabId, { loading = false, focusReturnKey = "" } = {}) {
|
|
35549
37504
|
if (!tabId || !elements.sessionSummaryOverlay) return;
|
|
35550
37505
|
sessionSummaryOverlayFocusReturn = document.activeElement instanceof HTMLElement ? document.activeElement : null;
|
|
37506
|
+
sessionSummaryOverlayFocusReturnKey = focusReturnKey || terminalTabControlKey(sessionSummaryOverlayFocusReturn);
|
|
35551
37507
|
sessionSummaryOverlayTabId = tabId;
|
|
35552
37508
|
if (loading) {
|
|
35553
37509
|
const previous = sessionSummaryStateForTab(tabId);
|
|
@@ -35569,7 +37525,7 @@ function updateSessionSummaryForTab(tabId, value, { resetProjection = false } =
|
|
|
35569
37525
|
const normalized = normalizeSessionSummaryClientState(value, sessionSummaryByTab.get(tabId), { resetProjection });
|
|
35570
37526
|
if (!normalized) return null;
|
|
35571
37527
|
sessionSummaryByTab.set(tabId, normalized);
|
|
35572
|
-
|
|
37528
|
+
renderSessionSummaryControls();
|
|
35573
37529
|
if (sessionSummaryOverlayTabId === tabId) renderSessionSummaryOverlay();
|
|
35574
37530
|
return normalized;
|
|
35575
37531
|
}
|
|
@@ -35604,7 +37560,7 @@ async function requestSessionSummaryGeneration(tabId, { refresh = false } = {})
|
|
|
35604
37560
|
}
|
|
35605
37561
|
}
|
|
35606
37562
|
|
|
35607
|
-
async function openSessionSummaryForTab(tabId = activeTabId, { refresh = false } = {}) {
|
|
37563
|
+
async function openSessionSummaryForTab(tabId = activeTabId, { refresh = false, focusReturnKey = "" } = {}) {
|
|
35608
37564
|
if (!tabId || !hasAvailableCommand("summary", { tabId })) return;
|
|
35609
37565
|
let state = sessionSummaryStateForTab(tabId);
|
|
35610
37566
|
if (!state?.configured) {
|
|
@@ -35618,11 +37574,11 @@ async function openSessionSummaryForTab(tabId = activeTabId, { refresh = false }
|
|
|
35618
37574
|
updatedAt: new Date().toISOString(),
|
|
35619
37575
|
});
|
|
35620
37576
|
if (!response.data?.preferences?.configured) {
|
|
35621
|
-
await openNativeSessionSummarySetupDialog({ initialData: response.data });
|
|
37577
|
+
await openNativeSessionSummarySetupDialog({ initialData: response.data, tabId, focusReturnKey });
|
|
35622
37578
|
return;
|
|
35623
37579
|
}
|
|
35624
37580
|
}
|
|
35625
|
-
openSessionSummaryOverlay(tabId, { loading: refresh || !state?.summaryMarkdown });
|
|
37581
|
+
openSessionSummaryOverlay(tabId, { loading: refresh || !state?.summaryMarkdown, focusReturnKey });
|
|
35626
37582
|
if (refresh || !state?.summaryMarkdown) await requestSessionSummaryGeneration(tabId, { refresh }).catch(() => {});
|
|
35627
37583
|
}
|
|
35628
37584
|
|
|
@@ -36312,9 +38268,9 @@ const SAFETY_GUARD_CATEGORY_LABELS = Object.freeze({
|
|
|
36312
38268
|
async function openNativeSafetyGuardSetupDialog() {
|
|
36313
38269
|
openNativeCommandDialog({
|
|
36314
38270
|
title: "/safety-guard-setup",
|
|
36315
|
-
message: "Configure persistent command categories, protected-path checks,
|
|
38271
|
+
message: "Configure persistent command categories, protected-path checks, preview context, and optional model auto-review.",
|
|
36316
38272
|
});
|
|
36317
|
-
renderNativeLoading("Loading safety guard setup…");
|
|
38273
|
+
renderNativeLoading("Loading safety guard setup and authenticated models…");
|
|
36318
38274
|
|
|
36319
38275
|
let data;
|
|
36320
38276
|
try {
|
|
@@ -36328,6 +38284,7 @@ async function openNativeSafetyGuardSetupDialog() {
|
|
|
36328
38284
|
|
|
36329
38285
|
const config = data.config || {};
|
|
36330
38286
|
const defaults = data.defaults || {};
|
|
38287
|
+
const models = Array.isArray(data.models) ? data.models : [];
|
|
36331
38288
|
const categories = Array.isArray(data.categories) && data.categories.length
|
|
36332
38289
|
? data.categories
|
|
36333
38290
|
: Object.keys(SAFETY_GUARD_CATEGORY_LABELS);
|
|
@@ -36337,6 +38294,17 @@ async function openNativeSafetyGuardSetupDialog() {
|
|
|
36337
38294
|
{ length: Math.max(1, maximumContext - minimumContext + 1) },
|
|
36338
38295
|
(_, index) => String(index + minimumContext),
|
|
36339
38296
|
);
|
|
38297
|
+
const modelKey = (model) => model?.provider && model?.id ? `${model.provider}/${model.id}` : "";
|
|
38298
|
+
const configuredModelKey = config.autoReview?.model?.provider && config.autoReview?.model?.modelId
|
|
38299
|
+
? `${config.autoReview.model.provider}/${config.autoReview.model.modelId}`
|
|
38300
|
+
: "";
|
|
38301
|
+
const modelOptions = [
|
|
38302
|
+
{ value: "", label: models.length ? "Select an authenticated model" : "No authenticated models available" },
|
|
38303
|
+
...models.map((model) => ({
|
|
38304
|
+
value: modelKey(model),
|
|
38305
|
+
label: `${modelKey(model)}${model.name && model.name !== model.id ? ` · ${model.name}` : ""}`,
|
|
38306
|
+
})),
|
|
38307
|
+
];
|
|
36340
38308
|
const categoryControls = Object.fromEntries(categories.map((category) => [
|
|
36341
38309
|
category,
|
|
36342
38310
|
nativeSettingToggle(
|
|
@@ -36348,38 +38316,105 @@ async function openNativeSafetyGuardSetupDialog() {
|
|
|
36348
38316
|
]));
|
|
36349
38317
|
const controls = {
|
|
36350
38318
|
enabled: nativeSettingToggle("Safety guard enabled", config.enabled !== false, "Master switch for command and protected-path guards.", { label: "global", tone: "safety" }),
|
|
38319
|
+
autoReview: nativeSettingToggle("Automatic model review", config.autoReview?.enabled === true, "Off by default. When enabled, matched operations wait for this model's allow/block verdict; failures return to the existing prompt.", { label: "opt-in", tone: "safety" }),
|
|
38320
|
+
autoReviewModel: nativeSettingSelect("Review model", configuredModelKey, modelOptions, "Authenticated provider/model used only for safety preflight. There is no provider fallback.", { label: "required when on", tone: "safety" }),
|
|
38321
|
+
autoReviewThinking: nativeSettingSelect("Review thinking", config.autoReview?.model?.thinkingLevel || "off", data.thinkingLevels || SETTINGS_THINKING_OPTIONS, "Only levels supported by the selected model are offered.", { label: "required when on", tone: "safety" }),
|
|
36351
38322
|
before: nativeSettingSelect("Lines before a match", config.contextLines?.before ?? 3, contextOptions, "Number of command lines shown before each matched line.", { label: "preview", tone: "browser" }),
|
|
36352
38323
|
after: nativeSettingSelect("Lines after a match", config.contextLines?.after ?? 3, contextOptions, "Number of command lines shown after each matched line.", { label: "preview", tone: "browser" }),
|
|
36353
38324
|
protectedWrite: nativeSettingToggle("Guard protected-path writes", config.protectedPaths?.write !== false, "Prompt before write calls target credentials, private keys, or environment files.", { label: "write", tone: "safety" }),
|
|
36354
38325
|
protectedEdit: nativeSettingToggle("Guard protected-path edits", config.protectedPaths?.edit !== false, "Prompt before edit calls target credentials, private keys, or environment files.", { label: "edit", tone: "safety" }),
|
|
36355
38326
|
};
|
|
36356
|
-
|
|
36357
|
-
|
|
36358
|
-
|
|
36359
|
-
|
|
36360
|
-
|
|
36361
|
-
|
|
36362
|
-
|
|
36363
|
-
|
|
36364
|
-
|
|
36365
|
-
|
|
36366
|
-
|
|
36367
|
-
|
|
36368
|
-
|
|
36369
|
-
|
|
38327
|
+
controls.autoReviewModel.select.options[0].disabled = true;
|
|
38328
|
+
if (configuredModelKey && !models.some((model) => modelKey(model) === configuredModelKey)) {
|
|
38329
|
+
const unavailable = make("option", undefined, `Unavailable: ${configuredModelKey}`);
|
|
38330
|
+
unavailable.value = configuredModelKey;
|
|
38331
|
+
unavailable.disabled = true;
|
|
38332
|
+
controls.autoReviewModel.select.append(unavailable);
|
|
38333
|
+
controls.autoReviewModel.select.value = configuredModelKey;
|
|
38334
|
+
}
|
|
38335
|
+
|
|
38336
|
+
const autoReviewAvailability = nativeSettingsNote("Auto-review availability", "");
|
|
38337
|
+
const autoReviewAvailabilityText = autoReviewAvailability.querySelector("span");
|
|
38338
|
+
const thinkingLevelsForModel = (selectedModelKey) => {
|
|
38339
|
+
const levels = data.modelThinkingLevels?.[selectedModelKey];
|
|
38340
|
+
return Array.isArray(levels) && levels.length ? levels : [];
|
|
38341
|
+
};
|
|
38342
|
+
const syncAutoReviewControls = ({ preferredThinking, preserveUnavailable = false } = {}) => {
|
|
38343
|
+
const enabled = controls.autoReview.input.checked;
|
|
38344
|
+
const selectedModelKey = controls.autoReviewModel.select.value;
|
|
38345
|
+
const selectedAvailable = models.some((model) => modelKey(model) === selectedModelKey);
|
|
38346
|
+
const levels = thinkingLevelsForModel(selectedModelKey);
|
|
38347
|
+
const preferred = preferredThinking ?? controls.autoReviewThinking.select.value ?? "off";
|
|
38348
|
+
replaceNativeSettingSelectOptions(controls.autoReviewThinking.select, levels.length ? levels : ["off"], preferred);
|
|
38349
|
+
if (preserveUnavailable && preferred && !levels.includes(preferred) && preferred !== "off") {
|
|
38350
|
+
const unavailable = make("option", undefined, `Unavailable: ${preferred}`);
|
|
38351
|
+
unavailable.value = preferred;
|
|
38352
|
+
unavailable.disabled = true;
|
|
38353
|
+
controls.autoReviewThinking.select.append(unavailable);
|
|
38354
|
+
controls.autoReviewThinking.select.value = preferred;
|
|
38355
|
+
}
|
|
38356
|
+
controls.autoReviewModel.select.disabled = !models.length;
|
|
38357
|
+
controls.autoReviewThinking.select.disabled = !selectedAvailable;
|
|
38358
|
+
autoReviewAvailability.classList.toggle("warning", enabled && (!selectedAvailable || !levels.includes(controls.autoReviewThinking.select.value)));
|
|
38359
|
+
autoReviewAvailabilityText.textContent = !enabled
|
|
38360
|
+
? "Off. Matched operations use the existing interactive prompt; model and thinking can still be preselected before enabling auto-review."
|
|
38361
|
+
: !models.length
|
|
38362
|
+
? "Unavailable: no authenticated Pi models are available. Run /login or configure a provider before enabling auto-review."
|
|
38363
|
+
: !selectedAvailable
|
|
38364
|
+
? "Unavailable: select one of the authenticated models from this active tab."
|
|
38365
|
+
: `Ready: ${selectedModelKey} supports ${levels.join(", ")} thinking.`;
|
|
38366
|
+
};
|
|
38367
|
+
controls.autoReview.input.addEventListener("change", () => syncAutoReviewControls());
|
|
38368
|
+
controls.autoReviewModel.select.addEventListener("change", () => syncAutoReviewControls({ preferredThinking: "off" }));
|
|
38369
|
+
syncAutoReviewControls({ preferredThinking: config.autoReview?.model?.thinkingLevel || "off", preserveUnavailable: true });
|
|
38370
|
+
|
|
38371
|
+
const collectConfig = () => {
|
|
38372
|
+
const selectedModelKey = controls.autoReviewModel.select.value;
|
|
38373
|
+
const selectedModel = models.find((model) => modelKey(model) === selectedModelKey);
|
|
38374
|
+
const persistedModel = selectedModelKey === configuredModelKey ? config.autoReview?.model : null;
|
|
38375
|
+
return {
|
|
38376
|
+
version: data.version || 1,
|
|
38377
|
+
enabled: controls.enabled.input.checked,
|
|
38378
|
+
categories: Object.fromEntries(categories.map((category) => [category, categoryControls[category].input.checked])),
|
|
38379
|
+
protectedPaths: {
|
|
38380
|
+
write: controls.protectedWrite.input.checked,
|
|
38381
|
+
edit: controls.protectedEdit.input.checked,
|
|
38382
|
+
},
|
|
38383
|
+
contextLines: {
|
|
38384
|
+
before: Number.parseInt(controls.before.select.value, 10),
|
|
38385
|
+
after: Number.parseInt(controls.after.select.value, 10),
|
|
38386
|
+
},
|
|
38387
|
+
autoReview: {
|
|
38388
|
+
enabled: controls.autoReview.input.checked,
|
|
38389
|
+
model: {
|
|
38390
|
+
provider: selectedModel?.provider || persistedModel?.provider || "",
|
|
38391
|
+
modelId: selectedModel?.id || persistedModel?.modelId || "",
|
|
38392
|
+
thinkingLevel: controls.autoReviewThinking.select.value || "off",
|
|
38393
|
+
},
|
|
38394
|
+
},
|
|
38395
|
+
};
|
|
38396
|
+
};
|
|
36370
38397
|
const applyConfig = (value) => {
|
|
36371
38398
|
controls.enabled.input.checked = value?.enabled !== false;
|
|
36372
38399
|
controls.before.select.value = String(value?.contextLines?.before ?? 3);
|
|
36373
38400
|
controls.after.select.value = String(value?.contextLines?.after ?? 3);
|
|
36374
38401
|
controls.protectedWrite.input.checked = value?.protectedPaths?.write !== false;
|
|
36375
38402
|
controls.protectedEdit.input.checked = value?.protectedPaths?.edit !== false;
|
|
38403
|
+
controls.autoReview.input.checked = value?.autoReview?.enabled === true;
|
|
38404
|
+
const nextModelKey = value?.autoReview?.model?.provider && value?.autoReview?.model?.modelId
|
|
38405
|
+
? `${value.autoReview.model.provider}/${value.autoReview.model.modelId}`
|
|
38406
|
+
: "";
|
|
38407
|
+
controls.autoReviewModel.select.value = [...controls.autoReviewModel.select.options].some((option) => option.value === nextModelKey) ? nextModelKey : "";
|
|
36376
38408
|
for (const category of categories) categoryControls[category].input.checked = value?.categories?.[category] !== false;
|
|
38409
|
+
syncAutoReviewControls({ preferredThinking: value?.autoReview?.model?.thinkingLevel || "off", preserveUnavailable: true });
|
|
36377
38410
|
};
|
|
36378
38411
|
|
|
36379
38412
|
const body = make("div", "native-settings-panel");
|
|
36380
38413
|
body.append(
|
|
36381
38414
|
nativeSettingsNote("Persistence", `Saved globally in ${data.path || "~/.pi/agent/safety-guard.json"}. Changes are reloaded before guard checks.`),
|
|
36382
38415
|
nativeSettingsSection("General", "Enable or disable all guard behavior.", [controls.enabled], { open: true }),
|
|
38416
|
+
nativeSettingsSection("Automatic review", "Opt in to a dedicated authenticated model for non-modal allow/block preflight. Provider failures and invalid verdicts return to the existing prompt.", [controls.autoReview, controls.autoReviewModel, controls.autoReviewThinking], { open: true }),
|
|
38417
|
+
autoReviewAvailability,
|
|
36383
38418
|
nativeSettingsSection("Command preview", "Choose independent context limits before and after each dangerous matched line.", [controls.before, controls.after], { open: true }),
|
|
36384
38419
|
nativeSettingsSection("Command categories", "Disable only categories you intentionally do not want guarded.", categories.map((category) => categoryControls[category]), { open: true }),
|
|
36385
38420
|
nativeSettingsSection("Protected paths", "Control write/edit prompts for secret-bearing files and credential paths.", [controls.protectedWrite, controls.protectedEdit], { open: true }),
|
|
@@ -36396,16 +38431,28 @@ async function openNativeSafetyGuardSetupDialog() {
|
|
|
36396
38431
|
setNativeActionBusy(save, true, "Saving…");
|
|
36397
38432
|
setNativeCommandError("");
|
|
36398
38433
|
try {
|
|
38434
|
+
const submitted = collectConfig();
|
|
38435
|
+
const selectedModelKey = controls.autoReviewModel.select.value;
|
|
38436
|
+
const supportedLevels = thinkingLevelsForModel(selectedModelKey);
|
|
38437
|
+
if (submitted.autoReview.enabled && !models.some((model) => modelKey(model) === selectedModelKey)) {
|
|
38438
|
+
throw new Error("Select an authenticated auto-review model from this active tab.");
|
|
38439
|
+
}
|
|
38440
|
+
if (submitted.autoReview.enabled && !supportedLevels.includes(submitted.autoReview.model.thinkingLevel)) {
|
|
38441
|
+
throw new Error(`${selectedModelKey} does not support thinking level ${submitted.autoReview.model.thinkingLevel}.`);
|
|
38442
|
+
}
|
|
36399
38443
|
const response = await nativeCommandApi("/api/safety-guard/config", {
|
|
36400
38444
|
method: "POST",
|
|
36401
|
-
body: { config:
|
|
38445
|
+
body: { config: submitted },
|
|
36402
38446
|
});
|
|
36403
|
-
const saved = response.data?.config ||
|
|
38447
|
+
const saved = response.data?.config || submitted;
|
|
36404
38448
|
const activeCategories = categories.filter((category) => saved.categories?.[category]).length;
|
|
38449
|
+
const autoReviewSummary = saved.autoReview?.enabled
|
|
38450
|
+
? `auto-review ${saved.autoReview.model.provider}/${saved.autoReview.model.modelId} at ${saved.autoReview.model.thinkingLevel}`
|
|
38451
|
+
: "auto-review off";
|
|
36405
38452
|
addTransientMessage({
|
|
36406
38453
|
role: "native",
|
|
36407
38454
|
title: "/safety-guard-setup",
|
|
36408
|
-
content: `Safety guard ${saved.enabled ? "enabled" : "disabled"}; ${activeCategories}/${categories.length} command categories active; preview ${saved.contextLines?.before ?? 3} before and ${saved.contextLines?.after ?? 3} after.`,
|
|
38455
|
+
content: `Safety guard ${saved.enabled ? "enabled" : "disabled"}; ${activeCategories}/${categories.length} command categories active; ${autoReviewSummary}; preview ${saved.contextLines?.before ?? 3} before and ${saved.contextLines?.after ?? 3} after.`,
|
|
36409
38456
|
level: saved.enabled ? "info" : "warn",
|
|
36410
38457
|
});
|
|
36411
38458
|
closeNativeCommandDialog();
|
|
@@ -36421,8 +38468,8 @@ function gitWorkflowSetupModelKey(model) {
|
|
|
36421
38468
|
return model?.provider && model?.id ? `${model.provider}/${model.id}` : "";
|
|
36422
38469
|
}
|
|
36423
38470
|
|
|
36424
|
-
async function openNativeSessionSummarySetupDialog({ initialData = null, onSaved } = {}) {
|
|
36425
|
-
nativeCommandTabId =
|
|
38471
|
+
async function openNativeSessionSummarySetupDialog({ initialData = null, onSaved, tabId = activeTabId, focusReturnKey = "" } = {}) {
|
|
38472
|
+
nativeCommandTabId = tabId;
|
|
36426
38473
|
openNativeCommandDialog({
|
|
36427
38474
|
title: "/summary-setup",
|
|
36428
38475
|
message: "Configure persistent background titles and Markdown summaries. Saving confirms the disclosure below, then immediately generates and opens the first summary.",
|
|
@@ -36519,10 +38566,11 @@ async function openNativeSessionSummarySetupDialog({ initialData = null, onSaved
|
|
|
36519
38566
|
const summaryPrompt = controls.summaryPrompt.textarea.value.trim();
|
|
36520
38567
|
if (!titlePrompt || !summaryPrompt) throw new Error("Both editable prompts are required.");
|
|
36521
38568
|
if (titlePrompt.length > SESSION_SUMMARY_PROMPT_MAX_CHARS || summaryPrompt.length > SESSION_SUMMARY_PROMPT_MAX_CHARS) throw new Error("Each editable prompt must not exceed 8 KiB.");
|
|
38569
|
+
const targetTabId = nativeCommandTabId || tabId || activeTabId;
|
|
36522
38570
|
const reviewed = await appConfirm({
|
|
36523
38571
|
title: "Save session summary setup?",
|
|
36524
38572
|
summary: `${disclosure.scope || "Selected active-branch text and tool names will be sent to the configured model."}\n\n${disclosure.cost || "Generation may incur provider usage."}`,
|
|
36525
|
-
affected: "Global session-summary preferences and the
|
|
38573
|
+
affected: "Global session-summary preferences and the selected tab's first generated summary",
|
|
36526
38574
|
undoable: false,
|
|
36527
38575
|
confirmLabel: "Save and generate",
|
|
36528
38576
|
danger: false,
|
|
@@ -36530,6 +38578,7 @@ async function openNativeSessionSummarySetupDialog({ initialData = null, onSaved
|
|
|
36530
38578
|
if (!reviewed) return;
|
|
36531
38579
|
const response = await nativeCommandApi("/api/session-summary/preferences", {
|
|
36532
38580
|
method: "PUT",
|
|
38581
|
+
tabId: targetTabId,
|
|
36533
38582
|
body: {
|
|
36534
38583
|
confirmed: true,
|
|
36535
38584
|
preferences: {
|
|
@@ -36542,7 +38591,6 @@ async function openNativeSessionSummarySetupDialog({ initialData = null, onSaved
|
|
|
36542
38591
|
},
|
|
36543
38592
|
},
|
|
36544
38593
|
});
|
|
36545
|
-
const targetTabId = nativeCommandTabId || activeTabId;
|
|
36546
38594
|
updateSessionSummaryForTab(targetTabId, response.data?.summary || {
|
|
36547
38595
|
version: SESSION_SUMMARY_PROTOCOL_VERSION,
|
|
36548
38596
|
status: "idle",
|
|
@@ -36553,7 +38601,7 @@ async function openNativeSessionSummarySetupDialog({ initialData = null, onSaved
|
|
|
36553
38601
|
});
|
|
36554
38602
|
nativeSettingsDirty = false;
|
|
36555
38603
|
closeNativeCommandDialog({ force: true });
|
|
36556
|
-
openSessionSummaryOverlay(targetTabId, { loading: true });
|
|
38604
|
+
openSessionSummaryOverlay(targetTabId, { loading: true, focusReturnKey });
|
|
36557
38605
|
await requestSessionSummaryGeneration(targetTabId, { refresh: true }).catch(() => {});
|
|
36558
38606
|
if (typeof onSaved === "function") await onSaved(response.data?.preferences);
|
|
36559
38607
|
} catch (error) {
|
|
@@ -36623,6 +38671,10 @@ async function openNativeGitWorkflowSetupDialog({ onSaved } = {}) {
|
|
|
36623
38671
|
{ value: "preserve", label: "Use current staged set" },
|
|
36624
38672
|
{ value: "all", label: "Stage all with git add ." },
|
|
36625
38673
|
], "Review/select is the safe default and opens Git Changes for per-file staging.", { label: "safety", tone: "safety" }),
|
|
38674
|
+
reviewProcess: nativeSettingSelect("Manual review process", preferences.reviewProcessEnabled !== false ? "enabled" : "disabled", [
|
|
38675
|
+
{ value: "enabled", label: "Enabled when aur-review is available" },
|
|
38676
|
+
{ value: "disabled", label: "Disabled — continue to message generation" },
|
|
38677
|
+
], "When enabled, staged changes require explicit approval before message, worktree, or commit actions.", { label: "safety", tone: "safety" }),
|
|
36626
38678
|
delivery: nativeSettingSelect("Delivery path", preferences.deliveryMode || "ask", [
|
|
36627
38679
|
{ value: "ask", label: "Ask each workflow" },
|
|
36628
38680
|
{ value: "current", label: "Prefer current branch" },
|
|
@@ -36651,7 +38703,7 @@ async function openNativeGitWorkflowSetupDialog({ onSaved } = {}) {
|
|
|
36651
38703
|
nativeSettingsNote("Persistence", `Saved globally in ${data.path || "the Pi Web UI settings file"}. Credentials are never stored here.`),
|
|
36652
38704
|
nativeSettingsSection("Generation profile", "Required model and effort for generated Git text.", [controls.model, controls.thinking], { open: true }),
|
|
36653
38705
|
nativeSettingsSection("Commit style", "Conventional Commit output preferences.", [controls.language, controls.defaultVariant, controls.scope], { open: true }),
|
|
36654
|
-
nativeSettingsSection("Workflow safety", "Staging, delivery, and verification defaults; push and PR confirmation remain mandatory.", [controls.staging, controls.delivery, controls.verification], { open: true }),
|
|
38706
|
+
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 }),
|
|
36655
38707
|
);
|
|
36656
38708
|
elements.nativeCommandBody.replaceChildren(body);
|
|
36657
38709
|
elements.nativeCommandActions.replaceChildren();
|
|
@@ -36679,6 +38731,7 @@ async function openNativeGitWorkflowSetupDialog({ onSaved } = {}) {
|
|
|
36679
38731
|
scope: controls.scope.select.value,
|
|
36680
38732
|
},
|
|
36681
38733
|
stagingPolicy: controls.staging.select.value,
|
|
38734
|
+
reviewProcessEnabled: controls.reviewProcess.select.value === "enabled",
|
|
36682
38735
|
deliveryMode: controls.delivery.select.value,
|
|
36683
38736
|
verificationPolicy: controls.verification.select.value,
|
|
36684
38737
|
},
|
|
@@ -37682,6 +39735,9 @@ function insertNumpadDecimal(event) {
|
|
|
37682
39735
|
return true;
|
|
37683
39736
|
}
|
|
37684
39737
|
|
|
39738
|
+
// Transcript-only. Message rendering may reconcile transcript state and the
|
|
39739
|
+
// transcript DOM, but never footer/feedback/widget chrome: those surfaces are
|
|
39740
|
+
// owned by the coalesced semantic reconciler.
|
|
37685
39741
|
function renderMessages(messages) {
|
|
37686
39742
|
latestMessages = messages || [];
|
|
37687
39743
|
reconcileOptimisticUserPrompts(latestMessages);
|
|
@@ -37690,8 +39746,6 @@ function renderMessages(messages) {
|
|
|
37690
39746
|
syncPromptHistoryFromMessages(latestMessages);
|
|
37691
39747
|
trackSkillsFromMessages(latestMessages, activeTabId);
|
|
37692
39748
|
renderAllMessages();
|
|
37693
|
-
renderFooter();
|
|
37694
|
-
renderFeedbackTray();
|
|
37695
39749
|
}
|
|
37696
39750
|
|
|
37697
39751
|
function cancelStreamBubbleHide() {
|
|
@@ -37836,10 +39890,6 @@ function handleCompactMessageUpdate(event) {
|
|
|
37836
39890
|
if (!reduced.changed) return true;
|
|
37837
39891
|
compactLiveState = reduced.state;
|
|
37838
39892
|
clearCompactToolShells();
|
|
37839
|
-
if (reduced.kind.startsWith("thinking")) setRunIndicatorActivity("Thinking…", { scroll: false });
|
|
37840
|
-
else if (reduced.kind.startsWith("toolcall")) setRunIndicatorActivity("Building tool call…", { scroll: false });
|
|
37841
|
-
else setRunIndicatorActivity("Writing response…", { scroll: false });
|
|
37842
|
-
compactLiveScheduler.request();
|
|
37843
39893
|
return true;
|
|
37844
39894
|
}
|
|
37845
39895
|
|
|
@@ -37899,15 +39949,7 @@ function applyOutputModeControl(event, tabContext = activeTabContext()) {
|
|
|
37899
39949
|
return true;
|
|
37900
39950
|
}
|
|
37901
39951
|
|
|
37902
|
-
function cancelStreamingAssistantTextRender() {
|
|
37903
|
-
clearTimeout(streamTextRenderTimer);
|
|
37904
|
-
streamTextRenderTimer = null;
|
|
37905
|
-
if (streamTextRenderFrame !== null && typeof cancelAnimationFrame === "function") cancelAnimationFrame(streamTextRenderFrame);
|
|
37906
|
-
streamTextRenderFrame = null;
|
|
37907
|
-
}
|
|
37908
|
-
|
|
37909
39952
|
function removeStreamBubble() {
|
|
37910
|
-
cancelStreamingAssistantTextRender();
|
|
37911
39953
|
cancelStreamBubbleHide();
|
|
37912
39954
|
removeLiveTranscriptBubble(streamBubble, "assistant");
|
|
37913
39955
|
streamBubble = null;
|
|
@@ -38054,18 +40096,6 @@ function renderStreamingAssistantText() {
|
|
|
38054
40096
|
}
|
|
38055
40097
|
}
|
|
38056
40098
|
|
|
38057
|
-
function scheduleStreamingAssistantTextRender({ immediate = false } = {}) {
|
|
38058
|
-
if (streamTextRenderTimer || streamTextRenderFrame !== null) return;
|
|
38059
|
-
const flush = () => {
|
|
38060
|
-
streamTextRenderTimer = null;
|
|
38061
|
-
streamTextRenderFrame = null;
|
|
38062
|
-
renderStreamingAssistantText();
|
|
38063
|
-
scheduleChatFollowScroll();
|
|
38064
|
-
};
|
|
38065
|
-
if (immediate && typeof requestAnimationFrame === "function") streamTextRenderFrame = requestAnimationFrame(flush);
|
|
38066
|
-
else streamTextRenderTimer = setTimeout(flush, immediate ? 0 : STREAM_OUTPUT_TOOLCALL_GUARD_MS);
|
|
38067
|
-
}
|
|
38068
|
-
|
|
38069
40099
|
function suppressStreamingAssistantTextBeforeToolCall() {
|
|
38070
40100
|
setStreamRawText("");
|
|
38071
40101
|
removeStreamBubble();
|
|
@@ -38162,7 +40192,6 @@ function showStreamingThinking(initialText = "") {
|
|
|
38162
40192
|
|
|
38163
40193
|
function resetStreamBubble({ preserveCompact = false } = {}) {
|
|
38164
40194
|
resetCompactLiveOutput({ remove: !preserveCompact });
|
|
38165
|
-
cancelStreamingAssistantTextRender();
|
|
38166
40195
|
cancelStreamBubbleHide();
|
|
38167
40196
|
streamBubble = null;
|
|
38168
40197
|
streamText = null;
|
|
@@ -38401,52 +40430,35 @@ function handleMessageUpdate(event) {
|
|
|
38401
40430
|
if (compactOutputActive() && handleCompactMessageUpdate(event)) return;
|
|
38402
40431
|
const update = event.assistantMessageEvent || {};
|
|
38403
40432
|
if (update.type === "thinking_start") {
|
|
38404
|
-
setRunIndicatorActivity("Thinking…", { scroll: false });
|
|
38405
40433
|
syncStreamingThinkingFromUpdate(event, update);
|
|
38406
|
-
scheduleChatFollowScroll();
|
|
38407
40434
|
} else if (update.type === "thinking_delta") {
|
|
38408
40435
|
const delta = thinkingDeltaText(update);
|
|
38409
|
-
setRunIndicatorActivity("Thinking…", { scroll: false });
|
|
38410
40436
|
const synced = syncStreamingThinkingFromUpdate(event, update);
|
|
38411
40437
|
if (thinkingOutputVisible && delta && (!synced || !streamThinking?.textContent)) {
|
|
38412
40438
|
showStreamingThinking("");
|
|
38413
40439
|
if (streamThinking) renderThinkingMarkdown(streamThinking, `${streamThinking._rawThinkingText || ""}${delta}`);
|
|
38414
40440
|
}
|
|
38415
|
-
scheduleChatFollowScroll();
|
|
38416
40441
|
} else if (update.type === "thinking_end") {
|
|
38417
40442
|
if (syncStreamingThinkingFromUpdate(event, update)) streamThinkingBubble?.classList.add("complete");
|
|
38418
|
-
setRunIndicatorActivity("Finished thinking; waiting for the next output or action…", { scroll: false });
|
|
38419
40443
|
} else if (update.type === "text_delta" || update.type === "text_end") {
|
|
38420
40444
|
syncStreamRawTextFromUpdate(event, update);
|
|
38421
|
-
|
|
38422
|
-
setRunIndicatorActivity("Writing response…", { scroll: false });
|
|
38423
|
-
scheduleStreamingAssistantTextRender({ immediate: !!(streamToolCallSeen || streamBubble) });
|
|
38424
|
-
// Streaming output must stay transcript-local. Full footer/status
|
|
38425
|
-
// reconciliation happens on message/state refreshes, not per token.
|
|
38426
|
-
scheduleChatFollowScroll();
|
|
40445
|
+
renderStreamingAssistantText();
|
|
38427
40446
|
} else if (update.type === "toolcall_start") {
|
|
38428
40447
|
streamToolCallSeen = true;
|
|
38429
40448
|
suppressStreamingAssistantTextBeforeToolCall();
|
|
38430
|
-
|
|
38431
|
-
setRunIndicatorActivity(`Building tool call: ${name}…`, { scroll: false });
|
|
38432
|
-
addEvent(`tool call started in assistant message`, "info");
|
|
40449
|
+
updateStreamingToolCallFromEvent(event, { reset: true });
|
|
38433
40450
|
} else if (update.type === "toolcall_delta") {
|
|
38434
40451
|
streamToolCallSeen = true;
|
|
38435
40452
|
suppressStreamingAssistantTextBeforeToolCall();
|
|
38436
|
-
|
|
38437
|
-
setRunIndicatorActivity(`Building tool call: ${name}…`, { scroll: false });
|
|
38438
|
-
scheduleChatFollowScroll();
|
|
40453
|
+
updateStreamingToolCallFromEvent(event, { appendDelta: true });
|
|
38439
40454
|
} else if (update.type === "toolcall_end") {
|
|
38440
40455
|
streamToolCallSeen = true;
|
|
38441
40456
|
suppressStreamingAssistantTextBeforeToolCall();
|
|
38442
|
-
|
|
38443
|
-
setRunIndicatorActivity(`Tool call ready: ${name}; waiting to run…`, { scroll: false });
|
|
40457
|
+
updateStreamingToolCallFromEvent(event, { complete: true });
|
|
38444
40458
|
} else if (update.type === "error") {
|
|
38445
40459
|
streamProviderErrorText = assistantStreamErrorMessage(event, update);
|
|
38446
|
-
setRunIndicatorActivity("Assistant stream reported an error…");
|
|
38447
40460
|
appendMessage({ role: "error", title: "assistant error", timestamp: Date.now(), content: streamProviderErrorText, level: "error" }, { streaming: true });
|
|
38448
40461
|
renderRunIndicator({ scroll: false });
|
|
38449
|
-
scheduleChatFollowScroll();
|
|
38450
40462
|
}
|
|
38451
40463
|
}
|
|
38452
40464
|
|
|
@@ -38475,6 +40487,11 @@ async function refreshState(tabContext = activeTabContext()) {
|
|
|
38475
40487
|
renderStatus();
|
|
38476
40488
|
if (mobilePhoneExperienceInstalled && isMobileShellV2Active()) renderMobilePhoneExperience();
|
|
38477
40489
|
requestGitFooterWebuiPayload(tabContext, { force: shouldRefreshGitFooter });
|
|
40490
|
+
// Sampling support and effective values depend on the active model, so refresh
|
|
40491
|
+
// them whenever the session reports a different model.
|
|
40492
|
+
if (modelStateKey(previousState?.model) !== modelStateKey(currentState?.model)) {
|
|
40493
|
+
refreshSamplingParametersForTabContext(tabContext);
|
|
40494
|
+
}
|
|
38478
40495
|
}
|
|
38479
40496
|
|
|
38480
40497
|
async function refreshStats(tabContext = activeTabContext()) {
|
|
@@ -38742,7 +40759,13 @@ async function refreshMessages(tabContext = activeTabContext(), { authoritative
|
|
|
38742
40759
|
else if (preserveNormalStream) restoreStreamRenderAfterChatRebuild();
|
|
38743
40760
|
restoreChatTextSelection(selectionSnapshot);
|
|
38744
40761
|
markTabOutputSeen();
|
|
38745
|
-
|
|
40762
|
+
// Authoritative content just landed: derive the todo-progress record once
|
|
40763
|
+
// here instead of from raw token cadence, and let the coalesced semantic
|
|
40764
|
+
// reconciler own the footer/widget chrome that message data can change.
|
|
40765
|
+
// syncLiveTodoProgressWidgetFromText owns the frame-coalesced widget render
|
|
40766
|
+
// and only fires when the parsed checklist value actually changed.
|
|
40767
|
+
reconcileTodoProgressFromMessages(latestMessages, tabContext.tabId);
|
|
40768
|
+
scheduleSemanticReconcile({ footer: true }, tabContext);
|
|
38746
40769
|
}
|
|
38747
40770
|
|
|
38748
40771
|
async function refreshModels(tabContext = activeTabContext()) {
|
|
@@ -39527,6 +41550,7 @@ function renderCommands() {
|
|
|
39527
41550
|
async function refreshCommands(tabContext = activeTabContext()) {
|
|
39528
41551
|
if (!tabContext.tabId) return;
|
|
39529
41552
|
const response = await api("/api/commands", { tabId: tabContext.tabId });
|
|
41553
|
+
if (!tabs.some((tab) => tab.id === tabContext.tabId)) return;
|
|
39530
41554
|
const catalog = {
|
|
39531
41555
|
raw: normalizeCommands(response.data?.commands || [], { dedupe: false }),
|
|
39532
41556
|
available: normalizeCommands(response.data?.commands || []),
|
|
@@ -39535,6 +41559,7 @@ async function refreshCommands(tabContext = activeTabContext()) {
|
|
|
39535
41559
|
// while this request was in flight. Guided Git must never borrow another
|
|
39536
41560
|
// tab's extension availability or duplicate-command alias.
|
|
39537
41561
|
commandCatalogsByTab.set(tabContext.tabId, catalog);
|
|
41562
|
+
scheduleTabsRender();
|
|
39538
41563
|
if (!isCurrentTabContext(tabContext)) return;
|
|
39539
41564
|
rawAvailableCommands = catalog.raw;
|
|
39540
41565
|
availableCommands = catalog.available;
|
|
@@ -39854,8 +41879,8 @@ function updateServerActionButton() {
|
|
|
39854
41879
|
button.textContent = action === "restart" ? "Restart" : action === "update" || action === "update-all" ? "Update" : action === "stop" ? "Stop" : "Run";
|
|
39855
41880
|
button.classList.toggle("danger", action === "stop");
|
|
39856
41881
|
if (action === "restart") setServerActionStatus("Ready to restart the Web UI server.", "info");
|
|
39857
|
-
else if (action === "update") setServerActionStatus("Ready to
|
|
39858
|
-
else if (action === "update-all") setServerActionStatus("Ready to
|
|
41882
|
+
else if (action === "update") setServerActionStatus("Ready to create and confirm an exact Pi-only update plan.", "info");
|
|
41883
|
+
else if (action === "update-all") setServerActionStatus("Ready to create and confirm an exact combined update plan for eligible Pi, Web UI, and Pi-owned Optional Features.", "info");
|
|
39859
41884
|
else if (action === "stop") setServerActionStatus("Ready to stop the Web UI server.", "info");
|
|
39860
41885
|
else setServerActionStatus();
|
|
39861
41886
|
}
|
|
@@ -39876,19 +41901,25 @@ function resetServerActionControls() {
|
|
|
39876
41901
|
updateServerActionButton();
|
|
39877
41902
|
}
|
|
39878
41903
|
|
|
39879
|
-
async function waitForServerRestart() {
|
|
39880
|
-
|
|
39881
|
-
|
|
39882
|
-
|
|
41904
|
+
async function waitForServerRestart(previousBootIdentity = serverBootIdentity) {
|
|
41905
|
+
const deadline = Date.now() + 90_000;
|
|
41906
|
+
let attempt = 0;
|
|
41907
|
+
while (Date.now() < deadline) {
|
|
41908
|
+
attempt += 1;
|
|
41909
|
+
await delay(attempt === 1 ? 900 : 500);
|
|
41910
|
+
const remainingSeconds = Math.max(0, Math.ceil((deadline - Date.now()) / 1000));
|
|
41911
|
+
const message = `Restarting… waiting for changed server identity (${remainingSeconds}s remaining)`;
|
|
39883
41912
|
setServerActionStatus(message, "warn");
|
|
39884
41913
|
setServerRestartOverlay(true, message);
|
|
39885
41914
|
try {
|
|
39886
|
-
await api("/api/health", { scoped: false });
|
|
41915
|
+
const health = await api("/api/health", { scoped: false });
|
|
41916
|
+
if (!health.bootIdentity || health.bootIdentity === previousBootIdentity) continue;
|
|
41917
|
+
serverBootIdentity = health.bootIdentity;
|
|
39887
41918
|
setBackendOffline(false);
|
|
39888
41919
|
await initializeTabs();
|
|
39889
41920
|
setServerRestartOverlay(false);
|
|
39890
41921
|
setServerActionStatus("Server restarted and reconnected.", "success");
|
|
39891
|
-
addEvent("Pi Web UI server restarted", "warn");
|
|
41922
|
+
addEvent("Pi Web UI server restarted with a changed boot identity", "warn");
|
|
39892
41923
|
return true;
|
|
39893
41924
|
} catch (error) {
|
|
39894
41925
|
setBackendOffline(true, error);
|
|
@@ -39928,7 +41959,7 @@ async function restartServer() {
|
|
|
39928
41959
|
}
|
|
39929
41960
|
|
|
39930
41961
|
setBackendOffline(true, new Error("restart requested from side panel"));
|
|
39931
|
-
const restarted = await waitForServerRestart();
|
|
41962
|
+
const restarted = await waitForServerRestart(serverBootIdentity);
|
|
39932
41963
|
if (elements.serverActionSelect) {
|
|
39933
41964
|
elements.serverActionSelect.disabled = false;
|
|
39934
41965
|
elements.serverActionSelect.value = "";
|
|
@@ -40965,7 +42996,39 @@ function handleInactiveTabEvent(event) {
|
|
|
40965
42996
|
}
|
|
40966
42997
|
}
|
|
40967
42998
|
|
|
42999
|
+
const TRANSCRIPT_STREAM_BARRIER_EVENT_TYPES = new Set([
|
|
43000
|
+
"agent_start",
|
|
43001
|
+
"message_start",
|
|
43002
|
+
"message_end",
|
|
43003
|
+
"tool_execution_start",
|
|
43004
|
+
"tool_execution_end",
|
|
43005
|
+
"agent_end",
|
|
43006
|
+
"agent_settled",
|
|
43007
|
+
"auto_retry_start",
|
|
43008
|
+
"auto_retry_end",
|
|
43009
|
+
"compaction_start",
|
|
43010
|
+
"compaction_end",
|
|
43011
|
+
"webui_output_mode",
|
|
43012
|
+
"pi_process_exit",
|
|
43013
|
+
"pi_process_error",
|
|
43014
|
+
]);
|
|
43015
|
+
|
|
43016
|
+
function dispatchTranscriptStreamEvent(event) {
|
|
43017
|
+
return streamOutputController.dispatch(event, {
|
|
43018
|
+
owner: transcriptStreamOwner(event?.tabId || activeTabId),
|
|
43019
|
+
});
|
|
43020
|
+
}
|
|
43021
|
+
|
|
43022
|
+
function flushTranscriptStreamBarrier(event) {
|
|
43023
|
+
if (!TRANSCRIPT_STREAM_BARRIER_EVENT_TYPES.has(event?.type)) return;
|
|
43024
|
+
streamOutputController.barrier(event.type);
|
|
43025
|
+
reconcileUnknownTranscriptEvidenceAtBarrier(event);
|
|
43026
|
+
if (event.type === "pi_process_exit" || event.type === "pi_process_error") streamOutputController.cancel();
|
|
43027
|
+
}
|
|
43028
|
+
|
|
40968
43029
|
function handleEvent(event) {
|
|
43030
|
+
if (dispatchTranscriptStreamEvent(event)) return;
|
|
43031
|
+
flushTranscriptStreamBarrier(event);
|
|
40969
43032
|
if (event?.type === "webui_session_summary") {
|
|
40970
43033
|
handleSessionSummaryEvent(event);
|
|
40971
43034
|
return;
|
|
@@ -40988,6 +43051,10 @@ function handleEvent(event) {
|
|
|
40988
43051
|
}
|
|
40989
43052
|
if (eventHasTabActivityPayload(event)) ingestEventTabActivity(event);
|
|
40990
43053
|
if (event?.type === "auto_retry_start" || event?.type === "auto_retry_end") trackAutoRetryStateFromEvent(event);
|
|
43054
|
+
// Advance the fallback tool-boundary epoch before inactive-tab routing.
|
|
43055
|
+
// Inactive tool boundaries are still tracked, so their agent_start must own
|
|
43056
|
+
// the same run identity semantics as the foreground tab.
|
|
43057
|
+
if (event?.type === "agent_start") beginToolBoundaryRun(event);
|
|
40991
43058
|
if (eventMayAffectSkillUsage(event)) trackSkillsFromEvent(event);
|
|
40992
43059
|
if (!eventTargetsActiveTab(event)) {
|
|
40993
43060
|
handleInactiveTabEvent(event);
|
|
@@ -41171,9 +43238,8 @@ function handleEvent(event) {
|
|
|
41171
43238
|
if (voiceConversationActiveFor(event.tabId || activeTabId)) voiceConversation.setAssistantActivity({ streaming: true });
|
|
41172
43239
|
setRunIndicatorActivity("Agent run started; waiting for first output or action…");
|
|
41173
43240
|
addEvent("agent started");
|
|
41174
|
-
|
|
41175
|
-
|
|
41176
|
-
renderFeedbackTray();
|
|
43241
|
+
syncLifecycleComposerState({ force: true });
|
|
43242
|
+
scheduleSemanticReconcile({ state: true, footer: true, feedback: true }, tabContext);
|
|
41177
43243
|
break;
|
|
41178
43244
|
case "agent_end":
|
|
41179
43245
|
if (compactOutputActive()) finishCompactLiveOutput(tabContext);
|
|
@@ -41187,9 +43253,7 @@ function handleEvent(event) {
|
|
|
41187
43253
|
}
|
|
41188
43254
|
addEvent("agent run ended; waiting for settlement");
|
|
41189
43255
|
if (runIndicatorIsActive()) setRunIndicatorActivity("Agent run ended; checking for retry or continuation…", { scroll: false });
|
|
41190
|
-
|
|
41191
|
-
scheduleRefreshState();
|
|
41192
|
-
scheduleRefreshFooter();
|
|
43256
|
+
scheduleSemanticReconcile({ messages: true, state: true, footerData: true }, tabContext);
|
|
41193
43257
|
break;
|
|
41194
43258
|
case "message_start":
|
|
41195
43259
|
if (event.message?.role === "assistant") {
|
|
@@ -41198,9 +43262,6 @@ function handleEvent(event) {
|
|
|
41198
43262
|
setRunIndicatorActivity("Starting assistant message…", { scroll: false });
|
|
41199
43263
|
}
|
|
41200
43264
|
break;
|
|
41201
|
-
case "message_update":
|
|
41202
|
-
handleMessageUpdate(event);
|
|
41203
|
-
break;
|
|
41204
43265
|
case "message_end": {
|
|
41205
43266
|
if (compactOutputActive()) finishCompactLiveOutput(tabContext);
|
|
41206
43267
|
streamMessageActive = false;
|
|
@@ -41211,9 +43272,9 @@ function handleEvent(event) {
|
|
|
41211
43272
|
}
|
|
41212
43273
|
streamProviderErrorText = "";
|
|
41213
43274
|
if (runIndicatorIsActive()) setRunIndicatorActivity("Assistant message finished; waiting for the next step…", { scroll: false });
|
|
41214
|
-
|
|
41215
|
-
|
|
41216
|
-
|
|
43275
|
+
// Authoritative message reconciliation derives the todo-progress record;
|
|
43276
|
+
// raw assistant tokens never rebuild widgets.
|
|
43277
|
+
scheduleSemanticReconcile({ messages: true, state: true, footerData: true }, tabContext);
|
|
41217
43278
|
break;
|
|
41218
43279
|
}
|
|
41219
43280
|
case "tool_execution_start":
|
|
@@ -41228,11 +43289,7 @@ function handleEvent(event) {
|
|
|
41228
43289
|
handleToolExecutionStart(event);
|
|
41229
43290
|
}
|
|
41230
43291
|
setRunIndicatorActivity(`Running tool: ${runIndicatorToolName(event.toolName)}…`);
|
|
41231
|
-
addEvent(`tool ${event.toolName} started`, "info", { toolCallId: event.toolCallId });
|
|
41232
|
-
break;
|
|
41233
|
-
case "tool_execution_update":
|
|
41234
|
-
if (!compactOutputActive()) handleToolExecutionUpdate(event);
|
|
41235
|
-
setRunIndicatorActivity(`Running tool: ${runIndicatorToolName(event.toolName)}…`, { scroll: false });
|
|
43292
|
+
if (claimToolBoundaryRecord(event, "log:start")) addEvent(`tool ${event.toolName} started`, "info", { toolCallId: event.toolCallId });
|
|
41236
43293
|
break;
|
|
41237
43294
|
case "tool_execution_end": {
|
|
41238
43295
|
if (voiceConversationActiveFor(event.tabId || activeTabId)) voiceConversation.setAssistantActivity({ toolRunning: false });
|
|
@@ -41246,10 +43303,10 @@ function handleEvent(event) {
|
|
|
41246
43303
|
handleToolExecutionEnd(event);
|
|
41247
43304
|
}
|
|
41248
43305
|
setRunIndicatorActivity(`Tool ${runIndicatorToolName(event.toolName)} ${event.isError ? "failed" : "finished"}; waiting for the agent's next step…`);
|
|
41249
|
-
addEvent(`tool ${event.toolName} ${event.isError ? "failed" : "finished"}`, event.isError ? "error" : "info", { toolCallId: event.toolCallId });
|
|
43306
|
+
if (claimToolBoundaryRecord(event, "log:end")) addEvent(`tool ${event.toolName} ${event.isError ? "failed" : "finished"}`, event.isError ? "error" : "info", { toolCallId: event.toolCallId });
|
|
41250
43307
|
// Compact tool shells deliberately defer rich body construction to the
|
|
41251
43308
|
// final transcript reconciliation; normal mode retains its live card.
|
|
41252
|
-
|
|
43309
|
+
scheduleSemanticReconcile({ footerData: true }, tabContext);
|
|
41253
43310
|
break;
|
|
41254
43311
|
}
|
|
41255
43312
|
case "compaction_start":
|
|
@@ -41269,9 +43326,7 @@ function handleEvent(event) {
|
|
|
41269
43326
|
if (!currentState?.isStreaming) clearRunIndicatorActivity();
|
|
41270
43327
|
markTabOutputSeen();
|
|
41271
43328
|
renderStatus();
|
|
41272
|
-
|
|
41273
|
-
scheduleRefreshMessages();
|
|
41274
|
-
scheduleRefreshFooter();
|
|
43329
|
+
scheduleSemanticReconcile({ state: true, messages: true, footerData: true }, tabContext);
|
|
41275
43330
|
break;
|
|
41276
43331
|
case "agent_settled":
|
|
41277
43332
|
promptRoutingTabs.delete(event.tabId || activeTabId);
|
|
@@ -41288,24 +43343,17 @@ function handleEvent(event) {
|
|
|
41288
43343
|
clearRunIndicatorActivity({ deferRemoval: !autoFollowChat || !isChatNearBottom() });
|
|
41289
43344
|
markTabOutputSeen();
|
|
41290
43345
|
requestGitFooterWebuiPayload(tabContext, { force: true });
|
|
41291
|
-
|
|
41292
|
-
|
|
41293
|
-
|
|
41294
|
-
|
|
41295
|
-
|
|
41296
|
-
|
|
41297
|
-
|
|
41298
|
-
|
|
41299
|
-
|
|
41300
|
-
|
|
41301
|
-
|
|
41302
|
-
loadGitWorkflowMessage({ requireFresh: true, generationId: workflow.messageGenerationId, runId: workflow.runId, tabId: workflowTabId });
|
|
41303
|
-
} else if (workflow?.active && workflow.step === "branchNaming") {
|
|
41304
|
-
loadGitWorkflowBranchName({ requireFresh: true, retries: 3, runId: workflow.runId, tabId: workflowTabId });
|
|
41305
|
-
} else if (workflow?.active && workflow.step === "prGenerating") {
|
|
41306
|
-
loadGitWorkflowPr({ requireFresh: true, retries: 3, runId: workflow.runId, tabId: workflowTabId });
|
|
41307
|
-
}
|
|
41308
|
-
}
|
|
43346
|
+
// Settlement is the one boundary allowed to reconcile the full changed
|
|
43347
|
+
// set; it runs once here through the coalesced semantic scheduler.
|
|
43348
|
+
syncLifecycleComposerState({ force: true });
|
|
43349
|
+
scheduleSemanticReconcile({
|
|
43350
|
+
state: true,
|
|
43351
|
+
messages: true,
|
|
43352
|
+
footerData: true,
|
|
43353
|
+
feedback: true,
|
|
43354
|
+
usage: true,
|
|
43355
|
+
workflow: true,
|
|
43356
|
+
}, tabContext);
|
|
41309
43357
|
break;
|
|
41310
43358
|
case "auto_retry_start": {
|
|
41311
43359
|
const seconds = Math.max(0, Math.ceil(Number(event.delayMs || 0) / 1000));
|
|
@@ -41366,6 +43414,7 @@ function handleEvent(event) {
|
|
|
41366
43414
|
function connectEvents(tabContext = activeTabContext(), { requestedMode = "auto", fallbackAttempted = false } = {}) {
|
|
41367
43415
|
eventSource?.close();
|
|
41368
43416
|
eventSource = null;
|
|
43417
|
+
streamOutputController.cancel();
|
|
41369
43418
|
resetCompactLiveOutput();
|
|
41370
43419
|
activeOutputMode = "normal";
|
|
41371
43420
|
outputModeAcknowledged = false;
|
|
@@ -41395,6 +43444,8 @@ function connectEvents(tabContext = activeTabContext(), { requestedMode = "auto"
|
|
|
41395
43444
|
};
|
|
41396
43445
|
source.onerror = () => {
|
|
41397
43446
|
if (eventSource !== source || !isCurrentTabContext(tabContext)) return;
|
|
43447
|
+
streamOutputController.flush();
|
|
43448
|
+
streamOutputController.cancel();
|
|
41398
43449
|
if (compactOutputActive()) compactLiveScheduler.flushNow();
|
|
41399
43450
|
addEvent("event stream disconnected; browser will retry", "warn");
|
|
41400
43451
|
fetch("/api/health", { cache: "no-store" }).catch((error) => setBackendOffline(true, error));
|
|
@@ -41571,16 +43622,7 @@ elements.newTabMenu?.addEventListener("focusout", () => {
|
|
|
41571
43622
|
elements.newTabCurrentDirectoryButton?.addEventListener("click", () => createTerminalTab(currentDirectoryForNewTab(), { triggerButton: elements.newTabCurrentDirectoryButton }));
|
|
41572
43623
|
elements.newTabChooseDirectoryButton?.addEventListener("click", () => createTerminalTabFromChosenDirectory({ triggerButton: elements.newTabChooseDirectoryButton }));
|
|
41573
43624
|
elements.newTabWorktreeButton?.addEventListener("click", () => openBranchWorktreePicker());
|
|
41574
|
-
elements.splitTabButton?.addEventListener("click", () => splitActiveTerminalTab());
|
|
41575
43625
|
elements.workspaceSaveButton?.addEventListener("click", () => saveWebuiWorkspace());
|
|
41576
|
-
const openActiveSessionSummary = () => {
|
|
41577
|
-
void openSessionSummaryForTab().catch((error) => addEvent(error.message || String(error), "error"));
|
|
41578
|
-
};
|
|
41579
|
-
elements.summaryHeaderButton?.addEventListener("click", openActiveSessionSummary);
|
|
41580
|
-
elements.summaryActionButton?.addEventListener("click", () => {
|
|
41581
|
-
setComposerActionsOpen(false);
|
|
41582
|
-
openActiveSessionSummary();
|
|
41583
|
-
});
|
|
41584
43626
|
elements.terminalSplitCloseButton?.addEventListener("click", () => closeTerminalSplitView());
|
|
41585
43627
|
elements.closeAllTabsButton.addEventListener("click", () => closeAllTerminalTabs());
|
|
41586
43628
|
elements.commandPaletteButton?.addEventListener("click", () => openCommandPalette());
|
|
@@ -41706,6 +43748,17 @@ optionsMenuContainer?.addEventListener("focusout", () => {
|
|
|
41706
43748
|
if (!optionsMenuContainer?.contains(document.activeElement)) setOptionsMenuOpen(false);
|
|
41707
43749
|
}, 0);
|
|
41708
43750
|
});
|
|
43751
|
+
elements.optionsMenuButton.addEventListener("keydown", (event) => {
|
|
43752
|
+
if (event.key !== "ArrowDown" && event.key !== "ArrowUp") return;
|
|
43753
|
+
event.preventDefault();
|
|
43754
|
+
setPublishMenuOpen(false);
|
|
43755
|
+
setNativeCommandMenuOpen(false);
|
|
43756
|
+
setAppRunnerMenuOpen(false);
|
|
43757
|
+
setOptionsMenuOpen(true);
|
|
43758
|
+
const items = optionsMenuRootItems();
|
|
43759
|
+
focusOptionsMenuItem(event.key === "ArrowDown" ? items[0] : items[items.length - 1]);
|
|
43760
|
+
});
|
|
43761
|
+
initializeOptionsSubmenus();
|
|
41709
43762
|
elements.releaseNpmButton.addEventListener("click", () => runPublishWorkflow("/release-npm"));
|
|
41710
43763
|
elements.releaseAurButton.addEventListener("click", () => runPublishWorkflow("/release-aur"));
|
|
41711
43764
|
elements.nativeSkillsButton.addEventListener("click", () => runNativeCommandMenu("/skills"));
|
|
@@ -42058,6 +44111,8 @@ function resetAbortLongPressAffordance() {
|
|
|
42058
44111
|
async function abortActiveRun({ source = "button" } = {}) {
|
|
42059
44112
|
if (abortRequestInFlight || !isAbortAvailable()) return;
|
|
42060
44113
|
const tabContext = activeTabContext();
|
|
44114
|
+
streamOutputController.barrier("user-abort");
|
|
44115
|
+
reconcileUnknownTranscriptEvidenceAtBarrier({ type: "user_abort", tabId: tabContext.tabId });
|
|
42061
44116
|
abortRequestInFlight = true;
|
|
42062
44117
|
resetAbortLongPressAffordance();
|
|
42063
44118
|
updateComposerModeButtons();
|
|
@@ -42254,6 +44309,33 @@ elements.themeSchemeToggle?.querySelectorAll("[data-scheme-mode]").forEach((butt
|
|
|
42254
44309
|
setThemeSchemeMode(button.dataset.schemeMode, { announce: true }).catch((error) => addEvent(error.message || String(error), "error"));
|
|
42255
44310
|
});
|
|
42256
44311
|
});
|
|
44312
|
+
elements.themeCustomizeButton?.addEventListener("click", () => openThemeCustomizer().catch((error) => addEvent(error.message || String(error), "error")));
|
|
44313
|
+
elements.themeCustomizerName?.addEventListener("input", updateThemeCustomizerFromVisual);
|
|
44314
|
+
elements.themeCustomizerScope?.addEventListener("change", () => {
|
|
44315
|
+
invalidateThemeCustomizerOverwrite();
|
|
44316
|
+
updateThemeCustomizerActions();
|
|
44317
|
+
});
|
|
44318
|
+
elements.themeCustomizerThinkingMax?.addEventListener("input", updateThemeCustomizerFromVisual);
|
|
44319
|
+
elements.themeCustomizerVars?.addEventListener("input", updateThemeCustomizerFromVisual);
|
|
44320
|
+
elements.themeCustomizerJson?.addEventListener("input", updateThemeCustomizerFromJson);
|
|
44321
|
+
elements.themeCustomizerCancelButton?.addEventListener("click", () => closeThemeCustomizer({ restore: true }));
|
|
44322
|
+
elements.themeCustomizerResetButton?.addEventListener("click", resetThemeCustomizerDraft);
|
|
44323
|
+
elements.themeCustomizerSaveButton?.addEventListener("click", () => saveThemeCustomizer().catch((error) => setThemeCustomizerStatus(error.message || String(error), "error")));
|
|
44324
|
+
elements.themeCustomizerOverwriteButton?.addEventListener("click", () => saveThemeCustomizer({ overwrite: true }).catch((error) => setThemeCustomizerStatus(error.message || String(error), "error")));
|
|
44325
|
+
elements.themeCustomizerDialog?.addEventListener("cancel", (event) => {
|
|
44326
|
+
event.preventDefault();
|
|
44327
|
+
if (themeCustomizerState?.saving) {
|
|
44328
|
+
setThemeCustomizerStatus("Wait for the theme save to finish before closing.", "warn");
|
|
44329
|
+
return;
|
|
44330
|
+
}
|
|
44331
|
+
closeThemeCustomizer({ restore: true });
|
|
44332
|
+
});
|
|
44333
|
+
elements.themeCustomizerDialog?.addEventListener("close", () => {
|
|
44334
|
+
const state = themeCustomizerState;
|
|
44335
|
+
if (!state || state.closing) return;
|
|
44336
|
+
restoreThemeCustomizerOpeningState(state.generation);
|
|
44337
|
+
themeCustomizerState = null;
|
|
44338
|
+
});
|
|
42257
44339
|
if (elements.backgroundChooseButton && elements.backgroundInput) {
|
|
42258
44340
|
elements.backgroundChooseButton.addEventListener("click", () => elements.backgroundInput.click());
|
|
42259
44341
|
elements.backgroundInput.addEventListener("change", () => {
|
|
@@ -42357,6 +44439,24 @@ elements.subagentLaunchSlotsLater?.addEventListener("click", () => {
|
|
|
42357
44439
|
setSubagentLaunchSlotAnnouncement("Agent models are saved. Reload this tab later before relying on them for future launches.");
|
|
42358
44440
|
renderSubagentLaunchSlots();
|
|
42359
44441
|
});
|
|
44442
|
+
elements.applySamplingParametersButton?.addEventListener("click", () => {
|
|
44443
|
+
applySamplingParameters().catch((error) => {
|
|
44444
|
+
setSamplingParametersFeedback({ error: error.message || String(error) });
|
|
44445
|
+
renderSamplingParameters();
|
|
44446
|
+
});
|
|
44447
|
+
});
|
|
44448
|
+
elements.resetSamplingParametersButton?.addEventListener("click", () => {
|
|
44449
|
+
resetSamplingParameters().catch((error) => {
|
|
44450
|
+
setSamplingParametersFeedback({ error: error.message || String(error) });
|
|
44451
|
+
renderSamplingParameters();
|
|
44452
|
+
});
|
|
44453
|
+
});
|
|
44454
|
+
elements.reloadSamplingParametersButton?.addEventListener("click", () => {
|
|
44455
|
+
loadSamplingParameters({ force: true }).catch((error) => {
|
|
44456
|
+
setSamplingParametersFeedback({ error: error.message || String(error) });
|
|
44457
|
+
renderSamplingParameters();
|
|
44458
|
+
});
|
|
44459
|
+
});
|
|
42360
44460
|
elements.subagentTerminalCopyButton?.addEventListener("click", () => copySubagentTerminalOutput());
|
|
42361
44461
|
elements.subagentTerminalRefreshButton?.addEventListener("click", () => {
|
|
42362
44462
|
refreshSubagentTerminalView(activeSubagentTerminalId, { showLoading: true }).finally(() => scheduleSubagentTerminalRefresh());
|
|
@@ -42473,6 +44573,9 @@ document.addEventListener("pointerdown", (event) => {
|
|
|
42473
44573
|
if (elements.sidePanelContextMenu && !elements.sidePanelContextMenu.hidden && !event.target?.closest?.(".side-panel-context-menu")) {
|
|
42474
44574
|
closeSidePanelContextMenu();
|
|
42475
44575
|
}
|
|
44576
|
+
if (elements.gitFooterContextMenu && !elements.gitFooterContextMenu.hidden && !event.target?.closest?.(".git-footer-context-menu")) {
|
|
44577
|
+
closeGitFooterContextMenu();
|
|
44578
|
+
}
|
|
42476
44579
|
}, { passive: true });
|
|
42477
44580
|
document.addEventListener("pointermove", (event) => {
|
|
42478
44581
|
if (openTerminalTabGroupKey && !event.target?.closest?.(".terminal-tab-group")) {
|
|
@@ -42685,6 +44788,10 @@ window.addEventListener("offline", () => {
|
|
|
42685
44788
|
window.addEventListener("beforeunload", persistMobileContinuityState);
|
|
42686
44789
|
window.addEventListener("storage", (event) => {
|
|
42687
44790
|
if (event.key === OPTIONAL_FEATURES_STORAGE_KEY) reconcileDisabledOptionalFeaturesFromStorage();
|
|
44791
|
+
if (event.key === OPTIONAL_FEATURE_MIGRATION_DISMISS_STORAGE_KEY && optionalFeatureMigrationCompletionIsDismissed()) {
|
|
44792
|
+
optionalFeatureRestartNotice = null;
|
|
44793
|
+
renderOptionalFeatureMigrationSurface();
|
|
44794
|
+
}
|
|
42688
44795
|
if (event.key === SIDE_PANEL_SECTION_VISIBILITY_STORAGE_KEY) restoreSidePanelSectionVisibility();
|
|
42689
44796
|
if (event.key === SIDE_PANEL_SECTION_ORDER_STORAGE_KEY) restoreSidePanelSectionOrder();
|
|
42690
44797
|
if (event.key === COMPOSER_ACTION_ORDER_STORAGE_KEY) restoreComposerActionOrder();
|
|
@@ -42915,6 +45022,30 @@ elements.sidePanelContextMenu?.addEventListener("keydown", (event) => {
|
|
|
42915
45022
|
items[event.key === "Home" ? 0 : items.length - 1]?.focus({ preventScroll: true });
|
|
42916
45023
|
}
|
|
42917
45024
|
});
|
|
45025
|
+
elements.gitFooterContextMenu?.addEventListener("keydown", (event) => {
|
|
45026
|
+
const items = [...elements.gitFooterContextMenu.querySelectorAll('[role="menuitem"]:not([disabled])')];
|
|
45027
|
+
const index = items.indexOf(document.activeElement);
|
|
45028
|
+
if (event.key === "Escape") {
|
|
45029
|
+
event.preventDefault();
|
|
45030
|
+
closeGitFooterContextMenu();
|
|
45031
|
+
} else if (event.key === "ArrowDown" || event.key === "ArrowUp") {
|
|
45032
|
+
event.preventDefault();
|
|
45033
|
+
const direction = event.key === "ArrowDown" ? 1 : -1;
|
|
45034
|
+
items[(Math.max(0, index) + direction + items.length) % items.length]?.focus({ preventScroll: true });
|
|
45035
|
+
} else if (event.key === "Home" || event.key === "End") {
|
|
45036
|
+
event.preventDefault();
|
|
45037
|
+
items[event.key === "Home" ? 0 : items.length - 1]?.focus({ preventScroll: true });
|
|
45038
|
+
}
|
|
45039
|
+
});
|
|
45040
|
+
elements.gitFooterContextMenu?.addEventListener("click", (event) => {
|
|
45041
|
+
const button = event.target?.closest?.("[data-git-footer-menu-action]");
|
|
45042
|
+
const state = gitFooterContextMenuState;
|
|
45043
|
+
if (!button || !state) return;
|
|
45044
|
+
const action = button.dataset.gitFooterMenuAction;
|
|
45045
|
+
closeGitFooterContextMenu({ returnFocus: action !== "visibility" });
|
|
45046
|
+
if (action === "disable") void disableGitFooterContextChip(state.key, state.label);
|
|
45047
|
+
else if (action === "visibility") openGitFooterVisibilityDialog();
|
|
45048
|
+
});
|
|
42918
45049
|
elements.fileContextMenu?.addEventListener("click", (event) => {
|
|
42919
45050
|
const button = event.target?.closest?.("[data-file-menu-action]");
|
|
42920
45051
|
if (!button) return;
|
|
@@ -43110,8 +45241,14 @@ elements.optionalFeatureMigrationDialog?.addEventListener("cancel", (event) => {
|
|
|
43110
45241
|
});
|
|
43111
45242
|
|
|
43112
45243
|
installModalPrimitives();
|
|
45244
|
+
installMiddleButtonDragScroll({
|
|
45245
|
+
onDirection: ({ target, offsetY }) => {
|
|
45246
|
+
if (target === elements.chat) noteChatUserScrollIntent({ type: "middle-drag", deltaY: offsetY });
|
|
45247
|
+
},
|
|
45248
|
+
});
|
|
43113
45249
|
initializeIssueWizard();
|
|
43114
45250
|
resizePromptInput();
|
|
45251
|
+
clearRemovedSidePanelSectionHeightState();
|
|
43115
45252
|
restoreDurableUiLayoutPendingJournal();
|
|
43116
45253
|
restoreSidePanelWidthPreference();
|
|
43117
45254
|
restoreFileViewerWidthPreference();
|
|
@@ -43155,6 +45292,7 @@ initializeCodexUsage();
|
|
|
43155
45292
|
initializeClaudeUsage();
|
|
43156
45293
|
initializeSubagents();
|
|
43157
45294
|
initializeSubagentLaunchSlots();
|
|
45295
|
+
initializeSamplingParameters();
|
|
43158
45296
|
initializeUpdateNotifications();
|
|
43159
45297
|
bindMobileViewChanges();
|
|
43160
45298
|
bindSidePanelOverlayViewChanges();
|